bat 文件和具有网络路径的 windows 服务,凭证问题

bat file and windows services with network path, problems with credentials

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

我创建了一个 windows 服务,它从一个 bat 文件中获取一些配置值,使用 args parameter.This 服务在所需位置写入一个 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
                                     }
     }

写文件程序:

//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

**问题是我收到一个错误:"The user name or password is incorrect".

你能帮帮我吗?我尝试做所有 Whosebug 的答案,比如 ,等等。但是没有用。

我想在bat中插入用户和密码。因此,在调用 File.WriteAllText 过程时,它也需要凭据。

谢谢

据我所知,File.WriteAllText 过程是由服务 运行 执行的,但它没有写入目标文件的凭据。所以您想使用执行此类任务所需的凭据启动服务。

您可以使用 sc 命令的 obj=password= 开关为服务设置凭据,如

@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 期望 = 符号后面有一个 space,而您的 binPath= 没有。