Test-Path是否接受相对路径?

3
相对路径在使用Test-Path cmdlet时似乎有效,但我找不到任何官方文件支持此操作。
如果它们得到支持:
- 它们在Powershell 2.0中是否有效? - 它们相对于哪个路径? - 脚本路径?执行路径?还是其他地方? - 如何更改根相对路径?(例如将脚本路径更改为其他内容)
我的有限测试表明它相对于脚本路径(脚本所在的文件夹)。这总是正确的吗?如果是这样,那么我可以可靠地使用Join-Path来更改该路径。

3
在 PoSh 中,相对路径是相对于 PoSh 认为的当前位置的位置。这可以是脚本启动的位置、脚本启动时操作系统的当前位置或脚本设置的当前位置。与所有脚本或编程语言一样,如果可以避免使用相对路径,请不要使用相对路径。歧义是危险的。 - Lee_Dailey
1
我建议查看关于PATH语法的以下文档。这些文档似乎没有回到2.0版本,至少我没有快速找到。https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_path_syntax?view=powershell-5.1 - Stringfellow
1
关于“当前工作位置”,请查看文档。https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_locations?view=powershell-5.1 - Stringfellow
最安全的方法是使用自动变量,例如$PSScriptRoot - Santiago Squarzon
1个回答

2
是的,Test-Path 接受相对路径。
通常情况下,相对路径被解释为“相对于会话的当前 位置”,如自动变量 $PWDGet-Location 的输出所反映的那样。
当前位置也可以表示为 .
请注意,虽然位置通常是文件系统的“目录”,但 PowerShell 的提供程序模型也允许以类似于文件系统的方式呈现其他数据存储,例如 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所指出的那样,在脚本中最好使用完整路径,除非你事先仔细控制了当前位置。但请注意,改变当前位置(用Set-LocationPush-Location)会在整个会话中改变它,因此最好在退出脚本之前恢复先前的位置,你可以通过成对的Push-Location/Pop-Location调用来实现。
如果您需要相对于脚本位置测试路径,则可以使用自动变量$PSScriptRoot,正如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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接