使用 Test-path 检查多个路径

Check multiple path with Test-path

在我的函数中,我有 3 个没有强制性参数也没有位置参数 Folder1, Folder2 and Folder3,在 运行 我的函数之前,如果文件夹存在,我想检查每个选定的参数。它必须是动态的,因为用户可以随机指定一个或两个或所有树文件夹。 提前致谢。

您可以将数组传递给 Test-Path

Test-Path c:, d:, e:
True
True
True

编辑

所以我从你的评论中相信你有这样的事情:

$mypaths = "c:","d:",$null
Test-Path $mypaths

发出以下错误:

Test-Path : Cannot bind argument to parameter 'Path' because it is null.

那你可以试试这个:

$mypaths = "c:","d:",$null
$mypaths | Foreach { if ($_){Test-Path $_}}

结果只有两条有效路径。

因此您可以考虑检查返回值:

$valid = $mypaths | Foreach { if ($_){Test-Path $_}}

write-host "Variable `$mypaths contains $($mypaths.count) paths, and $($valid.count) were found valid"

输出:

Variable $mypaths contains 3 paths, and 2 were found valid