问题描述
每当我需要引用通用模块或脚本时,我都喜欢使用相对于当前脚本文件的路径.这样,我的脚本总能在库中找到其他脚本.
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)
我知道在模块 (.psm1) 中您可以使用 $PSScriptRoot
来获取此信息,但这不会在常规脚本(即 .ps1 文件)中设置.
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).
获取当前 PowerShell 脚本文件位置的规范方法是什么?
推荐答案
# This is an automatic variable set to the current file's/module's directory
$PSScriptRoot
PowerShell 2
在 PowerShell 3 之前,没有比查询更好的方法通用脚本的 MyInvocation.MyCommand.Definition
属性.我基本上在我拥有的每个 PowerShell 脚本的顶部都有以下行:
Prior to PowerShell 3, there was not a better way than querying theMyInvocation.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
这篇关于确定当前 PowerShell 脚本位置的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!