[英]How can I map a network drive from a Windows Service
I have a windows service (C#) running as Local System.我有一个 windows 服务 (C#) 作为本地系统运行。 I want to be able to read my database and run PowerShell commands and scripts.
我希望能够读取我的数据库并运行 PowerShell 命令和脚本。 I am able to run most scripts but my test machine is hanging on this one:
我能够运行大多数脚本,但我的测试机挂在这个上:
NET USE Z: /Delete /y
NET USE Z: \\TEST2\ProgramData
I can run these commands on the computer and it all works but when I try to run these commands from within my Windows Service it hands on the line which runs the script.我可以在计算机上运行这些命令并且一切正常,但是当我尝试从我的 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;
}
}
I am not sure why this is so difficult.我不确定为什么这如此困难。 I have been wracking my head on this one for three days and trying every option from net use to DOM objects
三天以来,我一直在努力解决这个问题,并尝试了从网络使用到 DOM 对象的所有选项
NET USE Z: /Delete /y
(New-Object -Com WScript.Network).MapNetworkDrive("z:" , "\\test2\programdata")
I was attempting to do this from a service but switched to an application running on a user session.我试图从服务中执行此操作,但切换到在用户 session 上运行的应用程序。 It works this way.
它以这种方式工作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.