[英]Powershell GUI - Output to textbox from Invoke-Command function
我正在將整個環境的當前備份解決方案轉換為 Powershell GUI 應用程序。 我的腳本按預期工作,但現在我正在嘗試將 output 顯示到我的 GUI 文本框字段。
我試圖顯示的 output 位於Invoke-Command
腳本塊的 function 內。 這是我的代碼片段:
function ZipFiles {
Invoke-Command -ComputerName $servers -ScriptBlock {
# Store the server name in a variable
$hostname = hostname
# Specify the 7zip executable path
$7zipPath = "$env:ProgramFiles\7-Zip\7z.exe"
# Throw an error if 7zip is not installed on the server
if (-not (Test-Path -Path $7zipPath -PathType Leaf)) {
throw "7 zip file '$7zipPath' not found on $hostname"
$7zipInstalled = $false
}
# Confirm that 7zip is installed on the remote server
else {
$7zipInstalled = $true
Write-Host -ForegroundColor Cyan "7zip found on $hostname. Zipping files..."
我從 XAML 文件導入我的布局,我的TextBox
項目存儲在名為$var_textInfo
的變量下。 由於此變量在我的 Invoke-Command 塊之外,因此我需要using:$var_textInfo
語法調用它。
我嘗試使用以下命令將Write-Host
行替換為 output 結果到文本框:
$using:var_textInfo.AppendText("7zip found on $hostname. Zipping files...")
但是,Powershell 似乎不允許我使用 using 表達式調用方法。 它拋出以下錯誤消息:
Using 表達式中不允許使用表達式。
知道我如何正確地將Invoke-Command
function 中的文本 output 發送到我的文本框嗎?
提前感謝您的想法!
我需要使用 using:$var_textInfo 語法調用它
不,你不知道。 Invoke-Command
腳本塊在遠程機器上運行,無法訪問您的本地 GUI 對象。 通常,您不能將活動對象傳遞給遠程腳本,只能傳遞可以序列化的數據。
相反,pipe Invoke-Command
到ForEach-Object
並從那里更新您的 GUI(本地):
Invoke-Command -ComputerName $servers -ScriptBlock {
# Store the server name in a variable
$hostname = hostname
# Specify the 7zip executable path
$7zipPath = "$env:ProgramFiles\7-Zip\7z.exe"
# Throw an error if 7zip is not installed on the server
if (-not (Test-Path -Path $7zipPath -PathType Leaf)) {
throw "7 zip file '$7zipPath' not found on $hostname"
$7zipInstalled = $false
}
# Confirm that 7zip is installed on the remote server
else {
$7zipInstalled = $true
# Implicit output that can be captured by next pipeline command.
"7zip found on $hostname. Zipping files..."
}
} | ForEach-Object {
# Append text line received from remote script - this code runs locally!
$var_textInfo.AppendText( $_ )
}
為了能夠處理遠程腳本的 output ,您必須將它寫入成功 stream ,使用Write-Output
(很少使用)或隱式地,只需在其自己的行上寫入一個字符串文字(就像我上面所做的那樣)。 任何已經輸出成功 stream的命令也將被本地ForEach-Object
接收。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.