测试路径是否接受相对路径?
Does Test-Path accept Relative Paths?
使用 Test-Path
cmdlet 时,相对路径似乎有效,但我找不到任何官方文档支持这一点。
如果支持:
- 它们在 Powershell 2.0 中工作吗?
- 它们相对于的路径是什么?
- 脚本路径?执行路径?其他地方?
- 如何改变根目录的相对路径? (例如,其他内容的脚本路径)
我的有限测试表明它与脚本路径(脚本所在的文件夹)有关。总是这样吗?如果是这样,那么我可以可靠地使用 Join-Path
来改变该路径。
是的,Test-Path
接受相对路径。
与典型一样,相对路径被解释为相对于会话的当前location, as reflected in the automatic $PWD
variable and in the output from Get-Location
。
当前位置也可以表示为.
请注意,虽然位置通常是文件系统 目录 ,但 PowerShell 的 provider model 也允许以类似文件系统的方式呈现其他数据存储,例如 Windows 上的注册表,例如(驱动器 HKCU:
和 HKLM:
)
因此,下面的命令是等价的:
# Test if an item named 'foo' exists in the current location.
# If the current location is a *file-system* location, this
# could be either a file or a directory.
# Add:
# -PathType Container to test only for a directory (container item)
# -PathType Leaf to test only for a file (leaf item)
Test-Path foo
Test-Path .\foo
Test-Path (Join-Path $PWD foo)
作为 Lee Dailey notes, in scripts it is better to use full paths instead - unless you carefully control the current location beforehand, but note that changing the current location (with Set-Location
or Push-Location
) changes it session-wide, so it's best to restore the previous location before exiting your script, which you can do via paired Push-Location
/ Pop-Location
调用。
相比之下,如果您需要测试相对于您的脚本位置的路径,请使用automatic $PSScriptRoot
variable, as Santiago Squarzon建议:
# Test if a file or directory named 'foo' exists in the directory
# in which the enclosing script is located.
Test-Path (Join-Path $PSScriptRoot foo)
使用 Test-Path
cmdlet 时,相对路径似乎有效,但我找不到任何官方文档支持这一点。
如果支持:
- 它们在 Powershell 2.0 中工作吗?
- 它们相对于的路径是什么?
- 脚本路径?执行路径?其他地方?
- 如何改变根目录的相对路径? (例如,其他内容的脚本路径)
我的有限测试表明它与脚本路径(脚本所在的文件夹)有关。总是这样吗?如果是这样,那么我可以可靠地使用 Join-Path
来改变该路径。
是的,Test-Path
接受相对路径。
与典型一样,相对路径被解释为相对于会话的当前location, as reflected in the automatic $PWD
variable and in the output from Get-Location
。
当前位置也可以表示为.
请注意,虽然位置通常是文件系统 目录 ,但 PowerShell 的 provider model 也允许以类似文件系统的方式呈现其他数据存储,例如 Windows 上的注册表,例如(驱动器 HKCU:
和 HKLM:
)
因此,下面的命令是等价的:
# Test if an item named 'foo' exists in the current location.
# If the current location is a *file-system* location, this
# could be either a file or a directory.
# Add:
# -PathType Container to test only for a directory (container item)
# -PathType Leaf to test only for a file (leaf item)
Test-Path foo
Test-Path .\foo
Test-Path (Join-Path $PWD foo)
作为 Lee Dailey notes, in scripts it is better to use full paths instead - unless you carefully control the current location beforehand, but note that changing the current location (with Set-Location
or Push-Location
) changes it session-wide, so it's best to restore the previous location before exiting your script, which you can do via paired Push-Location
/ Pop-Location
调用。
相比之下,如果您需要测试相对于您的脚本位置的路径,请使用automatic $PSScriptRoot
variable, as Santiago Squarzon建议:
# Test if a file or directory named 'foo' exists in the directory
# in which the enclosing script is located.
Test-Path (Join-Path $PSScriptRoot foo)