如何获取正在执行的cmdlet的当前目录

如何获取正在执行的cmdlet的当前目录

本文介绍了如何获取正在执行的cmdlet的当前目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这应该是一个简单的任务,但我已经看到了多次尝试如何获取执行的 cmdlet 所在目录的路径,但结果参差不齐.例如,当我执行 C:empmyscriptsmycmdlet.ps1 时,它在 C:empmyscriptssettings.xml 处有一个设置文件,我想能够将 C:empmyscripts 存储在 mycmdlet.ps1 中的变量中.

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:empmyscriptsmycmdlet.ps1 which has a settings file at C:empmyscriptssettings.xml I would like to be able to store C:empmyscripts 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'

我非常喜欢后一种方法,并且更喜欢它每次都必须将文件路径解析为参数,但我无法让它在我的开发环境中工作.我该怎么办?是否与 PowerShell 的配置方式有关?

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. What should I do? Does it have something to do with how PowerShell is configured?

推荐答案

执行此操作的可靠方法就像您展示的 $MyInvocation.MyCommand.Path.

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

使用相对路径将基于 $pwd,在 PowerShell 中,应用程序的当前目录,或 .NET API 的当前工作目录.

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.

PowerShell v3+:

使用自动变量$PSScriptRoot.

这篇关于如何获取正在执行的cmdlet的当前目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 20:14