What's the best way to determine the location

2019-01-01 08:03发布

Whenever I need to reference a common module or script, I like to use paths relative to the current script file, that way, my script can always find other scripts in the library.

So, what is the best, standard way of determining the directory of the current script? Currently, I'm doing:

$MyDir = [System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.Definition)

I know in modules (.psm1) you can use $PSScriptRoot to get this information, but that doesn't get set in regular scripts (i.e. .ps1 files).

What's the canonical way to get the current PowerShell script file's location?

11条回答
大哥的爱人
2楼-- · 2019-01-01 08:41

If you are creating a V2 Module, you can use an automatic variable called $PSScriptRoot.

From PS > Help automatic_variable

$PSScriptRoot
       Contains the directory from which the script module is being executed.
       This variable allows scripts to use the module path to access other
       resources.
查看更多
笑指拈花
3楼-- · 2019-01-01 08:44

PowerShell 3+

# This is an automatic variable set to the current file's/module's directory
$PSScriptRoot

PowerShell 2

Prior to PowerShell 3, there was not a better way than querying the MyInvocation.MyCommand.Definition property for general scripts. I had the following line at the top of essentially every powershell script I had:

$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
查看更多
低头抚发
4楼-- · 2019-01-01 08:45

Maybe i'm missing something here... but if you want the present working directory you can just use this: (Get-Location).Path for a string, or Get-Location for an object.

Unless you're referring to something like this, which I understand after reading the question again.

function Get-Script-Directory
{
    $scriptInvocation = (Get-Variable MyInvocation -Scope 1).Value
    return Split-Path $scriptInvocation.MyCommand.Path
}
查看更多
刘海飞了
5楼-- · 2019-01-01 08:45

I needed to know the script name and where it is executing from.

Prefixing "$global:" to the MyInvocation structure returns the full path and script name when called from both the main script, and the main line of an imported .PSM1 library file. It also works from within a function in an imported library.

After much fiddling around, I settled on using $global:MyInvocation.InvocationName. It works reliably with CMD launch, Run With Powershell, and the ISE. Both local and UNC launches return the correct path.

查看更多
人间绝色
6楼-- · 2019-01-01 08:50

For Powershell 3+

function Get-ScriptDirectory {
    if ($psise) {Split-Path $psise.CurrentFile.FullPath}
    else {$global:PSScriptRoot}
}

I've placed this function in my profile. Works in ISE using F8/Run Selection too.

查看更多
登录 后发表回答