2

I'm trying to build a script which copies files and execute them on a specific amount of servers. To do so, I need to run a remote command. I stored it in a variable. I know that variables can't be used within a remote session. Except you use the -ArgumentList parameter. But this doesn't work for me either.

Here's the code and the error message:

$CMD_AgentDirectory = "New-Item -Path 'C:\FlexAgent' -ItemType Directory"
Invoke-Command -ComputerName Server01 -ScriptBlock {
    Invoke-Expression $CMD_AgentDirectory
} -ArgumentList $CMD_AgentDirectory

Error Message:

Cannot bind argument to parameter 'Command' because it is null.
    + CategoryInfo          : InvalidData: (:) [Invoke-Expression], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.InvokeExpressionCommand
    + PSComputerName        : Server01

What am I doing wrong?

Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328
CVoit
  • 21
  • 5
  • Which Powershell Version is running on the Host and the Destination? – Paxz Jun 27 '18 at 09:20
  • Add `param($CMD_AgentDirectory)` before `Invoke-Expression` – Robert Dyjas Jun 27 '18 at 09:25
  • Side note: `Invoke-Expression` is practically always [the wrong tool](https://blogs.msdn.microsoft.com/powershell/2011/06/03/invoke-expression-considered-harmful/). Just put the `New-Item` commandline directly into the scriptblock (without the double quotes) or create the scriptblock from that command string. – Ansgar Wiechers Jun 27 '18 at 09:39

0 Answers0