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

関数内からプロセスを開始しようとしていませんでしたが、同じエラーが発生していました。それが私のお気に入りの時間の浪費の 1 つである、UAC トラップであることに気付くのに数分かかりました。「管理者として実行」を使用して PowerShell を開始していませんでした。所有していないプロセスを開始/停止/変更するには、管理者権限を持ってコードを実行する必要があり、このエラーメッセージはこの点でまったく役に立ちません。

于 2014-09-25T20:28:35.583 に答える