2

我正在编写我的第一个 Powershell 脚本并且来自 C# 我很困惑,我的代码如下:

function Run(
[string] $command,
[string] $args,
[Ref] [string] $stdout,
[Ref] [string] $stderr
)
{  
    $p1 = New-Object System.Diagnostics.Process
    $p1.StartInfo = New-Object System.Diagnostics.ProcessStartInfo;
    $p1.StartInfo.FileName = $command
    $p1.StartInfo.Arguments = $arguments
    $p1.StartInfo.CreateNoWindow = $true
    $p1.StartInfo.RedirectStandardError = $true
    $p1.StartInfo.RedirectStandardOutput = $true
    $p1.StartInfo.UseShellExecute = $false

    $p1.Start()
    $p1.WaitForExit()
}

$p = New-Object System.Diagnostics.Process
$p.StartInfo = New-Object System.Diagnostics.ProcessStartInfo;
$p.StartInfo.FileName = "ping"
$p.StartInfo.Arguments = "142.553.22242.2"
$p.StartInfo.CreateNoWindow = $true
$p.StartInfo.RedirectStandardError = $true
$p.StartInfo.RedirectStandardOutput = $true
$p.StartInfo.UseShellExecute = $false

$p.Start()
$p.WaitForExit()
$code = $p.ExitCode
$stderr = $p.StandardError.ReadToEnd()
$stdout = $p.StandardOutput.ReadToEnd()


Run("ping","208.67.222.222","","")

$p.Start() 有效,但由于某种原因,传递给 Run 函数的参数被忽略并且 $p1 失败。请问我做错了什么?

Exception calling "Start" with "0" argument(s): "The system cannot find the file specified"
At C:\Users\Administrator\Desktop\logtofile.ps1:27 char:5
+     $p1.Start()
+     ~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : Win32Exception

Exception calling "WaitForExit" with "0" argument(s): "No process is associated with this object."
At C:\Users\Administrator\Desktop\logtofile.ps1:28 char:5
+     $p1.WaitForExit()
+     ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : InvalidOperationException
4

4 回答 4

4

我没有尝试从函数内部启动进程,但我遇到了同样的错误。我花了几分钟才意识到这是我最喜欢的浪费时间的方法之一:UAC 陷阱。我没有使用“以管理员身份运行”启动 PowerShell。您必须具有管理员权限并运行代码以启动/停止/修改您不拥有的进程,并且此错误消息在这方面完全没有帮助。

于 2014-09-25T20:28:35.583 回答
3

您必须按如下方式调用 run:

Run "ping","208.67.222.222","",""

放在括号之间将其作为单个数组参数传递给函数。

于 2013-04-13T17:22:48.210 回答
0
function Demo  {
    param (
        $fileName,$Arguments
    )

    $p = New-Object System.Diagnostics.Process
    $p.StartInfo = New-Object System.Diagnostics.ProcessStartInfo
    $p.StartInfo.FileName = $fileName
    $p.StartInfo.RedirectStandardError = $true
    $p.StartInfo.RedirectStandardOutput = $true
    $p.StartInfo.UseShellExecute = $false
    $p.StartInfo.Arguments = $Arguments
    $p.Start() | Out-Null
    $p.WaitForExit()

    $stdout = $p.StandardOutput.ReadToEnd()
    $stderr = $p.StandardError.ReadToEnd()
    Write-Host "stdout: $stdout"
    Write-Host "stderr: $stderr"
    Write-Host "exit code: " + $p.ExitCode
}

Demo "getmac" " /v"
于 2020-12-29T04:04:12.540 回答
0

我在服务上的 start() 函数中出现此错误,因为同事在 Windows 服务窗口中将该服务设置为“禁用”。将其设置回“手动”修复它。

于 2021-07-22T13:08:07.470 回答