2012-04-10 5 views
6

私はここで私の髪を引っ張っている、私はちょうどこれを動作させるように見えることができないので、私はこの問題をGoogleにする方法を把握することはできません。私はPowershell 2.0を実行しています。ここに私のスクリプトがあります:PowershellのInvoke-Commandは-ComputerNameパラメータの変数を取りませんか?

$computer_names = "server1,server2" 
Write-Output "Invoke-Command -ComputerName $computer_names -ScriptBlock { 
    Get-WmiObject -Class Win32_LogicalDisk | 
    sort deviceid | 
    Format-Table -AutoSize deviceid, freespace 
}" 
Invoke-Command -ComputerName $computer_names -ScriptBlock { 
    Get-WmiObject -Class Win32_LogicalDisk | 
    sort deviceid | 
    Format-Table -AutoSize deviceid, freespace 
} 

最後のコマンドはエラーを与える:

Invoke-Command : One or more computer names is not valid. If you are trying to 
pass a Uri, use the -ConnectionUri parameter or pass Uri objects instead of 
strings. 

しかし、私はシェルへの書き込み出力コマンドの出力をコピーして、それを実行すると、それだけで正常に動作します。文字列変数をInvoke-Commandが受け付けるものにキャストするにはどうすればよいですか?前もって感謝します!

答えて

5

あなたの配列を間違って宣言しました。以下のために、それぞれのように文字列とパイプの間にカンマを入れて:あなたは

$computer_names = "server1", "server2"; 

$computer_names | %{ 
    Write-Output "Invoke-Command -ComputerName $_ -ScriptBlock { 

    ...snip 
+0

これは、ありがとう!私はそれをそれぞれのために実行するとは思わなかった。それは私が見たことのない略語です。しかし、私はInvoke-Command -ComputerNameが1つを取るとは思わないので、配列の宣言を避けていました。代わりにコンマで区切られたコンピュータ名のリストをスペースなしで取ります。私が間違っている? – erictheavg

+0

自分自身に反応する:それはそうだ。私はちょうどそのコマンドのヘルプを読んで、それは文字列[]を期待していると言います。私は単なる例から離れて、悪い仮定をしていました。 – erictheavg

0

試してみました:

$computer_names = "server1" , "server2" 

foreach ($computer in $computer_names) 
{ 
Write-Output "Invoke-Command -ComputerName $computer -ScriptBlock { 
    Get-WmiObject -Class Win32_LogicalDisk | 
    sort deviceid | 
    Format-Table -AutoSize deviceid, freespace 
}" 
Invoke-Command -ComputerName $computer -ScriptBlock { 
    Get-WmiObject -Class Win32_LogicalDisk | 
    sort deviceid | 
    Format-Table -AutoSize deviceid, freespace 
} 
} 
6

をあなたの宣言が間違っていることにジェイミーとuser983965は、正しいです。ただし、foreachは必須ではありません。あなたはこのようなあなたの配列宣言を修正した場合、それは動作します:

$computer_names = "server1","server2" 
Invoke-Command -ComputerName $computer_names -ScriptBlock { 
    Get-WmiObject -Class Win32_LogicalDisk | 
    sort deviceid | 
    Format-Table -AutoSize deviceid, freespace 
} 
+0

コンピュータオブジェクトを使って '$ computers'という変数をすでに設定している場合に、この方法で動作するように配列を生成する別の方法(' get-adcomputer'を使用するなど)は '$ computer_names = $ computers.name'です。 –

0

をあなたもActive Directoryからコンピュータのarrayを取得している場合 - 次のように:

$computers = Get-ADComputer -filter {whatever} 

は、あなたが選択することを忘れないでください/このように...結果を展開します。次に

$Computers= Get-ADComputer -filter * | Select-Object -ExpandProperty Name 

...

Invoke-Command -ComputerName $Computers -ScriptBlock {Do Stuff} 
関連する問題