I have a problem with some script that I want to write. I have for example a TEST rule in local Exchange. There are accounts added manually which are disabled. I'm looking for a way to clear the rule of disabled accounts and leave the enabled accounts as they were. I thought that I will export through Exchange Management Shell a list of people from this rule. Then through foreach and Get-ADUser I will add the missing data and then load the .CSV file once again and based on the email and disabled account I will remove these people from the rule.
I don't know if this is feasible, but I'm trying. I would appreciate any hints on what I am doing wrong in the script.
When I want to run the script, I get the message:
Get-ADUser : Error parsing query: ' "UserPrincipalName -like
'$($_.Mail)'" -and "Enabled -eq '$false'"' Error Message: 'syntax
error' at position: '2'.
Below is my code:
<#
The first step is to export the list of users who are in the TEST rule
#>
Get-TransportRule "TEST" |
select -ExpandProperty "ExceptIfSentTo" |
Export-Csv -Path C:\TEST.csv -NoTypeInformation
<#
Second, the list of users is displayed and then I add the data of these users such as:
Name, SamAccountName, UserPrincipalName, Enabled
#>
Import-Csv C:\TEST.csv | foreach {
Get-ADUser -Filter "UserPrincipalName -eq '$($_.RawIdentity)'"} |
select name, sAMAccountName, UserPrincipalName, Enabled
#Export data with attributes to a second .csv file
Import-Csv C:\TEST.csv | foreach {
Get-ADUser -Filter "UserPrincipalName -eq '$($_.RawIdentity)'"} |
select name, sAMAccountName, UserPrincipalName, Enabled |
Export-Csv -Path C:\TEST_with_attributes.csv -Delimiter ";" -Encoding UTF8 -Force
Start-Sleep -Seconds 3
<#Here it wants to load a file and, based on the UserPrinicalName and the fact that the account is disabled, remove users from the TEST rule#>
Import-Csv C:\TEST_with_attributes.csv | foreach {
Get-ADUser -Filter { "UserPrincipalName -like '$($_.UserPrincipalName)'" -and "Enabled -eq '$false'"} } | Disable-InboxRule "TEST" -AlwaysDeleteOutlookRulesBlob
Related
So basically, I have a script that can generate a list of all the users in Active Directory, with their lastlogondate, samaccountname and name. However, I want to add a new clause to this where it EXCLUDES disabled (users). There doesn't seem to be an object such as disabledUsers that I could just add to the end of my Where-Object part.
So because there is no object ID for disabled users, I understand that it should be something like this:
$userList = Get-ADuser -filter {Enabled -eq $True}
But I keep running in to syntax errors when I add this
$companyName = "GG"
$dateStr = (Get-Date).ToString("yyyyMMdd-hhmmss")
$exportPath = "C:\"
$exportFileName = "$($exportPath)\($dateStr)_($companyName)_userlist.csv"
$userList = Get-ADUser -Filter "*" | Where-Object {($_.DistinguishedName -notLike "*System*")} | Select-Object Name,samAccountName, lastLogonDate
$userList | Export-Csv -Path $exportFilename -NoTypeInformation
I would very much appreciate some assistance here friends.
Sorry, i'm noob for powershell, but want to automate the following:
Got a powershell script:
import-module ActiveDirectory
$username = Read-Host 'Please enter Username!'
Get-ADPrincipalGroupMembership $username | Get-ADGroup -Properties * | select name, description
When run script i enter the username and it give me a list which group the user is member of.
I had a big 50-100 list user list which obtained with Get-aduser -filter * -properties Name | select-object Name | out-file -filepath .\userlist.txt command and saved to a text file.
Is there any way to read every user 1 by 1 and auto fill the username field, then save the output to a text file? when finished with the 1st, script rerun and read the next value.
Is that possible?
Thank you
Here's a few snippets to help you put together what you need.
Get all users from a file containing only usernames
[string[]]$allUsers = Get-Content -Path '.\FileWithUsernames.txt'
Get all active users from AD
[string[]]$allUsers = Get-AdUser -Filter "enabled -eq 'True'" | Select-Object -ExpandProperty 'SAMAccountName'
Loop through users getting the users' group info / doing something with it
foreach ($user in $allUsers) {
Get-AdUser -Identity $user -Properties 'memberof' |
Select-Object -ExpandProperty 'memberof' |
ForEach-Object {
([PSCustomObject]#{ Username=$user; GroupDN = $_})
} |
Export-Csv -Path '.\AllActiveUsersGroups.csv' -Append -Delimiter ',' -Encoding 'Utf8' #-NoTypeInformation #only include the -notypeinfomrmation parameter if using PS rather than PWSH)
}
I am able to export the disabled users, but then from that .csv I want to check if they have active accounts in AD, containing their samaccount name + -adm or -tst. The script runs but the second export is blank.
$users = import-csv C:\Users\....csv
$OU = 'OU=Disabled users ...'
Get-ADUser -Property Enabled -filter * -SearchBase $OU | Where {$_.Enabled -like "False"} | Select #{Name="samaccountname";Expression={$_.SamAccountName}} | Export-Csv C:\Users\... -notypeinformation -encoding UTF8
$data = foreach($line in $users){
$user = $line.samaccountname
Get-ADUser -Filter {(samaccountname -like $user) -and (samaccountname -like "*-adm") -and (samaccountname -like "*-tst")} -Properties Enabled | Where {$_.Enabled -like "True"} | select #{Name="SAPID";Expression={$_.samaccountname}}
} $data | export-csv C:\Users\... -notypeinformation -encoding UTF8
If I understand correctly, you're looking to find all those Enabled Accounts ending in -adm OR -tst AND containing the SamAccountName of ANY disabled user found in $OU.
If my assumption is correct, one way to approach the problem is to first query all the Disabled users in $OU and have them in memory (Note that there is no need to export them to CSV and then import them back again - see inline comments).
Once we have the list of Disabled users, we can loop over them to construct an LDAP Filter which will be used to query all users at once, and lastly export to CSV if any user was found.
$users = Import-Csv C:\Users\....csv
$OU = 'OU=Disabled users ...'
# Hold disabled Users under `$OU` in memory, no reason to import the data from CSV
$disabledUsers = Get-ADUser -LDAPFilter "(userAccountControl:1.2.840.113556.1.4.803:=2)" -SearchBase $OU |
Select-Object SamAccountName
# Export Disabled Users
$disabledUsers | Export-Csv C:\Users\... -NoTypeInformation -Encoding utf8
# Construct an LDAP Filter to query al users at once
$filters = foreach($user in $disabledUsers) {
'(samAccountName=*{0}*-adm)(samAccountName=*{0}*-tst)' -f $user.SamAccountName
}
$ldapFilter = "(&(!userAccountControl:1.2.840.113556.1.4.803:=2)(|$(-join $filters)))"
# Query the users
$enabledUsers = Get-ADUser -LDAPFilter $ldapFilter
# Check if any user could be found
if(-not $enabledUsers) {
'No Enabled -adm or -tst Account Could be found...'
}
else {
$enabledUsers | Select-Object #{ N = "SAPID"; E = { $_.SamAccountName} } |
Export-Csv C:\Users\... -NoTypeInformation -Encoding utf8
}
This is an example of how the filter would look like, having user0 and user1 as example SamAccountName:
(&
(!userAccountControl:1.2.840.113556.1.4.803:=2)
(|
(samAccountName=*user0*-adm)
(samAccountName=*user0*-tst)
(samAccountName=*user1*-adm)
(samAccountName=*user1*-tst)
)
)
First:
I am complete new to Powershell-Scripting.
Want to change the attribute "preferredLanguage" from some Users via powershell.
The users are written in txt-file
testUser000
testUser001 and so on
My first try was to become a list with users and some attributes:
$users = ForEach ($user in $(Get-Content C:\Temp\users.txt)) {
Get-AdUser $user -Properties Department, Mail, preferredLanguage
}
$users |
Select-Object SamAccountName,Department,Mail, preferredLanguage |
Export-CSV -Path C:\temp\outputUsers.csv -NoTypeInformation
That worked so far:
"SamAccountName","Department","Mail","preferredLanguage"
"tesUser000","dept1","testUser000#domain.com","DE"
"testUser0001","dept2","testUser001#domain.com",
testUser000 has an entry in preferredLanguage
testUser0001 has no entry
That's ok. When I have completed the users.txt, there are more than 100 users without an entry in 'preferredLanguage'
Now I want to change the preferredLanguage and with some investigation in the Internet I made this:
$users = ForEach ($user in $(Get-Content C:\Temp\users.txt)) {
Get-AdUser $user -Properties Department, Mail, preferredLanguage
}
$users |
Set-AdUser $users -Replace #preferredLanguage="DE" |
Select-Object SamAccountName,Department,Mail, preferredLanguage |
Export-CSV -Path C:\temp\outputUsers.csv -NoTypeInformation
When I understand this script right, then it get from my txt-File every user in it with the given attributes then it changes the attribute 'preferredLanguage' from the users in the txt-file and then it select it again then it will save the output in a csv-file.
Maybe someone can look over the script and would be so kind and give me feedback about it or a better way, because Iam too scary to use this script on the AD-Server.
Just a few things:
Get-AdUser $user means you must be sure the user with that identity exists or an exception will be thrown
the syntax for the -Replace operator should be #{preferredLanguage="DE"}
Set-ADUser does not generate any output unless the -PassThru parameter is used.
if you use ForEach-Object, you can do all this in one loop
Try changing the code with this:
(Get-Content C:\Temp\users.txt) | ForEach-Object {
$account = Get-AdUser -Filter "SamAccountName -eq '$_'" -Properties Department, Mail, preferredLanguage -ErrorAction SilentlyContinue
if ($account) {
$account | Set-AdUser -Replace #{preferredLanguage="DE"} -PassThru |
Select-Object SamAccountName,Department,Mail, preferredLanguage
}
else {
Write-Warning "User '$_' does not exist"
}
} | Export-CSV -Path C:\temp\outputUsers.csv -NoTypeInformation
Hope that helps
<#
Run the Script On Active Directory to remove disabled users from All Groups and Set description what user was member of group if you have all the disable users in an OU.
Just add -SearchBase "OU=disabled,DC=domain,DC=com" after -filter 'enabled -eq $false'
#>
import-module activedirectory
$users=get-aduser -filter 'enabled -eq $false' -SearchBase "OU=Lockdown,DC=home,DC=ac,DC=uk" -Properties samaccountname,memberof |select samaccountname, #{n=’MemberOf’; e= { ( $_.memberof | % { (Get-ADObject $_).Name }) -join “,” }}
#set description
Foreach ($user in $users)
{ Set-ADUser $user.samaccountname -Replace #{info="Was a member of :- $($user.memberof)"}
# Export the list to csv
$Groups = (Get-ADPrincipalGroupMembership -Identity $user.SamAccountName | Select-Object -ExpandProperty name) -join ','
get-aduser $user.SamAccountName -properties memberof,samaccountname,givenname,surname | select samaccountname, #{name="Groups";expression={$Groups}} | export-csv "C:\Users\Administrator\Desktop\grpsss.csv" -Delimiter ";"
# Remove From all the Groups
Get-ADGroup -Filter {name -notlike "*domain users*"} | Remove-ADGroupMember -Members $user.samaccountname -Confirm:$False
}
$total = ($users).count
Write-Host "$total accounts have been processed..." -ForegroundColor Green
This script Removes all the groups from Disabled Users (From Disabled OU), It adds the names of those groups to Information Field along with an export of csv with the same information.
Porblem is that the csv is only populated with one user's groupmembership when there are many users in Disabled OU. question is, how do i export all the user and their group membership in a csv format. so i have a list of all the users that have been processed.
I always thought that export-csv will export eveything that powershell processes?
Thanks for your help in advance.
Your script attempts to export a csv for each user:
Foreach ($user in $users) {
...
get-aduser $user.SamAccountName -properties memberof,samaccountname,givenname,surname |
select samaccountname, #{name="Groups";expression={$Groups}} |
export-csv "C:\Users\Administrator\Desktop\grpsss.csv" -Delimiter ";"
...
}
However, this will mean that only the last user run in this foreach block will have its data written out to a .csv file.
This is because Export-Csv will overwrite the contents of an existing .csv file by default. So every user in your foreach block will overwrite the user before it.
To fix this, add the parameter switch -Append to the end of your Export-Csv command. This will add on each users data to the end of the file rather than overwrite it e.g.
Foreach ($user in $users) {
...
get-aduser $user.SamAccountName -properties memberof,samaccountname,givenname,surname |
select samaccountname, #{name="Groups";expression={$Groups}} |
export-csv "C:\Users\Administrator\Desktop\grpsss.csv" -Delimiter ";" -Append
...
}