PowerShell scripts can be executed locally or remotely. In this article I will show how scripts can be executed remotely. It is important whether the script is on the source computer or on the target computer. Both scenarios are possible. Let’s dive in.
PowerShell Script is located on the Remote Computer
If the script is located on the remote computer, we must use the Scriptblock parameter.
Here is an example:
Invoke-Command -ComputerName mb01 -ScriptBlock {C:\temp\script.ps1}
This command will call the script script.ps1 which is located on the Remote-Computer.
PowerShell Script is located on the Local Computer
If the script is located on the local computer, we must use the FilePath parameter.
Invoke-Command -ComputerName mb01 -FilePath 'C:\temp\Script.ps1'
This command will call the script script.ps1 which is located on the Local Computer.
Alternative: Establish connection with Enter-PS session
If the script is saved on the remote computer we can also use Enter-PSSession to connect to the remote computer and finally execute the script.
Here is an example:
Enter-PSSession -ComputerName mb01 # next, navigate to the script folder
.\script.ps1 # run the script
Exit-PSSession
Hope this was helpful.
Categories: PowerShell




You are welcome!
On a slightly different note, I found that under PowerShell 7.5.1, the parallel parameter for the ForEach-Object cmdlet does not work under Invoke-Command or when using PSSession. It results in the following error: ForEach-Object : Parameter set cannot be resolved using the specified named parameters.
Some sample code:
— or —
Wish I had known that before spending a lot of time working on a remote machine!
LikeLike
Thank you for the hint.
LikeLike
Under the local computer header, you mention the script being remote again. I believe you meant local.
LikeLike
Thank you! Fixed now.
LikeLike