Check if string is in list of strings - powershell

Context:
We are making an API to get a list of all VMs and the filter it, using if loops, to return only VMs with name starting only with the values in $MachineList.
The list of servers is split in 2:
set 1: srv-a-1, srv-a-2, srv-b-1, srv-b-2, srv-c-1, srv-c-2, etc.
set 2: tst-a-1, tst-a-2, tst-b-1, tst-b-2, tst-c-1, tst-c-2, etc.
This is the script:
$EnvironmentList = "Environments-4" -or "Environments-5" -or "Environments-41" -or "Environments-61"
$MachineList = "srv-a*" -or "srv-b*" -or "srv-c*" -or "srv-d*" -or "srv-e*" -or "srv-f*" -or "srv-g*" -or "srv-h*" -or" srv-i*" -or "srv-j*" -or "srv-k*" -or "srv-l*"
function CheckService {
$MachinesRequest = (Invoke-WebRequest -Method Get -Headers #{"X-system-ApiKey"="Hashed-API-Key-Value"} -URI https://url-to-site.local/api/machines/all).Content | ConvertFrom-Json
foreach ($Machine in $MachinesRequest) {
if ($EnvironmentList -contains $Machine.EnvironmentIds) {
if ($MachineList -contains $Machine.Name) {
$Machine.Name
}
}
}
}
CheckService
We're trying to return just the items which match the values in the machine list however this is returning the full list of machines (both srv* and tst*).

First and foremost, $MachineList = "srv-a*" -or "srv-b*" -or ... won't do what you apparently think it does. It's a boolean expression that evaluates to $true, because PowerShell interprets non-empty strings as $true in a boolean context. If you need to define a list of values, define a list of values:
$MachineList = "srv-a*", "srv-b*", ...
Also, the -contains operator does exact matches (meaning it checks if any of the values in the array is equal to the reference value). For wildcard matches you need a nested Where-Object filter
$MachineList = "srv-a*", "srv-b*", "srv-c*", ...
...
if ($MachineList | Where-Object {$Machine.Name -like $_}) {
...
}
A better approach in this scenario would be a regular expression match, though, e.g.:
$pattern = '^srv-[a-l]'
...
if ($Machine.Name -match $pattern) {
...
}

use -eq for an exact match. use -match or -contains for a partial string match
$my_list='manager','coordinator','engineer', 'project engineer',
$retval=$False
if ($dd_and_pm -eq "engineer")
{
$retval=$True
}

Related

elseif not being recognized - Variable not being assigned correct value

I have written a small script that checks the HostName in a URL for a sharepoint Site Collection and then gives a variable a value based on that HostName but the elseif in the script is not working:
$sites = Get-SPSite https://contoso.domain.cs/sites/sc
$Logo = $null
if ($sites.HostName -eq "contoso.domain.cs" -or "contoso1.domain.cs" -or "contoso2.domain.cs")
{
$Logo = "/path/to/logo.jpg"
}
elseif ($sites.HostName -eq "contosoq.domain.cs" -or "contoso1q.domain.cs" -or "contoso2q.domain.cs")
{
$Logo = "/path/to/logo2.jpg"
}
elseif ($sites.HostName -eq "contoso3q.domain.cs")
{
$Logo = "/path/to/logo3.jpg"
}
else {}
The Variable $Logo is always getting the first value "/path/to/logo.jpg" even when the hostname is not equal to "contoso.domain.cs" or "contoso1.domain.cs" or "contoso2.domain.cs"
please help me if you see the error im making. thank you!
You need to alter the way you check the conditions. The entire expression to be evaluated must be repeated after each -or.
For example:
if ($sites.HostName -eq "contoso.domain.cs" -or "contoso1.domain.cs" -or "contoso2.domain.cs")
Could be changed to check each condition explicitly:
if ($sites.HostName -eq "contoso.domain.cs" -or $sites.HostName -eq "contoso1.domain.cs" -or $sites.HostName -eq "contoso2.domain.cs")
Or you could do it by using the -in comparison:
if ($sites.HostName -in ("contoso.domain.cs", "contoso1.domain.cs", "contoso2.domain.cs"))
As mentioned in the comments by iRon the following technique also works:
if ("contoso.domain.cs", "contoso1.domain.cs", "contoso2.domain.cs" -eq $sites.HostName)

How to check parameter is null in where clause in powershell

I'm trying to write a PowerShell command but stucked on where clause. What i want to achieve is if parameters are not defined, where clause needs to ignore them. I tried this code but couldn't success.
I have parameters;
Param(
[parameter(position=0)]
[String]
$JobName,
[parameter(position=1)]
[String]
$JobID
)
And where clause which i tried and failed,
$Timerjob = Get-SPTimerJob | where { ($_.Id -eq $JobID) -or ($_.Title -eq $JobName) }
If $JobName or $JobID is null (or both of them), where clause should ignore them
how can i achieve this without writing multiple if clause?
Continuing from my comment:
To retrieve all Timer Jobs if both $JobName and $JobID are empty, you will need to add that condition to the Where-Object cmdlet:
$Timerjob = Get-SPTimerJob |Where-Object {
(!$JobName -and !$JobID) -or ($_.Id -eq $JobID) -or ($_.Title -eq $JobName)
}
This means if both $JobName and $JobID are empty, the condition (!$JobName -and !$JobID) is $True. Any condition with the -or comparison operator won't be able to change that (to $false) causing the whole condition to be true in that matter and all Timer Jobs returned.
In case you would like to make a difference between an empty string filter and a parameter that isn't supplied, you would probably want to do something like this:
$Timerjob = Get-SPTimerJob |Where-Object {
($PSBoundParameters.ContainsKey('JobName') -and $PSBoundParameters.ContainsKey('JobID')) -or
($_.Id -eq $JobID) -or ($_.Title -eq $JobName)
}
In this case you would e.g. still be able to retrieve Time Jobs with an empty title (-JobName ''), if even possible.

Need help on where-object in powershell

if I execute the below code it is not filtering, it is returning all the results.
$R datatype is below
{} creates a [scriptblock] literal, the value of which will always evaluate to $True when cast to [bool].
Remove the {} around the comparisons inside the filter block:
$filteredRows = $R |Where-Object {$_.db_sync_state -eq 'NOT SYNCHRONIZING' -or -not $_.is_failover_ready}
As Gert Jan Kraaijeveld mentions, you can use () to group the individual comparisons if required:
$filteredRows = $R |Where-Object {($_.db_sync_state -eq 'NOT SYNCHRONIZING') -or (-not $_.is_failover_ready)}

How to "if" on multiple entries of an array?

I'm wondering if there's a way to simplify the code below by having an if statement that checks if a value matches one of the entries of an array...
The code I ended up with:
foreach ($sourceLine in $source) {
$sourceAVTrim = $sourceLine.ID.Remove(0, 1)
$sourceAV = "av" + $sourceAVTrim
if ($SourceLine.MAC -like "VCO*" -or $SourceLine.MAC -like "FOO*" -or $SourceLine.MAC -like "HOM*" -or $SourceLine.MAC -like "EOP*" -or $SourceLine.MAC -like "PCP*" -or $SourceLine.MAC -like "BUI*" -or $SourceLine.MAC -like "DML*") {
if ($SourceLine.MAC -like "*ADM" -or $SourceLine.MAC -like "*SAL" -or $SourceLine.MAC -like "*PLA" -or $SourceLine.MAC -like "*PLN" -or $SourceLine.MAC -like "*PLC" -or $SourceLine.MAC -like "*PLS") {
Write-Host "$($SourceAV) will NOT receive SMS - $($SourceLine.MAC)" -ForegroundColor Red
} else {
Write-Host "$($SourceAV) will receive SMS - $($SourceLine.MAC)" -ForegroundColor Green
}
} else {
Write-Host "$($SourceAV) will NOT receive SMS - $($SourceLine.MAC)" -ForegroundColor Red
}
}
But how can I set 2 arrays instead and have IF check my value against each entry?
$startMACs = #("VCO","FOO","HOM","EOP","PCP","BUI","DML")
$endMACs = #("ADM","SAL","PLA","PLN","PLC","PLS")
For exact matches you could use the -contains or -in operator. However, in your case you want a partial match against multiple strings, so I'd go with a regular expression.
$startMACs = 'VCO', 'FOO', 'HOM', 'EOP', 'PCP', 'BUI', 'DML'
$pattern = ($startMACs | ForEach-Object { [Regex]::Escape($_) }) -join '|'
if ($SourceLine.MAC -match "^($pattern)") {
...
} else {
...
}
^ anchors the expression at the beginning of a line, so you'll get the matches beginning with those substrings.
To anchor the expression at the end of a line (so you'll get the matches ending with the substrings) replace "^($pattern)" with "($pattern)$".
$pattern is constructed as an alternation (VCO|FOO|HOM|...), meaning "match any of these substrings" ("VCO" or "FOO" or "HOM" or ...).
Escaping the individual terms before building the pattern is so that characters with a special meaning in regular expressions (like for instance . or *) are treated as literal characters. It's not required in this case (since there are no special characters in the sample strings), but it's good practice so that nothing unexpected happens should someone update the list of strings with values that do contain special characters.
Since your patterns all start with a 3 letter code, one possibility is to grab the start of the target string and match using the -in operator with the pattern collection:
$startMACs = #("VCO","FOO","HOM","EOP","PCP","BUI","DML","HDOM")
if($SourceLine.MAC.Substring(0,3) -in $startMACs) {
# Do something
}
So, if $SourceLine.MAC is, say, EOP123, the substring() call grabs the EOP part, then compares it to each entry in the $startMACs array, returning true if it finds a match, and false otherwise - should be true in this example.
You can do something similar for the end patterns:
$endMACs = #("ADM","SAL","PLA","PLN","PLC","PLS")
if($SourceLine.MAC.Substring($SourceLine.MAC.Length - 3,3) -in $endMACs) {
# Do something
}

Powershell: How can you determine which variable in an "if" statement triggered True?

In powershell, I have code that looks like this. The intention is to populate a handful of variables with data if a user doesn't supply any:
if ($1 -eq $null){$1 = "N/A"}
if ($2 -eq $null){$2 = "N/A"}
if ($3 -eq $null){$3 = "N/A"}
Is it possible to condense these down to something like this?
if ($1 -or $2 -or $3 -eq $null){
$FILLER = "N/A"
}
Where $FILLER is the variable(s) that returned True?
Edit: For example, if $2 was null but $1 and $3 were not- then the code would assign N/A to $2.
Note: I don't have a problem with the individual if statements, I'm just aiming to condense repetitive code.
You can use Get-Variable cmdlet. That cmdlet return PSVariable objects, which represent variables, to you. PSVariable objects have Value property, which allows you get and set value of variable. So that, you can filter variables which have particular value ($null), and then assign new value to them.
Get-Variable 1, 2, 3 |
Where-Object { $null -eq $_.Value } |
ForEach-Object { $_.Value = 'N/A' }
You can use ! to define -eq $null or -eq $false:
if (!$1 -or !$2 -or !$3){
$FILLER = "N/A"
}
You could change the order a bit:
$1 = if (!$1) { "N/A" }
But what you're really asking, how to determine which of multiple conditions returned $true in an if statement, is not possible.
If you want to pass an array of values and get back the ones that satisfy a condition, consider Where-Object:
$result = $1,$2,$3 | Where-Object { -not $_ }
If the condition is a string operator like -match or -like it actually works on arrays already and returns an array:
$result = 'apple','apply','ape','zebra' -like 'app*'