我创建了一个Windows服务,它使用args参数从bat文件中获取一些配置值。该服务将txt文件写入所需位置,但是 在这里,您是我的Windows服务的一些基本代码:
static void Main(string[] args)
{ //args comes from the bat file
CmdLineArgs cmdArgs = new CmdLineArgs(args);
//pass the values for mydirectory from args
AppConfig.NetworkDirectory = cmdArgs.GetArg("/mydirectory");
writefile(AppConfig.NetworkDirectory,"text for file");
if(couldntwriteinpath())
{ //...manage error
}
}
writefile过程:
//this is a very simple way of doing this, so you can have an idea of what is going on
public static void writefile(string path, string text)
{ string savepathname=path+"\myfile.txt";
//uses the class File.writealltext function
File.WriteAllText(savepathname, text);
}
bat文件:
cd C:\Windows\System32
sc.exe stop MyService
sc.exe delete MyService
timeout 3
sc.exe create MyService binPath="\"C:\apps\MyService\MyService.exe\" /mydirectory"\\192.168.90.x\homes\writefolder\"" start= auto
sc.exe start MyService
PAUSE
**问题是我收到错误:"用户名或密码错误"。
你能帮帮我吗?我试图做所有stackoverflow答案,如https://stackoverflow.com/questions/3854026/how-to-give-credentials-in-a-batch-script-that-copies-files-to-a-network-locatio,https://stackoverflow.com/questions/303045/connecting-to-a-network-folder-with-username-password-in-powershell等,但没有用。我想在bat中插入用户和密码。因此,在调用File.WriteAllText过程时,它也会获取凭据。
由于
答案 0 :(得分:0)
如果我理解,File.WriteAllText
过程由服务运行,但它没有写入目标文件的凭据。因此,您希望使用执行此类任务所需的凭据来启动服务。
您可以使用obj=
命令的password=
和sc
开关设置服务凭据,如
@echo off
pushd %__APPDIR__% & rem cd C:\Windows\System32
setlocal
set "user=system\username"
set "pass=p@ssword"
sc.exe stop MyService
sc.exe delete MyService
timeout 3
sc.exe create MyService binPath="\"C:\apps\MyService\MyService.exe\" /mydirectory"\\192.168.90.x\homes\writefolder\"" start= auto obj= "%user%" password= "%pass%"
sc.exe start MyService
endlocal
popd
PAUSE
exit/B
注意:不确定它是否适合您,通常sc switches
期望=符号后面留有空格,而binPath=
没有。