Use -like variable in powershell if statement - powershell

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")
}

Related

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
}
}

Check a username list and if they already exist Powershell

I have a CSV with 100 Usernames i have to check now if they already exist. Whats the best way to do that?
And is there a possibility that if the Username "marmar" is already used the programm checks by its own if username "marmar1" or if that is used aswell "marmar2" is free?
Is it easier to read the Usernames through the csv or should i copy them into Powershell?
examples of Usernames:
marmar
langas
ianmow
lowbob
berret
lawpaw1
etc.
Open for ideas and tipps.$
Thanks very much
If your CSV file looks anything like
"UserName","OtherStuff"
"marmar","blah"
"langas2","blahblah"
"ianmow","blahblahblah"
"lowbob","blahblahblahblah"
"berret","blahblahblahblahblah"
"lawpaw1","blahblahblahblahblahblah"
You can do that with something like this:
$freeUserNames = Import-csv 'D:\UsersNamesToCheck.csv' | ForEach-Object {
#Check to see if the user already exists in AD
$name = $_.UserName
$dupes = Get-ADUser -Filter "SamAccountName -like '$name*'" -ErrorAction SilentlyContinue | Select-Object -ExpandProperty SamAccountName
$index = 1
# check if the username is already in use and if so, increase the index number and test again
while ($dupes -contains $name) {
$name = '{0}{1}' -f ($name -replace '\d+$'), $index++
}
$name
}
# output on screen
Write-Host "Unused usernames:`r`n"
$freeUserNames
Possible output:
Unused usernames:
marmar
langas1
ianmow1
lowbob
berret1
lawpaw2

Wont add value to expression

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

Powershell Issues with .contains function for strings

OK, i am trying to get this script to work and not continuously hit the same computers over and over and am having trouble getting it working. I don't think this is the best way to do it and if you have any suggestions please and thank you. Anyways there seems to be an issue with line 6 "IF (!$Succssful.Contains($Computer)) {" it doesn't shoot an error at me but instead ends the script per-maturealy. I have tried removing the "!" but no luck as I expected.
$Computers = "TrinityTechCorp"
$HotFixes = Get-Content HotFixes.csv
While ($Successful -AND $Successful.count -ne $Computers.count) {
ForEach ($Computer in $Computers) {
IF (!$Succssful.Contains($Computer)) {
If (Test-Connection $Computer) {
$Comparison = get-hotfix -ComputerName $Computer | Select -expand HotFixID
ForEach ($HotFix in $HotFixes) {
IF ($Comparison -NotLike "*$HotFix*") {
Write-Host "$Computer missing $HotFix"
}
$Successful += $Computer
}
}
}
}
}
This line
While ($Successful -AND $Successful.count -ne $Computers.count) {
can never evaluate to $true. The .count-property of a non-existing variable ($Successful) is $null, and the same goes for a string (because you specify only 1 computer, it's not an array).
To force Powershell to return the "true" number of items, use #($Successful).count and #($Computers).count instead. This will give you 1, even if $Computers wasn't defined as an array. So, with variables substituted, your line is interpreted as
While ($null -AND $null.count -ne $null) {
In Powershell 3, as you can read here, this is no longer the case.

Multiple variables in Foreach loop [PowerShell]

Is it possible to pull two variables into a Foreach loop?
The following is coded for the PowerShell ASP. The syntax is incorrect on my Foreach loop, but you should be able to decipher the logic I'm attempting to make.
$list = Get-QADUser $userid -includeAllProperties | Select-Object -expandproperty name
$userList = Get-QADUser $userid -includeAllProperties | Select-Object -expandproperty LogonName
if ($list.Count -ge 2)
{
Write-host "Please select the appropriate user.<br>"
Foreach ($a in $list & $b in $userList)
{
Write-host "<a href=default.ps1x?UserID=$b&domain=$domain>$b - $a</a><br>"}
}
}
Christian's answer is what you should do in your situation. There is no need to get the two lists. Remember one thing in PowerShell - operate with the objects till the last step. Don't try to get their properties, etc. until the point where you actually use them.
But, for the general case, when you do have two lists and want to have a Foreach over the two:
You can either do what the Foreach does yourself:
$a = 1, 2, 3
$b = "one", "two", "three"
$ae = $a.getenumerator()
$be = $b.getenumerator()
while ($ae.MoveNext() -and $be.MoveNext()) {
Write-Host $ae.current $be.current
}
Or use a normal for loop with $a.length, etc.
Try like the following. You don't need two variables at all:
$list = Get-QADUser $userid -includeAllProperties
if ($list.Count -ge 2)
{
Write-Host "Please select the appropriate user.<br>"
Foreach ($a in $list)
{
Write-Host "<a href=default.ps1x?UserID=$a.LogonName&domain=$domain>$a.logonname - $a.name</a><br>"
}
}