Powershell:從另一個遠端腳本呼叫一個遠端腳本

Powershell:從另一個遠端腳本呼叫一個遠端腳本

我繼承了一些程式碼,其中一個腳本引用另一個腳本,如下所示:

#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

這在本地工作正常,但是當兩個腳本都部署到遠端伺服器,並且透過 invoke-command 呼叫 script1 時,遠端 PS 實例抱怨它找不到 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 被許多其他腳本使用(在本地環境中成功),因此我無法將 script2 重構回 script1。

那麼,我該如何告訴 script1 以無論腳本是在本地還是在遠端伺服器上運行都有效的方式呼叫 script2?

答案1

好的,這有效:

# 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

相關內容