我需要一些帮助,因为test-path
只返回$true
或$false
。
我需要从$path返回最后一个存在的文件夹。
$path = \\test.pl\power\shell\test\company
但最后一个存在的是\shell
文件夹。
那么如何得到一个像这样的返回值:
$existingpath = \\test.pl\power\shell
$notexisting = \test\company
我需要一些帮助,因为test-path
只返回$true
或$false
。
我需要从$path返回最后一个存在的文件夹。
$path = \\test.pl\power\shell\test\company
但最后一个存在的是\shell
文件夹。
那么如何得到一个像这样的返回值:
$existingpath = \\test.pl\power\shell
$notexisting = \test\company
3条答案
按热度按时间pes8fvy91#
尝试使用管道解决此问题:
for
循环创建了一个临时变量$p
,这样原始路径就不会被破坏。在每次迭代时,它输出变量$p
,由于PowerShell的隐式输出行为,该变量会自动添加到数组中。然后将$p
设置为$p
的父路径(带有单个未命名参数的Split-Path
返回父路径)。当不再有父级时,循环退出。Where-Object | Select-Object
行看起来效率不高,但由于Select-Object
参数-First 1
,它实际上只测试了必要数量的路径。当找到第一个现有路径时,将退出管道(类似于循环中的break
语句)。以上是公认的答案。随后添加了以下解决方案。它的效率更高,因为它只根据需要调用
Split-Path
,而不需要Where-Object
和Select-Object
。r3i60tvu2#
您可以使用
Split-Path
、Test-Path
和while
循环逐个检查每个文件夹路径:rjee0c153#
除了第一个答案之外,优选的是在处理之前解析和测试所传递路径的根:
或者使用.NET方法: