'How to use invoke-command in powershell, to run a script on remote machine

Is it possible to use Invoke-Command in PowerShell to run a script on a remote machine?

I have tried :

Invoke-Command -ComputerName $MyPC -Credential $mycreds -ScriptBlock {
    & "C:\Users\MyPC\Desktop\scripts\Script1.ps1"
}

which returns

script1.ps1 is not recognized as the name of a cmdlet

The scenario here is, I have some scripts on a remote folder, and I need to use Invoke-Command or some other ways to run the script on a remote machine.

Also, how to write if I want to pass some parameters for script1.ps1? Thanks in advance!



Solution 1:[1]

Instead of this:

Invoke-Command -ComputerName $MyPC -Credential $mycreds -ScriptBlock {& "C:\Users\MyPC\Desktop\scripts\Script1.ps1"}

Try this:

Invoke-Command -ComputerName $MyPC -Credential $mycreds -FilePath C:\Users\MyPC\Desktop\scripts\Script1.ps1

Solution 2:[2]

to avoid confusion with filepaths on local machines/remote machines; i always run stuff from smb-shares; you can enter UNC as filepath... eg: -FilePath \server\Netscripts\script.ps1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Ranadip Dutta
Solution 2 BoGy