【发布时间】:2018-01-17 03:44:51
【问题描述】:
我有一个 powershell 脚本,它为给定文件吐出文件信息。该脚本在 Windows 服务的进程中执行,如下所示:
Process p = new Process();
ProcessStartInfo s = new ProcessStartInfo();
s.FileName = "powershell.exe";
s.Arguments = "./script.ps1";
s.RedirectStandardOutput = true;
s.RedirectStandardError = true;
s.UseShellExecute = false;
s.CreateNoWindow = true;
p.StartInfo = s;
p.EnableRaisingEvents = true;
/* ... defined output handlers ... */
p.Start();
p.BeginOutputReadLine();
p.BeginErrorReadLine();
powershell脚本如下:
function ChangeDir($dir)
{
try
{
echo ("Attempting to change directory: {0}" -f ($dir))
Set-Location -Path $dir -ErrorAction Stop
}
catch
{
echo $error[0].Exception
}
}
function OutputFileInfo($filePath)
{
try
{
echo ("Attempting to read file: {0}" -f ($filePath))
$file = @(Get-ChildItem $filePath -ErrorAction Stop)
for ($i = 0; $i -lt $file.Count; $i++)
{
echo ("{0},{1}" -f ($file[$i].Name, $file[$i].Length))
}
}
catch
{
echo $error[0].Exception
}
}
ChangeDir "/Windows/System32/drivers"
OutputFileInfo "tcpip.sys"
从命令行运行 powershell 脚本时的输出与我预期的一样:
Attempting to change directory: /Windows/System32/drivers
Attempting to read file: tcpip.sys
tcpip.sys,2773400
当脚本通过 windows 服务执行时,输出如下:
Attempting to change directory: /Windows/System32/drivers
Attempting to read file: tcpip.sys
Cannot find path 'C:\Windows\System32\drivers\tcpip.sys' because it does not exist.
对于其他文件,它可以在命令行和服务中完美运行。它是否与以 SYSTEM 身份运行 powershell 脚本的服务有关,该服务以某种方式无法访问该文件?虽然如果是这种情况,我会期望出现权限错误而不是找不到文件错误。
【问题讨论】:
标签: c# powershell service