Wont add value to expression - powershell

I am trying to popluate the $targetdb with a string value using the .startswith but it wont fill in. I have also tried using the the -match operator and still no luck. I just need to the $targetdb filled by the users first character of the lastname. Any help would be great thank you.
$lastname = "$($_.Surname)"
$region = Read-Host 'Region? (CR, XR, SR, CHI)'
If ($region -match "CR") {$office = "CR*"}
ElseIf ($region -match "SR") {$office = "SR*"}
ElseIf ($region -match "XR") {$office = "CR XR"}
ElseIf ($region -match "CHI") {$office = "NR*"}
Else {Write-Error 'Enter Correct Parameter!'}
$depart = Read-Host 'Department Name?'
If ($lastname.StartsWith("R-Z")) {$TargetDB = "$crmbxdb3"}
$filter = "department -like ""$depart"" -and Enabled -eq ""True"" -and office -like ""$office"""
$output = Get-ADUser -Filter $filter | Format-Table #{label="EmailAddress";expression={$_.UserPrincipalName}}, #{label="LastName";expression={$_.Surname}}, #{label="TargetDatabase";expression={$TargetDB}} | Out-String
$output

"$lastname".StartsWith("R-Z") is probably not doing what you expect - it tests whether the string starts literally with the three characters "R","-" and "Z".
If you want to test for a range of characters, use -match:
if($lastname -match "^[r-z]") { $TargetDB = "$crmbxdb3" }

Have you tried
If ("$lastname".StartsWith("R")) {$TargetDB = "$crmbxdb3"}
instead of
If ("$lastname".StartsWith("R")) {$TargetDB = "$crmbxdb3"}**
it works for me...
try also this: If ($lastname.StartsWith("R")) {$TargetDB = "$crmbxdb3"} skipping quotes for $lastname

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)

Compare 2 ActiveDirectory properties using Powershell

My Goal is to List all ADusers where the property proxyAddresses does not contain the value from the mail property.
My first step is to get all users that have both values filled with:
$ADUser = Get-ADUser -Properties Name,Mail,proxyAddresses -Filter {proxyAddresses -like '*' -and mail -like '*'}
then i try to run it trough a foreach loop with an integrated if statement
$result = foreach ($User in $ADUser){
$proxystring = $User.proxyAddresses
$Mailstring = $User.Mail
$Mailstring = $Mailstring.ToString()
if ($proxystring -contains '*$Mailstring*'){
Write-Host 'läuft'
}
else{
Write-Output($User).Name
}
}
in the if statement i tried
if ($proxystring -contains '*$Mailstring*')
if ($proxystring -contains $Mailstring)
if ($proxystring -like $Mailstring)
if (($proxystring).contains($Mailstring))
As in the mainpart of the Code seen, I also tried to pass it to a string because i thought the format might be a problem.
Everywhere i looked a variable only gets matched with a string, not with other variables.
If anyone happens to know what my mistake is i would be grateful.
You would need to remove the preceding SMTP: / smtp: from each address in proxyAddresses for this to work properly:
$result = :outer foreach ($User in $ADUser){
foreach($address in $user.proxyAddresses) {
# remove the leading `smtp:` from each address
$mail = $address -replace '^smtp:'
# and compare, if the user's mail was in the `proxyAddresses` array
if($mail -eq $User.mail) {
# there is no need to keep checking, we can skip this user
# and go next
continue outer
}
}
# if the user's `mail` wasn't found in the `proxyAddresses` array
# output this user
$user
}
You could also use -notcontains to simplify the above code a lot but this requires prepending smtp: to user's mail attribute:
$result = foreach ($User in $ADUser){
if($user.proxyAddresses -notcontains ('smtp:' + $user.mail)) {
$User
}
}

Use -like variable in powershell if statement

Is it possible to use -like and wildcard search in a PowerShell if statement - i'm trying to do something like this;
$name = 'matt'
$current = 'matt#'
if ($name -like "*$current*"){
write-host("this name matches")
}
However the "$current" does not work - please advise?
The other way around works...
$name = 'matt#'
$searchkey = 'matt'
if ($name -like "*$searchkey*"){
write-host("this name matches")
}

Check if string is in list of strings

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
}

powershell script that pulls WMIC data from remote workstations

I am looking for a Powershell script that queries remote workstations for installed Windows updates looking for specific HotFixes (6 of them) and then reports back which ones (if any) are installed.
Query would get the remote host's name from a text file.
I found this script on Microsoft's site and tried to alter it, but I have no where near the skills needed to it.
Function Get-MSHotfix
{
$outputs = Invoke-Expression "wmic qfe list"
$outputs = $outputs[1..($outputs.length)]
foreach ($output in $Outputs) {
if ($output) {
$output = $output -replace 'y U','y-U'
$output = $output -replace 'NT A','NT-A'
$output = $output -replace '\s+',' '
$parts = $output -split ' '
if ($parts[5] -like "*/*/*") {
$Dateis = [datetime]::ParseExact($parts[5], '%M/%d/yyyy',[Globalization.cultureinfo]::GetCultureInfo("en-US").DateTimeFormat)
} elseif (($parts[5] -eq $null) -or ($parts[5] -eq ''))
{
$Dateis = [datetime]1700
}
else {
$Dateis = get-date([DateTime][Convert]::ToInt64("$parts[5]", 16))-Format '%M/%d/yyyy'
}
New-Object -Type PSObject -Property #{
KBArticle = [string]$parts[0]
Computername = [string]$parts[1]
Description = [string]$parts[2]
FixComments = [string]$parts[6]
HotFixID = [string]$parts[3]
InstalledOn = Get-Date($Dateis)-format "dddd d MMMM yyyy"
InstalledBy = [string]$parts[4]
InstallDate = [string]$parts[7]
Name = [string]$parts[8]
ServicePackInEffect = [string]$parts[9]
Status = [string]$parts[10]
}
}
}
}
Here's something I wrote up for a very similar situation:
ForEach($Server in $ServerList){
$QFE=Get-WmiObject Win32_QuickFixEngineering -ComputerName $Server
$IDRX = 3188732,3188743,3192392 -join '|'
$QFE|?{$_.HotFixId -match $IDRX}
}
Mind you, I was looking for QFEs 3188732, 3188743, and 3192392, but you could easily modify that line for the ones you are looking for.