vendredi 21 février 2020

PowerShell If Statements: IF equals multiple specific Texts

Good Morning! I'm working on a script and I'm trying to include an IF/Else statement based off a text variable with multiple specific text options and to test for a directory path that will be named after the variable and make the directory if it doesn't exist. So example would be

$text = [Microsoft.VisualBasic.Interaction]::InputBox($msg, $title,"")

If($text -match "Specific Text1") -and (!(Test-Path $Path\$text))){

new-item -ItemType directory -path $Path\$text

}
ElseIF($text -match "Specific Text2") -and (!(Test-Path $Path\$text))){

new-item -ItemType directory -path $Path\$text

}

ElseIF($text -match "Specific Text3") -and (!(Test-Path $Path\$text))){

new-item -ItemType directory -path $Path\$text

}

ElseIF($text -notmatch "Specific Text1","Specific Text2","Specific Text3"){
write-host "invalid input"
}

Im providing users a list of the valid inputs, that can be entered into the text box. When I try running the script I'm still getting errors saying the folder already exists and it's not ignoring it like it should be.

A side question is there a cleaner way to write this?

Edit

Below is the answer that worked perfect for me. Thank you everyone for your responses!

$text = [Microsoft.VisualBasic.Interaction]::InputBox($msg, $title,"")
$AcceptableText = @("Specific Text1","Specific Text2","Specific Text3")
If ($text -in $AcceptableText)
{
    If (!(Test-Path $Path\$text)) 
    {
        new-item -ItemType directory -path $Path\$text
    }
}
Else
{
    write-host "invalid input"
}

Aucun commentaire:

Enregistrer un commentaire