如何在powershell管道中使用環境變數?

如何在powershell管道中使用環境變數?

命令

systeminfo | find "System Type"

應該返回

System Type:               x64-based PC

在命令提示字元視窗和 PowerShell 中。

就我而言,它說

/usr/bin/find: 'System Type': No such file or directory

因為,正如向我解釋的那樣https://github.com/MicrosoftDocs/WSL/issues/1025,我還有一個find西格溫這是我的道路上。

在這種情況下正確工作的是

systeminfo | c:\windows\system32\find.exe "System Type"

現在假設我想讓它獨立於系統所在的位置(例如,如果我想將此命令包含在一些針對粗心用戶或類似用戶的指南中)。我考慮過調用

systeminfo | %SystemRoot%\system32\find.exe "System Type"

這適用於命令提示符,但不適用於 PowerShell。在後者中,我嘗試過

systeminfo | $env:SystemRoot\system32\find.exe "System Type"

但這給了錯誤

Expressions are only allowed as the first element of a pipeline.

.exe如果我執行完整路徑但沒有:this,我也會收到錯誤

systeminfo | c:\windows\system32\find "System Type"

給出

Cannot run a document in the middle of a pipeline: C:\windows\system32\find

我也嘗試過

systeminfo | % $env:SystemRoot\system32\find.exe "System Type"

但這會產生大量錯誤,例如

% : Input name "C:\WINDOWS\system32\find.exe" cannot be resolved to a method.

到底是怎麼回事?怎樣做才正確呢?

答案1

你可以這樣做:

systeminfo | & $env:SystemRoot\system32\find.exe "System Type"

請注意命令前的 & 符號。

但更好的是,使用本機 PowerShell,而不是透過管道將非 PowerShell 輸出傳輸到非 PowerShell 程式。

(Get-ComputerInfo -Property CsSystemType).CsSystemType

相關內容