How to get the current directory of the cmdlet bei

2019-01-08 06:54发布

This should be a simple task but I have seen several attempts on how to get the path to the directory where the executed cmdlet is located with mixed success. For instance when I execute c:\temp\myscripts\mycmdlet.ps1 which has a settings file at c:\temp\myscripts\settings.xml I would like to be able to store c:\temp\myscripts in a variable within mycmdlet.ps1.

This is one solution which works (although a bit cumbersome):

$invocation = (Get-Variable MyInvocation).Value
$directorypath = Split-Path $invocation.MyCommand.Path
$settingspath = $directorypath + '\settings.xml'

Another one suggested this solution which only works on our test environment:

$settingspath = '.\settings.xml'

I like the latter approach a lot and prefer it to having to parse the filepath as a parameter each time, but I can't get it to work on my development environment. Does anyone have a suggestion on what to do? Does it have something to do with how PowerShell is configured?

12条回答
仙女界的扛把子
2楼-- · 2019-01-08 07:25

Try :

(Get-Location).path

or:

($pwd).path
查看更多
Explosion°爆炸
3楼-- · 2019-01-08 07:26

You can also use:

(Resolve-Path .\).Path

The part in brackets returns a PathInfo object.

(Available since PowerShell 2.0.)

查看更多
看我几分像从前
4楼-- · 2019-01-08 07:28

The reliable way to do this is just like you showed $MyInvocation.MyCommand.Path.

Using relative paths will be based on $pwd, in PowerShell, the current directory for an application, or the current working directory for a .NET API.

查看更多
Lonely孤独者°
5楼-- · 2019-01-08 07:29

Get-Location will return the current location:

$Currentlocation=Get-Location
查看更多
我命由我不由天
6楼-- · 2019-01-08 07:29

You would think that using '.\' as the path means that it's the invocation path. But not all the time. Example, if you use it inside a job ScriptBlock. In which case, it might point to %profile%\Documents.

查看更多
Juvenile、少年°
7楼-- · 2019-01-08 07:29

In Powershell 3 and above you can simply use

$PSScriptRoot

查看更多
登录 后发表回答