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(
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(
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(
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.
Answer from Matthew on Stack OverflowLooks 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(
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(
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(
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.
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(
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"
}
}
}
Using an If Statement to check a String *
PowerShell $null Variable in an IF Statement
PowerShell if-statement with a condition in a string - Stack Overflow
If A or B equals C
Videos
Hello Everyone. First, Apologies on this question. I know this has had to have been asked before but I'm not sure exactly how to word the question and all searches give me a ton of results for the wrong thing. (Wild card searches in this case)
The issue I'm having, I'm writing a script that is checking and creating some website information from a CSV. I'm creating these website URLs from ARecords and CName records pulled from DNS. Unfortunately, some of those records using * for wildcard in the DNS entries. So I get a list of websites with https://*.website.com
I'm attempting to use if statements to get rid of these instances. The problem I'm running into to is using the condition with a string * in it. For example:
if ($arecord.ARecordName -contains "https://*.") <- Is going to look for wildcard(anything) in between https:// and .
When attempting to use ` before *, it errors out. Single quotes around the outside are also not removing the * search.
At this point, I'm at a loss and just wanted to throw out something that is probably relatively easy into the world to see if someone can throw me a bone.
The problem is here:
$UserPref = if ($UserPref -eq $null){$UserPrefN = $UserGN} Else{$UserPrefN = $UserPref}
You’re doing a comparison on the $UserPref variable which has not been set because the comparison is in the assignment statement. This is not technically illegal, but you have strict mode on which will throw an error when you reference a variable that hasn’t been initiated. You can avoid this error by skipping the Set-StrictMode cmdlet.
However, the way you are assigning the $UserPref variable seems a bit wonky to me. It looks like you’re trying to check if it’s already set and then set some other variable values based on this comparison. Since each action you’re taking in the if construct is an assignment, there is no need to encapsulate those in the $UserPref assignment. Also, instead of checking for -eq $null in the if condition, you could just check for the existence of $UserPref:
if (!$UserPref){$UserPref = $UserGN}
I know I’m going to be kicking myself, but since I still consider myself a n00b with PS, I’ll try not to kick too hard.
I’ve got a script for new hires that works intermittently. HR insists that AD accounts use a person’s legal name, however many people prefer their nicknames for their email and display names, so a PreferredName field was created in HRIS. I’m checking for a preferred name ($UserPref) and if it exists I assign it to $UserPrefN and if it doesn’t, I assign their first name ($UserGN) to $UserPrefN. If $UserPref is blank ($null), sometimes it works and sometimes it doesn’t, lately more often than not it doesn’t and $UserPrefN doesn’t get set. It’s got to be my syntax, but I don’t see it.
[PS] C:\Windows\system32>Set-Strictmode -Version Latest -Verbose
[PS] C:\Windows\system32>$User = 'AccountName'
[PS] C:\Windows\system32>$UserSN = 'LastName'
[PS] C:\Windows\system32>$UserGN = 'FirstName'
[PS] C:\Windows\system32>$UserFI = $UserGN.substring(0,1)
[PS] C:\Windows\system32>$UserPref =
>> if ($UserPref -eq $null){$UserPrefN = $UserGN} Else{$UserPrefN = $UserPref}
>>
The variable '$UserPref' cannot be retrieved because it has not been set.
At line:2 char:5
+ if ($UserPref -eq $null){$UserPrefN = $UserGN} Else{$UserPrefN = $UserPref}
+ ~~~~~~~~~
+ CategoryInfo : InvalidOperation: (UserPref:String) [], RuntimeException
+ FullyQualifiedErrorId : VariableIsUndefined
[PS] C:\Windows\system32>
[PS] C:\Windows\system32>echo $UserPrefN
The variable '$UserPrefN' cannot be retrieved because it has not been set.
At line:1 char:6
+ echo $UserPrefN
+ ~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (UserPrefN:String) [], RuntimeException
+ FullyQualifiedErrorId : VariableIsUndefined
You might use the $ExecutionContext.InvokeCommand.ExpandString method to evaluate the string expression:
$test = 5
$myCheckTest = '$test -eq 4'
$ExecutionContext.InvokeCommand.ExpandString("`$($myCheckTest)")
False
$myCheckTest = '$test -eq 5'
$ExecutionContext.InvokeCommand.ExpandString("`$($myCheckTest)")
True
Note that the backtick (`) prevents the first dollar to be substituted so that you actual string expression will be something like: $($test -eq 4)
Or in your function:
if ($ExecutionContext.InvokeCommand.ExpandString("`$($myCheckTest)")) {
write-host "TEST MATCH"
} else {
write-host "TEST NO MATCH"
}
A more common way to do thing like this is, is to use a scriptblock:
$myCheckTest = {$test -eq 4}
$test = 5
if (&$myCheckTest) {
write-host "TEST MATCH"
} else {
write-host "TEST NO MATCH"
}
https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-expression
A collegae pointed me to the Invoke-Expression command:
if (Invoke-Expression $myCheckTest) {
write-host "TEST MATCH"
} else {
write-host "TEST NO MATCH"
}
This works within my actual script.
Source: https://github.com/Esri/arcgis-powershell-dsc/blob/main/Modules/ArcGIS/ArcGIS.psm1
Lines 1953 and 1973 specifically.
I am looking at some powershell code (link above), and don't understand why a simple boolean check is written as:
$JobFlag = $True
# more code here...
if ($JobFlag[$JobFlag.Count - 1] -eq $True) { # CODE HERE }There are some functions that might be called before the if-statement, but as far as I can tell, they return either $True or $False
Is there any reason for not writing a plain:
if ($JobFlag -eq $True)
I am by now means an experienced powershell user, therefore curious.