Powershell - Basic Script not working Regarding Get-AdUser - powershell

I want to Get-ADUser and then compare that to whatever the user has inserted.
I would greatly appreciative if anyone could help me fix this.
$user1 = Read-Host "Enter the first username"
$GetUser = Get-ADUser -Filter {SamAccountName- eq $user1}
if ($user1 -ne $GetUser){
Write-Host "It does not match our records. Please try again later" -ForeGroundColor Red
}
elseif ($User1 -eq $GetUser){
Write-Host "It matches our records" -ForegroundColor Green
}

You can just test that there is a return from Get-ADUser, if there's no match nothing is returned.
I would also use Identity (instead of Filter) as it accepts both SamAccountName and DN.
A distinguished name
A GUID (objectGUID)
A security identifier (objectSid)
A SAM account name (sAMAccountName)
This simplifies your code to:
$user1 = Read-Host "Enter the first username"
if (Get-ADUser -Identity $user1){
Write-Host "It matches our records" -ForegroundColor Green
}
else {
Write-Host "It does not match our records. Please try again later" -ForeGroundColor Red
}

Related

Using multiple if statemens in foreach loop

In this script, I am trying to make a group (if not exist) and add users thats are not already in the group.
But the problem is he only takes the first if statement I think, because it don't seems like he is taking the next statements in the loop.
#Tweede test met if
$teams = #Here comes the csv file.
Foreach($team in $teams)
{
$Test = (Get-UnifiedGroup $team.DisplayName)
if (Get-UnifiedGroup $team.DisplayName)
{
Write-Host -ForegroundColor Green "$($team.Displayname) already exists!"
}
elseif ($Test -eq "false")
{
$Group = New-UnifiedGroup -DisplayName $team.DisplayName -Alias $team.Alias -AccessType $team.AccessType
}
foreach($Member in $Members)
{
elseif (get-UnifiedgroepLinks $team.Links)
{
write-host -ForegroundColor Green "$($team.Links) already exists!"
}
else
{
Add-UnifiedGroupLinks -Identity $team.Identity -LinkType $team.Linktype -Links $team.Links
}
}}
OK so this is my current output form #Theo last improvement
Output
OK I have something very interesting, because when I looked at the output of
$existingMembers = #((Get-UnifiedGroupLinks -Identity $Group.DistinguishedName -LinkType Members).PrimarySMTPAddress)
I will get certain blank spots. And when I ran the script for one user it was working but for another one it did not, so I looked at the user that did not worked, and he does not have a license. So I tested it further. And in my conclusion now it's working. So when an acc is unlicensed, it is not seen like he is added to that specific group. So he is also throwing the second if statement, but also the second else statement.
Does this make sense to you #Theo?
### script name: Users_Verwijderen ###
### Datum updated: 14-12-2022 ###
### Auteur: Wessel Rouw ###
### Purpose script is to add groups and users in to groups in Azure. ###
#######################################################################
$teams = import-csv #Here your CSV
foreach($team in $teams) {
$team | Format-Table
$Check = (Get-UnifiedgroupLinks -Identity $team.Identity -LinkType $team.Linktype)
$existingMembers = #((Get-UnifiedGroupLinks -Identity $Group.DistinguishedName -LinkType Members).PrimarySMTPAddress)
$Group = (Get-UnifiedGroup $team.DisplayName)
if ($Group)
{
Write-Host "$($team.Displayname) already exists!" -ForegroundColor Green
}
else
{
Write-Host "Creating group $($team.Displayname)"
$Group = New-UnifiedGroup -DisplayName $team.DisplayName -Alias $team.Alias -AccessType $team.AccessType
}
if ($existingMembers -contains $team.Links)
{
Write-Host "$($team.Links) already exists!" -ForegroundColor Green
}
else
{
Write-Host "Creating group Links $($team.Links)"
Add-UnifiedGroupLinks -Identity $team.Identity -LinkType $team.Linktype -Links $team.Links
}
}
This is now my current script working with help from #Theo (Only, users that are not licensed will get the message that they are added even if they are already in the group).
Here is my input now in my csv.
I have changed username (Links) and the domain name (After the Test101 and the users (Links).
DisplayName,Alias,AccessType,Identity,Linktype,Links
Test101,Test101,private,Test101#domain.nl,Member,Hek_Sme#Domain.nl
Test101,Test101,private,Test101#domain.nl,Member,Mek_Lei#Domain.nl
Test101,Test101,private,Test101#domain.nl,Member,Wek_Bog#Domain.nl
This is another very helpful output. again same story as above with the changed domain and usernames.
Name DisplayName GroupType PrimarySmtpA
ddress
---- ----------- --------- ------------
Test101_(**Here comes a private number)** Test101 Universal Test101#1...
PS C:\WINDOWS\system32> $existingMembers
**Here comes the domain admin**
Hek_Sme#Domain.nl
Gek_Wel#Domain.nl
Gek_Wel#Domain.nl
Dir_Bog#Domain.nl
Wek_Bog#Domain.nl
PS C:\WINDOWS\system32> $inputMembers
Mek_Lei#Domain.nl
PS C:\WINDOWS\system32>
And as you can see some fields are empty and that are exactly the two users who don't own a licence and when I then run the command to get everyone who is not presenting in the get commando of users for that group it is specified to that users again.
I only don't know why this and if my thought is right?
Oke, so thanks already for the help. Now it works better. But in the second part I want to verify that if a user already exists in azure it displays the message, but if don't it has to be added? But this is now the problem.
This is now the output of my running script
VERBOSE: Returning precomputed version info: 3.0.0
VERBOSE: POST with -1-byte payload
VERBOSE: received 2945-byte response of content type application/json;charset=utf-8
VERBOSE: Returning precomputed version info: 3.0.0
VERBOSE: POST with -1-byte payload
VERBOSE: received 2906-byte response of content type application/json;charset=utf-8
Test105 already exists!
Creating group Links #Here stand the email (Links)
VERBOSE: Returning precomputed version info: 3.0.0
VERBOSE: POST with -1-byte payload
VERBOSE: received 386-byte response of content type application/json;charset=utf-8
The problem is when a user already exist it does not goes to the line that says that it already exits but instead it skips this part i think and goed directy to the else statement.
I think I am pretty close now.
`$teams = import-csv #CSV here
{
#$team | Format-Table #This was voor debugging
$Check = (Get-UnifiedgroupLinks -Identity $team.Identity -LinkType $team.Linktype)
$Group = (Get-UnifiedGroup $team.DisplayName)
if ($Group)
{
Write-Host "$($team.Displayname) already exists!" -ForegroundColor Green
}
else
{
Write-Host "Creating group $($team.Displayname)"
$Group = New-UnifiedGroup -DisplayName $team.DisplayName -Alias $team.Alias -AccessType $team.AccessType
}
if ($Check -contains $team.Links)
{
Write-Host "$($team.Links) already exists!" -ForegroundColor Green
}
else
{
Write-Host "Creating group Links $($team.Links)"
Add-UnifiedGroupLinks -Identity $team.Identity -LinkType $team.Linktype -Links $team.Links
}
}`
These are the columns of my csv.

How to validate 2 inputs in Powershell and only proceed when both inputs are validated

Trying to write a script in Powershell that needs to validate 2 User Inputs before applying policies to the correct entries. With the basic script I wrote, It Validates the 1st Entry which is the User ID in the Teams Tenant. Then Validates the 2nd entry which is the telephone number using the validate regex. The problem I am having is that the policies Do not get applied when the correct information is applied. It skips that part and states a Warning and asks to check another profile.
Connect-MicrosoftTeams
do {
try {
# 1st User Entry to check UserID
$upnentry = Read-Host 'Enter the User Principle Name'
# Validate in Teams Tenant if this ID exists, If Not,
# prompt to enter a valid entry again
$csu = Get-CsOnlineUser -Identity $upnentry -ErrorAction Stop
$csu | Format-List IsSipEnabled, Displ*
Write-Host 'User ID has been verified correctly!'
# 2nd User Entry to check for valid Telephone Number
$phoneinputblock = {
try
{
[validatescript({[regex]::Match($_,'^27\d{9}$').Length -eq 11})]
$phoneUserInput = Read-Host "`nEnter Telephone Number"
$phoneUserInput
}
catch{ Write-Warning "Incorrect Format for Telephone Number!"
& $phoneinputBlock
}
}
$phoneuserInput = & $phoneinputBlock
Write-Host 'Telephone Number is in the correct format!'
Set-CsPhoneNumberAssignment -Identity $user -PhoneNumber
$phonenumberinput -PhoneNumberType DirectRouting
Grant-CsOnlineVoiceRoutingPolicy -PolicyName VRP- International -Identity $upnentry
Write-host "Policies applied successfully for : $upnentry" - ForegroundColor Green
}
catch { Write-Warning "You've entered an invalid UserID: $upnentry"
}
} until($Host.UI.PromptForChoice('', 'Do you want to check another Users Profile?',
('&Yes', '&No'), 0))
I would not perform the two tests inside nested try--catch blocks like that, but instead use a boolean variable to keep track of the result from the first test and only if that is true proceed with the rest.
Something like this:
Connect-MicrosoftTeams
do {
$testID = $false
try {
# 1st User Entry to check UserID
$upnentry = Read-Host 'Enter the User Principle Name'
# Validate in Teams Tenant if this ID exists, If Not,
# prompt to enter a valid entry again
$csu = Get-CsOnlineUser -Identity $upnentry -ErrorAction Stop
$csu | Format-List IsSipEnabled, Displ*
Write-Host 'User ID has been verified correctly!'
$testID = $true
}
catch { Write-Warning "You've entered an invalid UserID: $upnentry"}
if ($testID) {
# 2nd User Entry to check for valid Telephone Number
while ($true) {
$phoneUserInput = Read-Host "`r`nEnter Telephone Number"
if ([regex]::Match($phoneUserInput,'^27\d{9}$').Length -eq 11) {
Write-Host 'Telephone Number is in the correct format!'
break # exit the loop
}
# here we have a wrong phone number, so ask again
Write-Host "`r`nThe Telephone Number is in the wrong format. Should start with 27 followed by nine digits" -ForegroundColor Red
if ((Read-Host "Do you want to stop here (Yes/No) ?") -match '^Y') { # exit the script
exit
}
}
# here we know both entries are correct, so proceed setting the phone number
try {
Set-CsPhoneNumberAssignment -Identity $upnentry -PhoneNumber $phoneUserInput -PhoneNumberType DirectRouting -ErrorAction Stop
Grant-CsOnlineVoiceRoutingPolicy -PolicyName 'VRP- International' -Identity $upnentry -ErrorAction Stop
Write-host "Policies applied successfully for: $upnentry" - ForegroundColor Green
}
catch {
Write-Warning "Error setting the phone number: $($_.Exception.Message)"
}
}
} until ($Host.UI.PromptForChoice('', 'Do you want to check another Users Profile?', ('&Yes', '&No'), 0))

Add User to Exchange In-placeHold/eDiscovery (In-Situ) with powershell

I'm currently encountering some problems with powershell, while creating scripts.
I want to add a User to our In-place-Hold / eDiscovery. I more or less found a workaround to adding a single User to the list, but I'm not sure if it works without losing data of the already existing In-Place-Hold users.
The goal is to add newly created users to an existing In-Place-Hold.
However, maybe its easier to understand with my code:
#All users that are already in the in-situ
$check = Get-MailboxSearch “In situ autotest"
foreach ($User in $ADUsers)
{
$Username = $User.username
$Firstname = $User.firstname
$Lastname = $User.lastname
if (Get-Mailbox -Identity $Username)
{
#If user does exist, output a warning message
Write-Warning "Benutzername $Username already existing on the Exchange Server."
}
else
{
Enable-Mailbox -Identity "$Username" -DomainController 'DC.domain.com'
}
#search for the user
$Add = Get-Mailbox -Identity "$Username"
$check.sources.add("$Add")
}
#write all users back into insitu mailbox
Set-Mailboxsearch -Name "In situ autotest" -Identity "In situ autotest" -SourceMailboxes $check.sources
Does someone know if there is an easier way to add a single user to the sourcemailboxes of Set-Mailboxsearch, without having to aplly everyone again?
Thank you guys very much in advance!

Automatically Adding a Number to variable in Powershell

I have looked at some sites online and browsed a few answers here and I have had no luck with my question.
I have a PowerShell script to automate account creations using information entered in the host. My question is this, how can I set my script to automatically add a number at the end of the submitted data if it already exists? Code block is below:
$Username = Read-host "Enter Desired Username"
#Test
IF(!(Get-ADUser -Identity $Username))
{ Write-Host "$username exists. Adding number.
HERE IS THE CODE I AM LOOKING FOR TO TAKE THE $Username and automatically add the number at the end.
}
If this was already answered, please send me the link and I'll mark this as answered but if not, any suggestions would be great.
Thanks!
Since this script isn't being automatically run and there is user input, I would suggest just re-prompting the user if the name is taken:
Do
{
$Username = Read-Host -Prompt 'Enter desired username'
} While (Get-ADUser -Identity $Username)
Alternatively:
$Username = Read-Host -Prompt 'Enter desired username'
While (Get-ADUser -Identity $Username)
{
"Username '$Username' taken!"
$Username = Read-Host -Prompt 'Enter desired username'
}
To supplement the other answer, you could also do something like this to determine the next available username:
$Username = Read-Host -Prompt 'Enter desired username'
$TestUsername = $Username
$i = 1
While (Get-ADUser -Identity $TestUsername)
{
Write-Warning "$TestUsername is taken"
$TestUsername = $Username + $i++
}
"The next available username is $TestUsername"
Within the loop the ++ operator is used to increment the counter variable $i and appends that to the original username each time the loop repeats. Note that it is appended first then incremented second, so we start at 1.
I've written such a script. My logic is:
Before creating an account, query this account firstly
If the account exists, suffix a 2 digits number (from 01, format by "{0:d2}" -f
Query the suffixed account, repeat step 1 and 2, till the account doesn't exist (use recursive function).
It's the code:
$seq = 1
Function Check-Existing {
param(
[Parameter(Mandatory=$true)]
[string]$Account
)
while (Get-ADUser $Account){
$suffix = "{0:d2}" -f $seq
$Account = $Account + $suffix
$seq++
return $Account
}
Check-Existing -Account $Account
}
(I'll double check the code on Monday)

Output of a PowerShell command doesn't show result until after Write-Host and Read-Host [duplicate]

This question already has answers here:
Unable to Pause or Sleep after Select-Object
(2 answers)
Closed 7 months ago.
Code will not return the results of the Get-ADUser command until after I hit a carriage return at the end of the code
Write-Host "Please enter the user account name. Ex. jsmith1" -ForegroundColor Yellow -BackgroundColor Black
$Username = Read-Host
"`n"
Write-Host "Is this the correct username? $Username" -ForegroundColor Yellow -BackgroundColor Black
Write-Host "If Yes Type 1; If No type 2" -ForegroundColor Yellow -BackgroundColor Black
$Continue1 = Read-Host
IF ($Continue1 -eq 1)
{
Get-ADUser -Server "contoso.com" -filter * -Properties * | Where {$_.SamAccountName -match $Username} | Select DisplayName, SamAccountName, EmployeeID, EmployeeNumber
}
ELSE
{}
Write-Host "Would you like to update the Employee ID and the Employee Number?" -ForegroundColor Yellow -BackgroundColor Black
Write-Host "If Yes Type 1; If No type 2" -ForegroundColor Yellow -BackgroundColor Black
$Continue2 = Read-Host
What am I missing here?
The Write-Host items are immediately displayed during the execution of your command.
The Get-ADUser results are on the output pipeline.
Normally this allows you to return the value into another script, for example, for further processing. Since you don't assign it or capture the output, it simply goes to a default formatter and displays after everything else before the execution ends.
If you really and truly just want to display the output, you can add | Write-Host to the end of your Get-ADUser call. If you ever want to connect this to another script, you can capture the value to a variable, then both Write-Host, and then Write-Output to add it back on the pipeline.
See also: Understanding the Windows PowerShell Pipeline
I found that you can also just add some formatting to the end and it will output as you would expect, when you expect it. I added this formatting to the end:
| FT -AutoSize