fmo*_*on1 2 string powershell path
我正在创建一个函数,我想验证传递给我的函数的字符串是否是格式正确的路径。Test-Path 确定路径是否存在,这是我不想要的。有没有正则表达式可以做到这一点?或者其他一些本机 Cmdlet?
谢谢。
您可以使用Test-Path -IsValid检查有效但不存在的路径:
Test-Path -LiteralPath 'C:\\Whatever' -IsValid\nRun Code Online (Sandbox Code Playgroud)\n但问题是,“有效”似乎与“格式正确”并不意味着同一件事。
\n例如,如果我使用D:\\Whatever它在我的机器上也有效,而则E:\\Whatever不是;因为没有这样的 PSDrive(但是C并且D)。
也奇怪,WSman:\\whatever就是Falsewhile HKCU:\\whateverisTrue,
它似乎确实认为 UNC 路径是有效的。
\n如果您打算尝试以另一种方式验证路径,您可以从一组无效字符开始,您可以使用[System.IO.Path]::InvalidPathChars.
但这里也有一些奇怪的事情,其中一个字符是,\xc2\xa7但又C:\\\xc2\xa7whatever从TrueTest-Path -IsValid。
我在这里提出的问题可能多于答案。
\n来自评论:
\n\n\n我正在寻找带有驱动器号和可能的目录的完全限定路径。“C:\\SomeDirectory\\ 或 D:\\blah\\blah”
\n
我认为这里要做的最直接的事情可能是首先检查路径是否“有根”,然后将其转换为[DirectoryInfo]:
if ([System.IO.Path]::IsPathRooted($path)) {\n # this will throw an exception if the path can't be used\n # for example Z:\\whatever is accepted, ZZ:\\whatever is not\n $validatedPath = ([System.IO.DirectoryInfo]$path).FullName\n}\nelse {\n throw [System.ArgumentException]"Only fully-qualified paths are accepted."\n}\nRun Code Online (Sandbox Code Playgroud)\n您还可以选择保留[DirectoryInfo]对象,而不是将其“转换”回字符串.FullName,因为该对象具有许多有用的属性和方法,即使该目录不存在也是如此。
$path = 'Z:\\whatever' -as [System.IO.DirectoryInfo]\n\n$path | Format-List *\n$path | Get-Member\nRun Code Online (Sandbox Code Playgroud)\n