2015-09-04 27 views
1

我已經創建了一段代碼,可以在腳本中正常工作,但在轉換爲函數時失敗。使用函數設置腳本文件夾位置失敗

該代碼將腳本所在的位置設置爲當前位置。

Function Set-ScriptFolder 
{ 
    <# 
     .SYNOPSIS 
     Sets the location to the folder where the script folder resides. 
     .DESCRIPTION 
     Sets the location to the folder where the script folder resides. 
     .EXAMPLE 
     Set-ScriptFolder 
     .EXAMPLE 
     Set-ScriptFolder 
    #> 


    $location = Split-Path $MyInvocation.MyCommand.Path 
    set-location $location 

} 

輸出是:

Split-Path : Cannot bind argument to parameter 'Path' because it is null. 

set-location : Cannot process argument because the value of argument "path" is null. Change the value of argument 
"path" to a non-null value. 

不知道如何轉換:

$location = Split-Path $MyInvocation.MyCommand.Path 
    set-location $location 

的功能?

感謝

+2

函數中的'$ MyInvocation'是該函數的調用信息嗎?那會是我想的問題。這意味着你可以從我認爲的腳本中將參數傳遞給你的函數......但是爲什麼呢? –

回答

2

如果你看一下documentation for $MyInvocation你會看到....

$MyInvocation只爲腳本,函數和腳本塊填充。 您可以使用在System.Management.Automation.InvocationInfo 對象的信息$ MyInvocation回報在當前腳本,如腳本($MyInvocation.MyCommand.Path的路徑 和文件名或 功能的名稱( $MyInvocation.MyCommand.Name)來識別當前命令。

你可以看到$MyInvocation.MyCommand.Name輸出裏面的函數將返回:

Set-ScriptFolder 

替代解決方案

您可以使用automatic variable$PSScriptRoot來代替。

Set-Location $PSScriptRoot 

這應該在函數內部工作。如果您願意,只要您使用PowerShell 3.0或更高版本,則還可以使用$MyInvocation的Properry PSScriptRoot

Set-Location $MyInvocation.PSScriptRoot 

功能只是一條線似乎有點矯枉過正。

+0

謝謝,Set-Location $ MyInvocation.PSScriptRoot可以工作,但$ PSScriptRoot無法正常工作。 – RalJans

+0

@RalJans確保你實際上保存了文件,而不是從ISE運行它在一個未保存的文件中。 '$ PSScriptRoot'只適用於從文件運行。 – briantist