如何获取PowerShell脚本的文件系统位置?
我的PowerShell脚本位于如何获取PowerShell脚本的文件系统位置?,powershell,batch-file,Powershell,Batch File,我的PowerShell脚本位于D:\temp 运行此脚本时,我希望列出文件的当前位置。我该怎么做 例如,此代码将在DOS批处理文件中完成;我正在尝试将其转换为PowerShell脚本 FOR /f "usebackq tokens=*" %%a IN ('%0') DO SET this_cmds_dir=%%~dpa CD /d "%this_cmds_dir%" PowerShell 3+ 正在运行的脚本的路径为: $PSCommandPath $MyInvocation.MyComm
D:\temp
运行此脚本时,我希望列出文件的当前位置。我该怎么做
例如,此代码将在DOS批处理文件中完成;我正在尝试将其转换为PowerShell脚本
FOR /f "usebackq tokens=*" %%a IN ('%0') DO SET this_cmds_dir=%%~dpa
CD /d "%this_cmds_dir%"
PowerShell 3+ 正在运行的脚本的路径为:
$PSCommandPath
$MyInvocation.MyCommand.Path
其目录为:
$PSScriptRoot
$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent
PowerShell 2
正在运行的脚本的路径为:
$PSCommandPath
$MyInvocation.MyCommand.Path
其目录为:
$PSScriptRoot
$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent
罗曼·库兹明回答了伊姆霍的问题。我只想补充一点,如果您导入一个模块(通过
import module
),您可以访问模块内部的$PsScriptRoot
自动变量,这将告诉您模块的位置。我发现这在PowerShell V5的脚本和PowerShell ISE中对我有效:
try {
$scriptPath = $PSScriptRoot
if (!$scriptPath)
{
if ($psISE)
{
$scriptPath = Split-Path -Parent -Path $psISE.CurrentFile.FullPath
} else {
Write-Host -ForegroundColor Red "Cannot resolve script file's path"
exit 1
}
}
} catch {
Write-Host -ForegroundColor Red "Caught Exception: $($Error[0].Exception.Message)"
exit 2
}
Write-Host "Path: $scriptPath"
嗯
p.S.包括完整的错误处理。相应地根据您的需要进行调整。以下是一个示例:
$ScriptRoot = ($ScriptRoot, "$PSScriptRoot" -ne $null)[0]
import-module $ScriptRoot\modules\sql-provider.psm1
Import-Module $ScriptRoot\modules\AD-lib.psm1 -Force
小心使用
$psstriptrot
。这是模块中预定义的变量。PowerShell团队最终将在普通脚本中引入$PSScriptRoot
——这正是我所希望的。当我发现这个变量时,我真的很兴奋——我想我可以取代$MyInvocation/Split Path dance,但是没有。:-)希望看到这一点的人们应该投票:这已经发生了。如果您在PowerShell 2上使用此技巧,请确保编写:If(!$PSScriptRoot){$PSScriptRoot=Split Path$MyInvocation.MyCommand.Path-Parent}
以便在PowerShell 3中“正常工作”,我相信Split Path$script:MyInvocation.MyCommand.Path通常比Split Path$MyInvocation.MyCommand.Path-Parent更受欢迎。有关更多信息,请参阅本文:值得注意的是:如果在PowerShell ISE的脚本控制台中键入:$PSScriptRoot和$PSCommandPath,或者仅执行脚本文件的选定部分,则它们将为空。如果整个脚本都运行,它就可以工作。只是观察一下你在“DOS”中是如何做到这一点的(我想在本世纪你指的是Windows)。只执行:CD“%~dp0”不是更好吗?在cmd.exe shell中,可以使用CD/D“%~dp0”
来执行。