Reputation: 1242
Afternoon all,
I've got a chunk of Powershell that does something along the lines of:
if (($env:COMPUTERNAME -like "AAA*") -or ($env:COMPUTERNAME -like "DAA*") -or ($env:COMPUTERNAME -like "JJD*")) {
#<Snip> (Do STuff)
}
else {
#<snip> (Do some other stuff)
}
Because I have multiple machine types (prefixed with multiple varying length codes) - I am potentially looking at having a 10-15 item "or" list for the initial if statement.
Is there a cleaner way of doing this or is the above snippet the cleanest way?
This will be run on PS v4 on 8.1/2012R2 kit only - so requirement for a solution to be backward compatible.
Upvotes: 0
Views: 9859
Reputation: 11
Generic check for mutiply wildcards:
$List | ? { $a = $_; ($Wildcards | ? { $a -like $_ }).Count -gt 0 }
Upvotes: 1
Reputation: 383
I guess what OP wanted was something like (pseudo code)
If ($a -like $b -or $c -or $d -or $e)
{
do stuff
}
Upvotes: 0
Reputation: 136114
You could put all your prefixes in to an array and reverse the functionality
$myArray = "AAA*","DAA*","JJD*"
$result = $myArray | where {$env:COMPUTERNAME -Like $_}
$result.length
will be zero if no matches.
Upvotes: 2
Reputation: 46710
Regex based solution as well
$prefixes = "AAA","DAA","JJD"
$regex = "^({0})" -f (($prefixes | ForEach-Object{[regex]::Escape($_)}) -join "|")
If($env:COMPUTERNAME -match $regex){
Write-host "Something should be happening"
}
Put all the letter prefixes into an array then build a regex string with that array that will look for a $env:COMPUTERNAME
that starts with either of the matches in the array. Using your example the regex match would look like this
^(AAA|DAA|JJD)
While not needed with your examples, it is a good measure to ensure no control characters end up in the regex string so we use the static method [regex]::Escape($_)
to ensure that. For simplicity's sake you could have also done
$regex = "^({0})" -f ($prefixes -join "|")
Upvotes: 1
Reputation: 175
if they are all 3 letter codes, why not get the first three characters and setup a switch? You could set some variables and then do work based on those variables after the switch statement.
switch ($env:computername.substring(0,3))
{
'AAA'
{ <do stuff> }
'BBB'
{ <do stuff> }
Default
{ <do stuff> }
}
Upvotes: 1
Reputation: 24555
One way is to use the switch statement.
switch -wildcard ( $Env:COMPUTERNAME ) {
"AAA*" {
# do stuff here, or set variable
}
"DAA*" {
# do stuff here, or set variable
}
"JJD*" {
# do stuff here, or set variable
}
}
Get more information by typing this command:
help about_Switch
Upvotes: 1