function Get-WSLIP {
wsl -- ip -o -4 -json addr list eth0 `
| ConvertFrom-Json `
| %{ $_.addr_info.local } `
| ?{ $_ }
}
我有這個函式,我想作為安裝了 WSL 的不同用戶運行,并通過將此函式分配給變數來捕獲輸出。
我試過了runas,但它似乎想打開第二個行程,但我無法捕捉到輸出。
uj5u.com熱心網友回復:
使用不同的用戶身份啟動行程總是會在 Windows 上的新視窗中啟動該行程,這意味著您無法直接捕獲該行程的輸出。
您有兩個選擇:
System.Diagnostics.Process直接使用API,它允許您通過類的(和)屬性在記憶體中捕獲行程的輸出,作為文本。.RedirectStandardOutput.RedirectStandardErrorSystem.Diagnostics.ProcessStartInfo這種方法很重要,特別是如果您還想在沒有死鎖風險的情況下捕獲stderr輸出;一個標準輸出,只輸出-capturing解決方案中可以找到這個答案。
它排除了行程hidden 的運行,因為使用另一個用戶的憑據(
.UserName和.PassWord屬性)需要.UseShellExecute是$false,這反過來意味著該.WindowStyle屬性被忽略。
使用
Start-Process,如果你想(選項)運行程序中隱藏的,雖然這需要使用的臨時檔案,以捕獲輸出:陷阱:您必須確保目標用戶具有權限:
- 訪問新啟動行程的 作業目錄,這需要傳遞一個合適的目錄給
-WorkingDirectory - 寫入傳遞給
-RedirectStandardOutput/的(臨時)檔案路徑-RedirectStandardError。
- 訪問新啟動行程的 作業目錄,這需要傳遞一個合適的目錄給
需要注意的是
-RedirectStandardOutput/-RedirectStandardError捕獲從命名流輸出分開,而且必須是獨立的檔案。如果要合并流并將它們交錯捕獲到單個檔案中,則必須通過shell(例如 PowerShell 或cmd.exe)啟動行程并使用其流合并功能,通常是2>&1.
以下Start-Process基于解決方案顯示了如何運行隱藏的行程并捕獲 stdout 輸出(僅):
# Prompt for the target user's credentials.
$cred = Get-Credential
# Determine the working directory and temporary file path.
# IMPORTANT: THE TARGET USER MUST HAVE PERMISSION TO
# * ACCESS the working directory
# * access and WRITE TO the temp file.
$workingDir = "$env:SystemRoot\Temp"
$tmpFile = Join-Path "$env:SystemRoot\Temp" "~$PID.tmp"
# Launch the process as the target user, hidden, save its stdout
# to the temporary file, and wait for it to terminate.
(Start-Process -WindowStyle Hidden -PassThru -WorkingDirectory $workingDir -RedirectStandardOutput $tmpFile -Credential $cred powershell.exe @'
-noprofile -command
"[array] (wsl -- ip -o -4 -json addr list eth0 | ConvertFrom-Json).addr_info.local -ne ''"
'@).WaitForExit()
# Get the captured output and remove the temp. file.
$output = Get-Content $tmpFile; Remove-Item $tmpFile
# Print the captured result
$output
筆記:
上面的
powershell.exeCLI呼叫使用了問題中命令的簡化版本。雖然
Start-Process有一個專用-Wait開關來等待啟動的行程終止,但從 PowerShell Core 7.2 開始,它似乎與 不兼容-Credential,即以不同的用戶身份運行(導致在Access denied啟動行程時出錯,盡管是異步的)。- 解決方法是使用
-PassThru,以便使通常無輸出Start-Process的System.Diagnostics.Process實體發出描述已啟動行程的實體,并呼叫.WaitForExit()該實體。
- 解決方法是使用
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/345218.html
標籤:电源外壳
上一篇:連接檔案夾的輸出
