ScriptBlock doesn't work with variables

Hi! I am newbie with Powershell and I trying to create a script do execute remote commands, using Invoke-Command.
Everything goes fine, except when I use the parameter -ScriptBlock.
When I try to execute the command, using a variable at the ScriptBlock ($Path), it doesn’t works (I don’t receive any ouput). For example:

$Path = "C:\temp"
$Server = "Computer1"

Invoke-Command -ComputerName $Server -Credential DOMAIN\USER -ScriptBlock {Get-ChildItem $Path}

But, If I insert the value “C:\temp” manually instead of use the variable “$Path”, I get the ouput that I want. Example:

Invoke-Command -ComputerName $Server -Credential DOMAIN\USER -ScriptBlock {Get-ChildItem C:\temp}


How can I use variables with -ScriptBlock {} ?

Thanks and BR,


It should if you use $Using:Path

1 Like

@thelmomauleon Welcome to forums.

@tonyd has provided the right documentation to understand how the variable thing works in a remote execution, in addition Get-SmbShareAccess Cannot validate argument on parameter ‘Name’ - PowerShell Help - PowerShell Forums

Will also help you as it has is a similar thread.

Thanks tonyd and kvprasoon, you guys saved my day.

The documentation is really good.

Thanks again and BR,