2011-09-11 69 views
13

我有以下目錄樹:如何使用相對路徑調用另一個PowerShell腳本?

e:\powershell\services\This-Script-Here-Should-Call-Press any key to continue.ps1 
e:\powershell\utils\Press any key to continue.ps1 

,現在我想調用名爲腳本「按任意鍵continue.ps1」,在「utils的」 -folder坐在從腳本,我在「服務」 - 文件夾中。我怎麼做?我無法弄清楚相對路徑。

我試圖做這樣說:

"$ '.\..\utils\Press any key to continue.ps1'" 

,但沒有奏效。

+0

可能重複:http://stackoverflow.com/q/6816450/2291(雖然這不是特定於相對路徑) –

回答

21

基於你在做什麼,下面應該工作:

& "..\utils\Press any key to continue.ps1" 

. "..\utils\Press any key to continue.ps1" 

(查找使用之間的差和.並決定使用哪一個)

這是我如何處理這種情況(到什麼@Shay提到略有變化):

$scriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path 
$utilsDir = Join-Path -Path $scriptDir -ChildPath ..\utils 

& "$utilsDir\Press any key to continue.ps1" 
+30

&和的鏈接。本來會很好的。不完全是Google友好的搜索表達式。 –

+4

如果其他人想要了解&,這是「Invoke-Expression」的快捷方式 - 請參閱http://technet.microsoft.com/en-us/library/ee176880.aspx –

+10

,以便那些仍然遇到問題的人嘗試找出區別。並看看以下博客: http://rkeithhill.wordpress.com/2007/11/24/effective-powershell-item-10-understanding-powershell-parsing-modes/ TL; DR 「。 「調用腳本並在當前範圍內運行 「&」調用腳本並運行在不同的子範圍內並被丟棄 – stanleykylee

5

多姆在調用腳本下面的函數來獲得它的目錄路徑,並加入utils的路徑與腳本名稱一起:

# create this function in the calling script 
function Get-ScriptDirectory { Split-Path $MyInvocation.ScriptName } 

# generate the path to the script in the utils directory: 
$script = Join-Path (Get-ScriptDirectory) 'utils\Press any key to continue.ps1' 

# execute the script 
& $script 
+0

這個解決方案有兩個問題:第一 - 這不是我想要實現的,因爲「ulits」目錄不是「服務的子目錄「我必須離開」服務「,然後輸入」utils「來調用正確的腳本。 2nd - ScriptName-屬性爲空。我編輯了這個問題,使它更清晰。 – t3chb0t

+0

它確實取決於控制檯的工作目錄(在控制檯中鍵入pwd)。如果你想使用相對路徑,你需要首先進入源腳本目錄,然後使用.. \ folder \ script.ps1。你確定Get-ScriptDirectory沒有返回調用腳本的父文件夾嗎? –

+0

我的不好。我必須監督Get-ScriptDirectory函數的工作。 – t3chb0t

相關問題