Get script directory in PowerShell when script is invoked with Invoke-Command

后端 未结 2 1545
醉话见心
醉话见心 2021-01-13 08:00

I have a set of PowerShell scripts that include a \"common\" script, located in the same folder, like this:

# some-script.ps1
$scriptDir = Split-Path -Parent         


        
相关标签:
2条回答
  • 2021-01-13 08:23

    I don't believe you can, from within the invoked script. From get-help invoke-command:

    -FilePath Runs the specified local script on one or more remote computers. Enter the path and file name of the script, or pipe a script path to Invoke-Command. The script must reside on the local computer or in a directory that the local computer can access. Use the ArgumentList parameter to specify the values of parameters in the script.

     **When you use this parameter, Windows 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.**
    

    When you use invoke-command using the -filepath parameter, the script is read from the file on the local computer, converted to a script block, and that's what gets passed to the remote computer. The remote computer doesn't have any way of knowing if that script block was read from a file.

    For the remote computer to know what that original file path was, you'll have to tell it. I think the easiest way to do that would be to write a function to do the invocation, and have it pass the filename to the invoked script as a parameter.

    0 讨论(0)
  • 2021-01-13 08:36

    alternatively rather than using filepath.. you could pass in a scriptblock, that dotsources the script from a UNC path that all machines have access to. However each machine will need to have the appropriate executionpolicy set so that they can run that script from the UNC path

    let me be clear though, that i'm not saying to run the script from the UNC path as if that does the remoting, but still using invoke-command or start-job to run a scriptblock on a remote computer. It just happens that that scriptblock will run the script from a UNC path for convenience.

    0 讨论(0)
提交回复
热议问题