Powershell: Call one remote script from another remote script

5,428

Okay, this works:

# script1.ps1

# do stuff

# get the current folder
$currentFolder = Split-Path $MyInvocation.MyCommand.Path

# call the second script in the remote folder with arguments from the first
. (Join-Path $currentFolder script2.ps1) $arg1
Share:
5,428
user364825
Author by

user364825

Updated on September 18, 2022

Comments

  • user364825
    user364825 almost 2 years

    I inherited some code where one script references another like this:

    #Script1.ps1
    param($arg1)
    
    # do some stuff
    
    # call script2 with argument from script1
    .\script2.ps1 $arg1
    
    
    #script2.ps1
    param($arg1)
    # do some stuff unique to this script
    

    This works fine locally, but when both scripts are deployed to remote server, and script1 is called via invoke-command, the remote PS instance complains that it can't find script2:

    invoke-command $remoteServer { param($arg1, $remoteScript) powershell $remoteScript $arg1 } -argumentList $arg1, $remoteScript
    # output from script1
    # more output from script 1    
    # here comes the error when script1 calls script2:
    The term '.\script2.ps1' is not recognized as the name of a cmdlet, functi
    
    on, script file, or operable program. Check the spelling of the name, or if a p
    
    ath was included, verify that the path is correct and try again.
    

    Script2 is used by a number of other scripts (successfully on the local environment) so I can't refactor script2 back into script1.

    So, how can I tell script1 to call script2 in a manner that will work whether the script is run locally or on a remote server?