【问题标题】:powershell script unable to locate certain files when executed from a windows service从 Windows 服务执行时,powershell 脚本无法找到某些文件
【发布时间】: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


    【解决方案1】:

    好的....这是因为在 64 位机器上运行的 32 位应用程序无法访问 system32/drivers,而且我没有意识到我在 Visual Studio 中将我的应用程序设置为默认值,我猜是 32 位。我将其更改为 64 位,它现在可以在服务中使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-23
      • 1970-01-01
      • 2019-01-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多