【发布时间】:2021-02-24 19:50:34
【问题描述】:
我有一个作为本地系统运行的 Windows 服务 (C#)。 我希望能够读取我的数据库并运行 PowerShell 命令和脚本。 我能够运行大多数脚本,但我的测试机器挂在这台机器上:
NET USE Z: /Delete /y
NET USE Z: \\TEST2\ProgramData
我可以在计算机上运行这些命令并且一切正常,但是当我尝试从我的 Windows 服务中运行这些命令时,它会手动运行脚本。
private static bool RunPSCommand(string command, out string output)
{
// create Powershell runspace
Runspace runspace = RunspaceFactory.CreateRunspace();
// open it
runspace.Open();
// create a pipeline and feed it the script text
Pipeline pipeline = runspace.CreatePipeline();
pipeline.Commands.AddScript(command);
// add an extra command to transform the script output objects into nicely formatted strings
// remove this line to get the actual objects that the script returns. For example, the script
// "Get-Process" returns a collection of System.Diagnostics.Process instances.
pipeline.Commands.Add("Out-String");
// execute the script
try
{
StringBuilder stringBuilder = new StringBuilder();
Collection<PSObject> results = pipeline.Invoke();
if (pipeline.HadErrors)
{
var errors = pipeline.Error.ReadToEnd();
foreach (object error in errors)
{
stringBuilder.AppendLine(error.ToString());
}
}
// close the runspace
runspace.Close();
// convert the script result into a single string
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
output = stringBuilder.ToString();
return true;
}
catch (CommandNotFoundException e)
{
output = e.Message;
return false;
}
catch (Exception e)
{
output = e.Message;
return false;
}
}
我不知道为什么这么难。三天来,我一直在努力解决这个问题,并尝试了从网络使用到 DOM 对象的所有选项
NET USE Z: /Delete /y
(New-Object -Com WScript.Network).MapNetworkDrive("z:" , "\\test2\programdata")
【问题讨论】:
-
这里有很多关于可以做什么和不可以做什么的讨论,以及解决服务中映射驱动器问题的一些创造性方法:stackoverflow.com/questions/182750/…
-
我不想为服务使用映射驱动器,我希望服务为另一个进程使用驱动器映射。
-
我认为问题本质上是相同的——无论是使用驱动器本身还是为其他驱动器创建。 LOCALSYSTEM 不是网络凭证,它只是本地凭证,所以当您尝试这样做时,
NET USE没有任何东西可以使用!我在这里推测了一下,但挂起可能是NET USE试图在没有现有交互式会话的情况下提示用户的结果。你试过NET USE Z: \\TEST2\ProgramData /username:myuser mypassword吗? -
我在 powershell 中尝试了 net use z: \\test2\programdata /u:dev1\administrator 密码,但没有成功。我在 powershell 中尝试了 net use z: \\test2\programdata /u:test2\test 密码,但它不起作用。这两台计算机是工作组的一部分,而不是网络,所以我尝试指定计算机\用户帐户以查看是否可行。然后,我从我在 powershell 中的测试中删除了用户名和密码,它工作了,但是当我回到尝试通过服务来做它时,它没有工作。
-
好吧,因为你在一个工作组而不是一个域中,所以我不太喜欢我的元素,你的经历让我走上了陌生的道路......有两件事要尝试。首先,也是最简单的,创建一个不是
LOCALSYSTEM的服务帐户。授予它所需的权限,包括远程共享。以该用户身份登录,并验证您是否可以执行NET USE。如果一切正常,请将服务配置为使用该服务帐户。其次,您不会喜欢这样 - 经历将其配置为交互式服务的麻烦,因此您可能会看到它挂起的原因。可能正在输入。
标签: c# powershell windows-services