在目录中搜索特定的文件类型,如果PowerShell中存在,则返回true或false



现在这可能是一个非常简单的修复程序,但我似乎无法获得它。我正在尝试搜索一个目录,它的子文件夹中有一个特定的文件类型。如果文件存在,我的代码当前返回true,但我也试图让它在终端上返回false。下面是我的代码

Get-ChildItem "$ScriptPath$kit" -recurse -include "*.pem"| ForEach-Object {Test-Path $_}

现在,对于具有PEM文件的文件夹,它将在终端上以true的形式返回。但我希望它也能在没有文件的文件夹的终端上以false的形式返回,因为我正计划使用truefalse来执行不同的代码集。

这个很简单。如果$target_files有值,则返回true,否则返回false。

$target_files = Get-ChildItem "$ScriptPath$kit" -recurse -include "*.pem"
if($target_files){
write-host "This returns true if there are files."
}
else{
write-host "This returns false if there are no files."
}

如果你有powershell 7,你可以使用三元运算符,但不是所有人都有powershell,因此如果你不喜欢If/ELSE方法,这里有一种更快、更短的方法来实现这一点$结果将返回true或false,具体取决于文件是否存在。

$target_files = Get-ChildItem "$ScriptPath$kit" -recurse -include "*.pem"
$result = (${true}, ${false})[-NOT $target_files]
$s = 'C:UsersuserDesktopSource'
foreach ($d in (Get-ChildItem -Recurse $s -Directory:$true)) {
if ($d.GetFiles('*.pem')) { 
$true 
} else { 
$false 
}
}

这应该让你开始。。。我真的希望PowerShell有一个内置的三元结构。。。

最新更新