2016-05-30 118 views
0

我想要做的是運行一個.ps1腳本,並在執行時打開一個新的powershell窗口並向其中寫入特定的文本。如何在powershell中調用第二個窗口並寫入它

打開一個新窗口很簡單。在許多方法中,我選擇了start Powershell。但是,我遇到的問題是,當我輸入write-host "ipsum lorem"時,它將它寫入本機窗口。

我想我可能不得不調用第二個PowerShell窗口,並將其保存在變量或對象中,然後寫入所述變量或對象。每次我嘗試在Google中進行搜索時,唯一的結果就是如何編寫輸出,而不是在本地窗口中運行腳本並完全寫入其他窗口。

據我所知,write-host寫入本機窗口,但我無法通過man write-*/get-help write-*或通過谷歌搜索找到任何東西。

任何人都可以用正確的方向指向我,讓我知道我可能開始看什麼?


下面是一個例子:

start powershell

if($var -eq $sum) {

# I want this to be written to the second window

write-host "This condition was met."

} else {

# I want this to be written to the second window

write-host "This condition was not met."

}

我知道write-host不應該被用作該寫入到本地窗口,但我只是把它作爲有一個佔位符。忍受着我。

在此先感謝。

+1

什麼是打開第二個窗口,並試圖從寫它的目的首先?對於大多數使用情況來說,這個(進程間通信)很可能是錯誤的方式去實現它 –

+0

它是分隔實際運行的和我想讓用戶看到的東西。它有助於打印狀態信息和自定義錯誤消息。使用不熟練的用戶進行故障排除變得非常簡單。有更多的原因,但我只想打印到第二個窗口。 – Rincewind

+1

到目前爲止,最簡單的方法就是寫一個文件,然後用不同的窗口/編輯器來顯示連續更新的文件(la'tail -f')。這不需要特殊的技術。另外它可以讓你免費登錄! –

回答

0

由於mentioned by Paul Hicks in the comments,你可以從第一個窗口輸出寫入到一個文件,讀回在第二個窗口:

# Create a temporary file 
$tmpFilePath = [System.IO.Path]::GetTempFileName() 

# Start a new powershell process that tails the temp file 
$outputWindow = Start-Process powershell "-NoExit -Command cls;Get-Content $tmpFilePath -Wait" -PassThru 

1..5 |ForEach-Object { 
    # Do some work and write the output to the temp file 
    'Doing step {0}' -f $_ |Out-File $tmpFilePath -Append 
    Start-Sleep -Seconds (1..3|Get-Random) 
} 
Write-Warning 'Please close the other window to continue!' 
# You could also use a timeout $outputWindow.WaitForExit(1000) 
# or $outputWindow.Kill() 
$outputWindow.WaitForExit() 

# Clean up 
Remove-Item $tmpFilePath 
+0

只是一個簡單的問題:將[System.IO。Path] :: GetTempFileName()給出與$ env:TEMP相同的信息? – Rincewind

+0

不,它會在磁盤上創建一個空的臨時文件並返回文件路徑 –