大家好,我瀏覽了以前的一些帖子,不幸的是,無法找到適用于我的特定情況的答案。背景是我有一個腳本,它洗掉了 Visual Studio 及其所有有效的目錄路徑/注冊表項。我遇到的問題是驗證。我正在嘗試驗證是否洗掉了某些路徑/目錄。
發生的情況是,該函式只會查看第一個“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
我的腳本的這一部分到此結束,我無法正常運行。當我安裝了有問題的程式時,我得到的輸出如下:“找到第一個路徑占位符,需要洗掉”“找到第一個注冊表占位符,需要洗掉”,就是這樣,沒有別的.
我知道我的設定是錯誤的,但是作為新手,很難知道哪里出錯了。
任何幫助,將不勝感激。
uj5u.com熱心網友回復:
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"
}
$l1 -or $l2 -or $l3如果三個變數中的任何一個保持$true,則計算結果為 true ,因此如果它們全部成立$false,則此運算式將為$false--not然后將其反轉,因此僅$true當所有變數都不成立時才會如此$true
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/371048.html
