Search code examples
powershellexecutioninvoke-command

Run an executable with a parameter using Invoke-Command


I am trying to run an executable with a config file as a parameter using invoke-command through a PowerShell script.

Here is what I have so far in my PowerShell script:

$config = 'D:\EmailLoader\App.config'
invoke-command -ComputerName SERVER-NAME -ScriptBlock {param($config) & 'D:\EmailLoader\GetMailAndAttachment.exe' $config} -ArgumentList $config

I then Execute the PowerShell script with the following command:

C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy ByPass -File "D:\PowerShellScripts\Email.ps1"

And I get the following error:

Unexpected token 'config' in expression or statement.
At D:\PowerShellScripts\Email.ps1:3 char:121
+ invoke-command -ComputerName SERVER-NAME -ScriptBlock {param($config)     'D:\EmailLoader\GetMailAndAttachment.exe' $config <<<< } -ArgumentList $config
+ CategoryInfo          : ParserError: (config:String) [], ParentContainsE   rrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken

Solution

  • The code looks like it should work. But the exception message is clearly missing the & symbol. I would check that first, because you are getting the exact same message I would anticipate to get when the & was missing. So maybe there is problem with the saved file, rather than with your code.

    Side note: If you are on PowerShell 3.0 or newer you should consider using the $using: scope in the script block to avoid adding the param and -ArgumentList.

    $config = 'D:\EmailLoader\App.config'
    Invoke-Command -ComputerName SERVER-NAME -ScriptBlock {
        &'D:\EmailLoader\GetMailAndAttachment.exe' $using:config
    }