我正在使用 Powershell 呼叫一個列印 Python 組態檔的程式,該檔案的結構如下:
[distutils]
index-servers =
some-pypi
[some-pypi]
repository: https://path/to/pypi
我想要做的是將整個輸出作為字串傳遞給另一個命令。不斷發生的事情是,每當我將它傳遞給使用它的程式時,Powershell 最終都會取出所有換行符和制表符特殊字符。這會產生錯誤的輸出。
以下是一些相關命令及其輸出。
> command to print config
它將完整地列印換行符和制表符的所有內容。
> $settings = command to print config
> echo $settings
哪個,當回顯時,會列印所有帶有換行符和制表符的內容。
> consuming-program $settings
這無法決議,因為運算式決議將所有輸出作為多個引數而不是單個引數提供給程式。
> consuming-program "$settings"
這取出了所有的換行符和制表符。
> consuming-program "$(command to print config)"
還取出所有換行符。
我錯過了什么?如何保留原始輸出并將其作為單個引數輸入到我的程式中,并且特殊字符完好無損?
uj5u.com熱心網友回復:
發生這種情況是因為命令的輸出被捕獲為字串陣列而不是單個字串。
例如,如果我們使用這個命令作為我們的基線:
C:\> dotnet
Usage: dotnet [options]
Usage: dotnet [path-to-application]
Options:
-h|--help Display help.
--info Display .NET information.
--list-sdks Display the installed SDKs.
--list-runtimes Display the installed runtimes.
path-to-application:
The path to an application .dll file to execute.
然后在 PowerShell 中捕獲輸出,我們可以看到它是一個字串陣列 - 每行輸出一個 - 而不是單個多行字串:
PS> $x = dotnet
PS> $x.GetType().FullName
System.Object[]
當您輸出$x到控制臺時,它會在單獨的行上顯示陣列中的每個專案,因此它在視覺上看起來與控制臺輸出相同:
PS> $x
Usage: dotnet [options]
Usage: dotnet [path-to-application]
Options:
-h|--help Display help.
--info Display .NET information.
--list-sdks Display the installed SDKs.
--list-runtimes Display the installed runtimes.
path-to-application:
The path to an application .dll file to execute.
但是當您將它用作命令引數時,會發生其他事情 - 通過將陣列中的專案與單個空格作為分隔符連接起來,它被序列化為單個字串:
Usage: dotnet [options] Usage: dotnet [path-to-application] Options: -h|--help Display help. --info Display .NET information. --list-sdks Display the installed SDKs. --list-runtimes Display the installed runtimes. path-to-application: The path to an application .dll file to execute.
這基本上就是 PowerShell 在某些情況下序列化陣列的方式。例如,比較這兩個命令的輸出:
PS> @( "aaa", "bbb", "ccc" )
aaa
bbb
ccc
PS> write-host @( "aaa", "bbb", "ccc" )
aaa bbb ccc
One fix, as suggested by @iRon in the comments, is to serialise the string yourself before using it in your command:
PS> $y = $x | Out-String
PS> $y
And then you can use $y as your command argument with the original formatting preserved.
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/454137.html
上一篇:我如何進行IIS網站站點名稱檢查
