elseif 语句仅读取基于布尔值的语句中的"if"部分



大家好,我查阅了以前的一些帖子,不幸的是,未能找到适用于我特定情况的答案。背景是一个I have脚本,它删除了Visual Studio及其所有有效的目录路径/注册表项。我遇到的问题是验证。我正在尝试验证某些路径/目录是否已删除。

所发生的是,函数将只查看第一个";如果";声明,似乎会忽略我包含的其他eif和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

这就结束了我的脚本的这一部分,我无法正常运行它。当我安装了有问题的程序时,我得到的输出如下:"路径占位符编号1已找到,需要删除";"注册表占位符编号1已找到,需要删除";就这样,没有别的。

我知道我错了,但作为一个新手,很难知道哪里错了。

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

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将求值为true,因此如果它们都是$false,则该表达式将是$false到--not,然后将其反转,因此只有当变量都不是$true时,它才是$true

相关内容

  • 没有找到相关文章