DTRT
DTRT

Reputation: 11040

Powershell $PSScriptRoot empty when using Invoke-Command

When running a .ps1 on a remote computer using Invoke-Command, $PSScriptRoot is empty on the remote computer.

Is this normal? How can one find the .ps1 path when using Invoke-Command?

Further, other methods, such as through $MyInvocation are also empty.

Upvotes: 1

Views: 1317

Answers (1)

mklement0
mklement0

Reputation: 437218

Is this normal? How can one find the .ps1 path when using Invoke-Command?

There is no script file involved on the remote computer when you call
Invoke-Command -ComputerName $someComputer -FilePath c:\path\to\some\script.ps1

What PowerShell does in this case is to send the contents (parsed source code)[1] of the caller-local script file to the remote machine and executes it there.

Therefore, $PSScriptRoot (the directory in which a script file resides) doesn't apply and returns the empty string.
The same applies to other script-file-related automatic variables, such as $PSCommandPath and $MyInvocation.MyCommand.Name (see about_Automatic_Variables).

To put it differently: When the script file's code executes remotely, it doesn't know anything about the file it came from on the caller's side.

Thus, the only information available you there is $PWD, i.e., the current (working) location (directory).


[1] From the docs: "When you use this [the -FilePath] parameter, PowerShell converts the contents of the specified script file to a script block, transmits the script block to the remote computer, and runs it on the remote computer."

Upvotes: 1

Related Questions