Search code examples
variablespowershellscriptblock

Powershell expand variable in scriptblock


I am trying to follow this article to expand a variable in a scriptblock

My code tries this:

$exe = "setup.exe"

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

How to fix the error:

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

Solution

  • To follow the article, you want to make sure to leverage PowerShell's ability to expand variables in a string and then use [ScriptBlock]::Create() which takes a string to create a new ScriptBlock. What you are currently attempting is to generate a ScriptBlock within a ScriptBlock, which isn't going to work. It should look a little more like this:

    $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