Hey guys need a little help,
I have been rapping my head around how to exclude certain users from a password reset script.
This is the script:
$newPassword = ConvertTo-SecureString -AsPlainText "MyP#ssw0rd" -Force
Import-Csv "C:\users\administrator\desktop\UserCreation.csv" | ForEach-Object {
$samAccountName = $_."samAccountName"
Set-ADAccountPassword -Identity $samAccountName -NewPassword $newPassword -Reset
Set-AdUser -Identity $samAccountName -ChangePasswordAtLogon $false
Write-Host " AD Password has been reset for: "$samAccountName
}
I want to exclude certain samAccountNames from this password reset however I cant quite work it out.
Any help would be much appreciated.
Thanks Guys
You can always set filters in your Set-AdUser comamand.
Like:
Get-ADUser -Filter {(Enabled -eq $true)`
-and (sAMAccountType -ne 805306370)`
-and (cn -ne "Administrator")}`
-and (SamAccountName -like "*-ext*")`
-SearchBase "OU=OUwithUsers,DC=MySubdomain,DC=MyDomain,DC=com"
You can filter your user list like that or you can modify your csv file by deleting/adding users there. You are using a csv file as an import so that one should have the list of the users that you want to change their passwords.
Personally I would clear the csv or create a csv with more filters so I can then import it and finish what I want to do without worrying if I changed someones password without his permission.
can you use an exclusion list like this :
$exclusion_list = "testuser1","testuser2"
$totalList = ("testuser1","testuser2","testuser4")
foreach($item in $totalList){
if( $exclusion_list -contains $item){
"excluding $item"
continue
}
else{
#reset the password
$item
}
}
Hash table version for performance reasons:
$exclusion_list = #{"testuser1"="exclude";"testuser2"="exclude"}
$totalList = ("testuser1","testuser2","testuser4")
foreach($item in $totalList){
if( $exclusion_list[$item]){
"excluding $item"
continue
}
else{
#your code
$item
}
}
Related
Looking to get some help with my powershell script. Basically have a script that I use to bulk edit fields in Azure AD for multiple users and it works fine. I tried to use it for editing custom attributes for multiple users via Exchange Online and it is not working. I'm guessing it does not work the same for EO. The goal here is to pull a csv that has 2 columns (the users emails address "userprincipalname", and one column for the value I want to add for "customattribute1") Any help is appreciated.
# Connect to ExchangeOnline
Connect-ExchangeOnline
# Get CSV content
$CSVrecords = Import-Csv C:\pathtofile.csv
# Create arrays for skipped and failed users
$SkippedUsers = #()
$FailedUsers = #()
# Loop trough CSV records
foreach ($CSVrecord in $CSVrecords) {
$upn = $CSVrecord.UserPrincipalName
$user = Get-Mailbox -Filter "userPrincipalName eq '$upn'"
if ($user) {
try{
$user | Set-Mailbox -customattribute1 $CSVrecord.customattribute1
} catch {
$FailedUsers += $upn
Write-Warning "$upn user found, but FAILED to update."
}
}
else {
Write-Warning "$upn not found, skipped"
$SkippedUsers += $upn
}
}
I think there could be 2 points that leads fail to set customattribute1.
The filter expression should be : "userPrincipalName -eq '$upn'"
Seems I can't find the -Delimiter param while you import your .CSV file which will lead to unbale to pull column value correctly.
Try the code below that works perfectly for me:
Connect-ExchangeOnline
$SkippedUsers = #()
$FailedUsers = #()
$CSVrecords = Import-Csv "C:\Users\Administrator\Desktop\test.csv" -Delimiter ","
foreach($CSVrecord in $CSVrecords ){
$upn = $CSVrecord.UserPrincipalName
$user = Get-Mailbox -Filter "userPrincipalName -eq '$upn'"
if ($user) {
try{
$user | Set-Mailbox -customattribute1 $CSVrecord.customattribute1
} catch {
$FailedUsers += $upn
Write-Warning "$upn user found, but FAILED to update."
}
}
else {
Write-Warning "$upn not found, skipped"
$SkippedUsers += $upn
}
}
My test .csv file:
After run the PS command, try to get customattribute1 of my test user:
Let me know if you have more questions.
How can I enable or disable an AD user account from a csv based on an entry. If the status for both say Active, only one account gets enabled instead of both. Same for the disabled status
CSV file:
Samaccountname,Status
john.doe,Active
jane.doe,Disabled
What I have so far:
Import-CSV -Path c:\folder\adaccounts.csv
ForEach ($User in $Users)
{
IF ($User.Status -contains "Disabled")
{
Get-ADUser -Identity $user.samaccountname | Disable-ADAccount
}
elseif ($User.Status -contains "Active")
{
Get-ADUser -Identity $user.samaccountname | Enable-ADAccount
}
At the top of your script you are importing the CSV but it doesn't look like you have assigned it to a variable for your foreach loop
if you assign it to the $Users variable like below, the rest of the script should then go through your CSV as expected.
$Users = Import-Csv -Path c:\folder\adaccounts.csv
-Contains is an operator to test if something can be found in an array of things, not for testing if a string is equal or not to another string.
I would revise your code like this:
Import-CSV -Path 'c:\folder\adaccounts.csv' | ForEach-Object {
# test if a user with that SamAccountName can be found
$user = Get-ADUser -Filter "SamAccountName -eq '$($_.Samaccountname)'" -ErrorAction SilentlyContinue
if ($user) {
# set Enabled if Status is not 'Disabled'
$user | Set-ADUser -Enabled ($_.Status -ne 'Disabled')
}
else {
Write-Warning "User $($_.Samaccountname) does not exist"
}
}
Currently I have a script that creates user accounts.
Note: Not all users have the same UPN (UserPrincipalName)
User accounts are in the following format: <firstinit><lastname>.
If this conflicts, the format will be changed to: <firstinit><middleinit><lastname>
Recently I have ran into an issue where the user's proxyAddress is conflicting with existing users. This is a problem because AD will not catch this.
Issue:
Checking every AD-User's proxy address is very time consuming if not included in the filter. However, when including proxyAddresses in the filter the results are inconsistent. I am assuming this is because the proxyAddresses attribute is an array.
Inconsistent:
Import-Module ActiveDirectory
$FirstLast = "jrider#ChuckNorrisKills.com"
$conflictCheck = Get-ADUser -Properties mail, proxyAddresses -Filter "mail -eq '$FirstLast' -or UserPrincipalName -eq '$FirstLast' -or proxyAddresses -eq `"smtp:'$FirstLast'`"" | measure
if($conflictCheck.Count -gt 0)
{
Write-Host "New user conflicts with existing user" -ForegroundColor Red
}
I have come up with a solution that will resolve me issue. Unfortunately this is very slow (expected):
Import-Module ActiveDirectory
function Test-NewADUser
{
Param(
[Parameter(Mandatory=$true)][string]$firstname,
[Parameter(Mandatory=$true)][string]$lastname,
[Parameter(Mandatory=$false)][string]$middle
)
[bool]$proxExsists = $false
$domain = '#chuckNorrisKills.com'
$FirstLast = $firstname.Substring(0,1)+$lastname+$domain
Get-ADUser -Filter * -Properties proxyAddresses | foreach {
#xpand the proxy address and iterate through it
foreach($address in $_.proxyAddresses)
{
#As you can see this goes through every user
Write-Host "Address: " $address -ForegroundColor Yellow
if($address -eq "smtp:$FirstLast")
{
Write-Host "Found Conflict" -ForegroundColor Red
$proxExsists = $true
}
}
}
}
Test-NewADUser -firstname jack -lastname Rider
Question(s):
Is there a way to expand proxyAddresses and check for conflicts in the -Filter?
If not, should I bother with Jobs, or an alternate way of checking for conflicts?
Thank you in advance for any help
You don't need to expand it, as the proxyAddress filter should be reliable.
So, this should be very straightforward:
function Validate-proxyAddress($email)
{
if (Get-ADUser -Filter "proxyAddresses -eq 'smtp:$email'")
{
return $true
}
elseif (Get-ADUser -Filter "mail -eq '$email'")
{
return $true
}
elseif (Get-ADUser -Filter "UserPrincipalName -eq '$email'")
{
return $true
}
return $false
}
or you can join it all in one like your code, hasn't tested it, so if you get false, the user not exist, should be ok to continue...
Also, you can use -like instead of -eq if you need (in cases where missing the smtp prefix somehow):
"proxyAddresses -like '*$email*'"
I am writing a powershell script to disable users due to the fact that we get a list of them everyday and it is monotonous. I paste the list from the ticket into a csv formatted as Lastname, Firstname then run my script with imports the list, serches ad and ask if you want to disable if it finds them. Here is the code...
# Set variables
$Import = "C:\Scripts\Support Files\Users_To_Disable.csv"
$Export = "C:\Scripts\Support Files\Disabled_Users_Output.txt"
# Import user list
$Users = Import-CSV $Import
foreach ($User in $Users)
{
# Set user variables
$LastName = $User.("Surname")
$FirstName = $User.("GivenName")
# Use user variables from list to search ad
$UserName = (Get-ADUser -Filter "GivenName -like '$FirstName*' -and Surname -like '$LastName*'").SamAccountName
# What to do if it finds nothing
If ($UserName -eq $Null)
{
Write-Host $LastName, $FirstName NA -ForegroundColor Yellow
Write-Output "$LastName, $FirstName NA" | Out-File $Export -Append
}
# What to do if it finds a user
Else
{
# Ask for user input
Write-Host $LastName, $FirstName Found -ForegroundColor Green
Write-Host UserName = $UserName -ForegroundColor Green
DO {
$Disable = Read-Host "Do you want to disable user? (Y/N)"
If($Disable -eq "Y")
{
# Disable the user
Disable-ADAccount -Identity $UserName
# Move the user
Get-ADUser $UserName | Move-ADObject -TargetPath "OU=Disabled - Retention,DC=intranet,DC=sw"
# Add Disabled Users group
Add-ADGroupMember "Disabled Users" -Members "$UserName"
# Set Disable Users as primary group
$Group = Get-ADGroup "Disabled Users" -Properties #("PrimaryGroupToken")
Get-ADUser "$UserName" | Set-ADUser -Replace #{PrimaryGroupID=$Group.PrimaryGroupToken}
# Remove all other groups
$User = Get-ADUser "$UserName" -Properties MemberOf
$Groups = $User.MemberOf |ForEach-Object { Get-ADGroup $_ }
$Groups | ForEach-Object { Remove-ADGroupMember -Identity $_ -Members $User -Confirm:$false }
# Output
Write-Host $LastName, $FirstName Disabled -ForegroundColor Red
Write-Output "$LastName, $FirstName Disabled" | Out-File $Export -Append
Break
}
}
Until ($Disable -eq "N")
}
}
Invoke-Item $Export
All of that works, what is scary is that if there are blank cells above a user then it returns all of the users in ad and asks if you want to disable all of them. In other words if the csv looks like this...
Surname GivenName
User Test
Everything works fine, but if it looks like this...
Surname GivenName
User Test
Pandemonium, well not really but it does ask if you want to initiate a resume generating event, which I don't so how can I build in some safety that would stop it from returning all of ad when there are blanks in the csv before users?
You can eliminate the blank lines by filtering out Null values on your import, which should resolve the problem.
$Users = Import-CSV $Import | Where-Object {$_.Surname}
Let's say I have an CSV sheet, first line with the usernames and the second with the emailadresses.
Example:
Username Emailadress
jhornet jhornet#mail.com
How can I import this info to the AD within a safe and nice way, maybe with a check in it?
This is what I have till now (without CSV):
Import-Module activedirectory
$company = "International"
$username = Get-Content c:\users.txt
$emailadress = Get-Content c:\mail.txt
foreach($user in $username)
{
Set-ADuser -Identity $user -Company $company
}
#second
foreach($emailadress in $username)
{
Set-ADuser -Identity $user -EmailAddress $emailadress
}
Still learning a lot with powershell, some things are just hard to understand and better to see :)
Thanks in advance!
Gr,
JPA
I'm going out on a shaky limb here because I've never used the AD commands before but it should go something like this:
Import-Module activedirectory
$company = "International"
$users = Import-Csv c:\user.csv
$users # dumps users to allow visual inspection
read-host "press Enter to continue or Ctrl+C to abort"
$users | Foreach {Set-ADUser -Identity $_.username -Company $company -whatif}
$users | Foreach {Set-ADUser -Identity $_.username -EmailAddress $_.emailaddress -whatif}
Remove the -WhatIf parameter when you think the commands are going to work correctly.