To complement briantist’s helpful answer:
The script block passed to Invoke-Command
is (as intended) executed on the remote machine, using the remote machine’s variables by default.
Thus, in order to use a local variable’s value,[1] extra steps are needed (to put it differently: inside a script block executed remotely, you cannot just refer to local variables as you normally would, such as with $dest
):
-
PS v3+ offers the
using:
scope modifier for direct use of a local variable’s value inside the script block – see briantist’s first command.- Note that
using:
only works whenInvoke-Command
actually targets a remote machine, such as with the-ComputerName
parameter.
- Note that
-
The only option that also works in earlier versions is to pass the local variable as a parameter to the script block. – see briantist’s second command.
[1] Note that you fundamentally cannot pass a variable itself, i.e. you cannot assign to a local variable in a remote script block.