我想知道為什麼當我在 powershell 命令中的參數之間留有空格時出現錯誤:
和空間:(不起作用)
wmic desktopmonitor get screenwidth, screenheight
Expression GET non valide.
沒有空間:(工作)
wmic desktopmonitor get screenwidth,screenheight
ScreenHeight ScreenWidth
這樣正常嗎?因為我在網路上看到很多指令都是帶空格的!
更新 27/01/2016 版本詳情:
$PSVersionTable
Name Value
---- -----
PSVersion 5.0.10240.16384
WSManStackVersion 3.0
SerializationVersion 1.1.0.1
CLRVersion 4.0.30319.42000
BuildVersion 10.0.10240.16384
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
PSRemotingProtocolVersion 2.3
兩種方式(有或沒有空格)都可以與 CMD 配合使用,但只有第二種方式(沒有空格)可以與 PowerShell 配合使用(請參見下面的螢幕截圖):
答案1
逗號是 PowerShell 中的陣列運算子。所以你的命令:
wmic desktopmonitor get screenwidth, screenheight
具有以下意義:wmic
使用三個參數呼叫: string desktopmonitor
、 stringget
和帶有兩個 stringscreenwidth
和 的陣列screenheight
。由於wmic
是本機應用程序,PowerShell 必須將參數轉換為命令列。 PowerShell 在將陣列轉換為命令列時使用空格作為分隔符號。因此,產生的命令列如下:
wmic desktopmonitor get screenwidth screenheight
您可以輸入以下命令來查看:
cmd /c echo wmic desktopmonitor get screenwidth, screenheight
從 PowerShell v5 開始,這裡有一個特殊情況。如果直接提供陣列(不是作為子表達式)且逗號和陣列元素之間沒有空格,則 PowerShell 在將陣列轉換為命令列時使用逗號作為分隔符號。
PS> cmd /c echo 1,2,3 (4,5,6) 7,8 ,9
1,2,3 4 5 6 7 8 9
這個命令:
wmic desktopmonitor get screenwidth,screenheight
符合這種特殊情況,產生的命令列如下:
wmic desktopmonitor get screenwidth,screenheight