
Herdei um código onde um script faz referência a outro assim:
#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
Isso funciona bem localmente, mas quando ambos os scripts são implantados no servidor remoto e o script1 é chamado via comando de invocação, a instância remota do PS reclama que não consegue encontrar o 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.
O Script2 é usado por vários outros scripts (com sucesso no ambiente local), portanto não posso refatorar o script2 de volta para o script1.
Então, como posso dizer ao script1 para chamar o script2 de uma maneira que funcione se o script for executado localmente ou em um servidor remoto?
Responder1
Ok, isso funciona:
# 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