[英]Piping to PowerShell from CMD
TLDR:為什么我不能在兩個POWERSHELL.exe實例之間管道流輸出?
我想input.txt
一個input.txt
文件並將其內容傳遞給任何接受STDIN的CLI。 消費者可能是PowerShell.exe,php.exe,awk,python,sed等。
我的假設是STDIN和STDOUT是所有CLI都會說的通用概念,因此我應該能夠快速地從CMD / DOS命令到/從POWERSHELL.exe進行管道傳輸。
input.txt中:
hello
world
我想要的操作模式是,當行添加到input.txt
它們會立即通過管道連接到接受STDIN的CLI。 在PowerShell中,可以將其模擬為:
Get-Content -Wait input.txt | ForEach-Object {$_}
除了這里不需要關注的額外新行之外,它的工作原理如下:
hello
world
I'm adding lines and saving and...
...they appear here...
yaaaay
現在,我將這個尾部功能封裝為tail.ps1
,然后創建一個簡單的用戶腳本process.ps1
,我將鏈接在一起:
tail.ps1:
Get-Content -Watch .\input.txt
process.ps1:
process {
$_
}
我明確使用了process{}
塊,因為我想要流式管道,而不是一些end{}
塊循環。
同樣,這適用於PowerShell Shell:
PS> .\tail.ps1 | .\process.ps1
hello
world
here is a new line saved to input.txt
現在我想將每個腳本視為一個單獨的CLI,可以從CMD / DOS調用:
C:\>POWERSHELL -f tail.ps1 | POWERShell -f process.ps1
這不起作用 - 沒有產生輸出,我的問題為什么不?
也只是輸入一些輸入TO powershell.exe process.ps1
產生輸出:
C:\>type input.txt | POWERSHELL -f process.ps1
但是,從PowerShell到AWK的管道確實有效:
C:\>POWERSHELL -f tail.ps1 | awk /e/
Hello
here is a newline with an e
so we're good
為什么AWK接受管道線但是POWERShell process.ps1
不行?
另一個令人費解的例子來自CMD / DOS:
C:\>powershell -c "'hello';'world'"
hello
world << This is as it should be
C:\>powershell -c "'hello';'world'" | powershell -f process.ps1
<< No output appears - why not!?
W:\other>powershell -c "'hello';'world'" | powershell -c "$input"
hello
world << Powershell does get the stdin
雖然我還沒有解釋,但我有一個解決方法可以很好地傳輸內容:
process.ps1 :
begin {if($input){}}
process {
$_
}
看來,如果沒有訪問$input
的begin{}
塊,則不會$input
process{}
塊。
這可能是一個PowerShell錯誤,因為它在PowerShell中正常運行。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.