6

この記事に従って、スクリプトブロックの変数を展開しようとしています

私のコードはこれを試みます:

$exe = "setup.exe"

invoke-command -ComputerName $j -Credential $credentials -ScriptBlock {cmd /c 'C:\share\[scriptblock]::Create($exe)'}

エラーを修正する方法:

The filename, directory name, or volume label syntax is incorrect.
    + CategoryInfo          : NotSpecified: (The filename, d...x is incorrect.:String) [], RemoteException
    + FullyQualifiedErrorId : NativeCommandError
    + PSComputerName        : remote_computer
4

2 に答える 2

5

このシナリオでは、新しいスクリプト ブロックを作成する必要はまったくありません。作成しない理由については、リンクされた記事の下部にある Bruce のコメントを参照してください。

Bruce は、スクリプト ブロックにパラメーターを渡すことについて言及しており、このシナリオではうまく機能します。

$exe = 'setup.exe'
invoke-command -ComputerName $j -Credential $credentials -ScriptBlock { param($exe) & "C:\share\$exe" } -ArgumentList $exe

PowerShell V3 では、Invoke-Command を介してパラメーターを渡すさらに簡単な方法があります。

$exe = 'setup.exe'
invoke-command -ComputerName $j -Credential $credentials -ScriptBlock { & "C:\share\$using:exe" }

PowerShell は exe ファイルを正常に実行することに注意してください。通常、最初に cmd を実行する理由はありません。

于 2014-08-28T15:25:16.857 に答える
4

この記事に従うには、PowerShell の機能を利用して文字列内の変数を展開し、文字[ScriptBlock]::Create()列を受け取る which を使用して新しい ScriptBlock を作成する必要があります。現在試みているのは、ScriptBlock 内で ScriptBlock を生成することですが、うまくいきません。次のようになります。

$exe = 'setup.exe'
# The below line should expand the variable as needed
[String]$cmd = "cmd /c 'C:\share\$exe'"
# The below line creates the script block to pass in Invoke-Command
[ScriptBlock]$sb = [ScriptBlock]::Create($cmd) 
Invoke-Command -ComputerName $j -Credential $credentials -ScriptBlock $sb
于 2014-08-28T15:20:34.477 に答える