![](/img/trans.png)
[英]Powershell: Exception calling “AttachDatabase” with “3” argument(s)
[英]PowerShell Exception calling “Start” with “0” argument(s) from within another function
我正在編寫我的第一個 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
我沒有嘗試從函數內部啟動進程,但我遇到了同樣的錯誤。 我花了幾分鍾才意識到這是我最喜歡的浪費時間之一:UAC 陷阱。 我沒有使用“以管理員身份運行”啟動 PowerShell。 您必須具有管理員權限並運行代碼以啟動/停止/修改您不擁有的進程,並且此錯誤消息在這方面完全沒有幫助。
您必須按如下方式調用 run:
Run "ping","208.67.222.222","",""
放在括號之間將它作為單個數組參數傳遞給函數。
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"
我在服務上的 start() 函數中遇到此錯誤,因為一位同事在 Windows 服務窗口中將該服務設置為“已禁用”。 將其設置回“手動”修復了它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.