2016-03-02 48 views
0

我有一些問題傳遞一個字符串數組到Powershell中的命令,所以我正在調試我的腳本。我正在使用PowerShell Community Extension Project (PSCX)中的EchoArgs.exe程序。 如果我執行這個腳本:如何在命令行參數中正確地轉義空格和反斜槓?

Import-Module Pscx 
cls 

$thisOne = 'this_one\'; 
$secondOne = 'second one\'; 
$lastOne = 'last_one' 

$args = $thisOne ` 
    , "the $secondOne" ` 
    , "the_$lastOne" 


EchoArgs $args 

我得到這樣的結果:

Arg 0 is <this_one\> 
Arg 1 is <the second one" the_last_one> 

Command line: 
"C:\Program Files (x86)\PowerShell Community Extensions\Pscx3\Pscx\Apps\EchoArgs.exe" this_one\ "the second one\" the_last_one 

看來,如果一個字符串包含空格,最後一個反斜槓轉義雙引號。其實一切似乎工作,如果我逃只有反斜線:

Import-Module Pscx 
cls 

$thisOne = 'this_one\'; 
$secondOne = 'second one\\'; 
$lastOne = 'last_one' 

$args = $thisOne ` 
    , "the $secondOne" ` 
    , "the_$lastOne" 


EchoArgs $args 

這個結果:

Arg 0 is <this_one\> 
Arg 1 is <the second one\> 
Arg 2 is <the_last_one> 

Command line: 
"C:\Program Files (x86)\PowerShell Community Extensions\Pscx3\Pscx\Apps\EchoArgs.exe" this_one\ "the second one\\" the_last_one 

所以我的問題是:是否有PowerShell中的一個「聰明」的方式(即小命令),以逃避任何字符串以避免此類問題?

+0

關於你的PS腳本中使用單引號是什麼?所以'$ args ='this_one',''第二個'','the_last_one'' – romellem

+0

你說得對,但我必須在數組字符串中使用變量,比如'$ args =「$ thisOne」'等等。 – lucazav

+0

我剛剛更新了代碼片段。謝謝 – lucazav

回答

相關問題