PowerShell If Statements: IF equals multiple specific Texts
Looks like you're trying to create the directories if your user chooses one of 3 text phrases and the directory doesn't already exist, and complain to your user if they choose something other than the 3 text phrases. I would treat each of those cases separately:
$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"
}
Or you could test for the existence of the directory first like this:
$text = [Microsoft.VisualBasic.Interaction]::InputBox($msg, $title,"")
$AcceptableText = @("Specific Text1","Specific Text2","Specific Text3")
If (!(Test-Path $Path\$text))
{
If (($text -in $AcceptableText))
{
new-item -ItemType directory -path $Path\$text
}
Else
{
write-host "invalid input"
}
}
EDIT: Or, if you want to be tricky and avoid the Test-Path (as suggested by @tommymaynard), you can use the following code (and even eliminate the Try|Catch wrappers if you don't want error checking)
$text = [Microsoft.VisualBasic.Interaction]::InputBox($msg, $title,"")
$AcceptableText = @("Specific Text1","Specific Text2","Specific Text3")
If (($text -in $AcceptableText))
{
try { mkdir -path $Path\$text -ErrorAction Stop } #Change to -ErrorAction Ignore if you remove Try|Catch
catch [System.IO.IOException] { } #Do nothing if directory exists
catch { Write-Error $_ }
}
Else
{
write-host "invalid input"
}
EDIT: Also worth noting that there are many ways to Use PowerShell to Create Folders
Some nice, clean examples. Hope this helps.
Yes you can :) Note that in the switch statement, default is being executed when all the other cases are not matched. Please test it and let me know.
$text = [Microsoft.VisualBasic.Interaction]::InputBox($msg, $title,"")
if (!(Test-Path $Path\$text))
{
switch ($text)
{
"Specific Text1"
{
new-item -ItemType directory -path $Path\$text
}
"Specific Text2"
{
new-item -ItemType directory -path $Path\$text
}
"Specific Text3"
{
new-item -ItemType directory -path $Path\$text
}
default
{
write-host "invalid input"
}
}
}
Start by worrying about the input validation separately from the Test-Path
call:
$validValues = 'Specific text 1','Specific text 2','Specific text 3'
$text = [Microsoft.VisualBasic.Interaction]::InputBox($msg, $title,"")
if($validValues -notcontains $text) {
Write-Host "Invalid output"
}
elseif(!(Test-Path -LiteralPath $path\$text)) {
Write-Host "Item exists"
}
else {
New-Item -ItemType Directory -LiteralPath $Path\$text
}