Elseif 语句仅读取基于布尔语句的 "if" 部分

Elseif statements only reading the "if" portion in boolean based statements

大家好, 我浏览了一些以前的帖子,不幸的是,无法找到适用于我的特定情况的答案。背景是我有一个脚本可以删除 Visual Studio 及其所有有效的目录 paths/registry 条目。我遇到的问题是验证。我正在尝试验证某些 paths/directories 已被删除。

实际情况是,该函数只会查看第一个“if”语句,似乎会忽略我包含的其他 elseif 和 else 语句。我知道我可能把它们格式化错了,因为我是 powershell 的新手可能有更好的方法来做到这一点,如果是这样,请随时分享。代码如下:

    function scriptvalidation{
$l1 = Test-Path -path "Path placeholder Number One"
$l2 = Test-Path -path "Path placeholder Number Two"
$l3 = Test-Path -path "Path placeholder Number Three"
$r1 = Test-Path -path "Registry path Number One"
$r2 = Test-Path -path "Registry path Number Two"
$r3 = Test-Path -path "Registry path Number Three"
$DirectoryArray = @($l1, $l2, $l3)
$RegistryArray = @($r1, $r2, $r3)

上面是我用的变量和数组,下面是语句:

    if ($l1 -eq $true) {
Write-Host ("Path Placeholder number one was found and needs to be removed")
}
elseif ($l2 -eq $true) {
Write-Host ("Path Placeholder Number Two was found and needs to be removed")
}
elseif ($l3 -eq $true) {
Write-Host ("Path Placeholder Number three was found and needs to be removed")
}
else{[String] "$DirectoryArray -eq $false" Write-Host "Directory paths were removed successfully"
}


    if ($r1 -eq $true) {
Write-Host ("Registry Placeholder Number One was found and needs to be removed")
}
elseif ($r2 -eq $true) {
Write-Host ("Registry Placeholder Number Two was found and needs to be removed")
}
elseif ($r3 -eq $true) {
Write-Host ("Registry Placeholder Number Three was found and needs to be removed")
}
else{[String] "$RegistryArray -eq $false Write-Host "Registry paths were removed, script completed successfully"
}
scriptvalidation

我的脚本的这一部分到此结束,我无法正确地到达 运行。当我安装有问题的程序时,我得到的输出如下: “找到第一个路径占位符,需要将其删除” “已找到第一个注册表占位符,需要将其删除” 仅此而已。

我知道我的设置有误,但作为新手,很难知道哪里错了。

如有任何帮助,我们将不胜感激。

elseif 表示“当且仅当不满足先前条件并且满足此条件”。由于无论文件 1 是否存在,文件 2 都可能存在,因此这不是您想要的行为。

而是使用 3 个 单独的 if 语句:

if ($l1) {
   Write-Host ("Path Placeholder number one was found and needs to be removed")
}

if ($l2) {
   Write-Host ("Path Placeholder Number Two was found and needs to be removed")
}

if ($l3) {
   Write-Host ("Path Placeholder Number three was found and needs to be removed")
}

现在唯一需要的是最后一个 else 块 - 在这里您需要测试 $l* 变量是否保持 $true,我们可以这样做:

if(-not($l1 -or $l2 -or $l3)){
  [string]"$DirectoryArray -eq $false" 
  Write-Host "Directory paths were removed successfully"
}
如果三个变量中的 保持 $true

$l1 -or $l2 -or $l3 将评估为真,因此如果它们都是 $false,则此表达式将从 $false 到 - -not 然后反转它所以只有 $true 如果变量的 none 是 $true