使用网络路径的bat文件和Windows服务,凭据问题

时间:2016-09-13 09:26:23

标签: batch-file cmd path windows-services

你好吗?我的凭据有问题,我不知道如何在bat文件中传递密码和用户。请阅读上下文。

我创建了一个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过程时,它也会获取凭据。

由于

1 个答案:

答案 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=没有。