Powershell コマンドのパラメータ間のスペース

Powershell コマンドのパラメータ間のスペース

PowerShell コマンドのパラメータ間にスペースを入れるとエラーが発生する理由を知りたいです。

スペース: (機能しません)

wmic desktopmonitor get screenwidth, screenheight
Expression GET non valide.

それなしスペース:(作業)

wmic desktopmonitor get screenwidth,screenheight
ScreenHeight  ScreenWidth

それは普通ですか? インターネットではスペース付きのコマンドをよく見かけます。


2016年1月27日更新 バージョン詳細:

$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 では 2 番目の方法 (スペースなし) のみが機能します (以下のスクリーンショットを参照)。

コマンド

パワーシェル

答え1

カンマは PowerShell の配列演算子です。したがって、コマンドは次のようになります。

wmic desktopmonitor get screenwidth, screenheight

は、次の意味を持ちます: wmic3 つの引数 (文字列desktopmonitor、文字列get、および 2 つの文字列とを含む配列screenwidth)で呼び出しますscreenheight。 はwmicネイティブ アプリケーションであるため、PowerShell は引数をコマンド ラインに変換する必要があります。PowerShell は、配列をコマンド ラインに変換するときに、区切り文字としてスペースを使用します。したがって、結果のコマンド ラインは次のようになります。

wmic desktopmonitor get screenwidth screenheight

次のコマンドを入力するとそれを確認できます。

cmd /c echo wmic desktopmonitor get screenwidth, screenheight

PowerShell v5 以降では、特別なケースが 1 つあります。配列が直接 (部分式としてではなく) 提供され、コンマと配列要素の間にスペースがない場合、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

関連情報