Powershell to replacing AD proxyAddresses with new domain - powershell

I have smtp address beginning with nby keyword like below.
I will remove nby24048#olddomain.com and nby44048#olddomain.com and add nby24048#domainA.com and nby44048#domainA.com. So I will replace those with new domain.
for example :
sAMAccountName,ProxyAddresses
user01,SMTP:user01#domainA.com;smtp:user01#domainA.com;smtp:nby24048#olddomain.com
user02,SMTP:user02#domainA.com;smtp:user02#domainA.com;smtp:nby44048#olddomain.com
....
so on
Here is my script so far:
$Users = import-csv "c:\temp\users.csv"
Foreach ($User in $Users)
{
$Samaccountname = $User.samaccountname
Set-ADUser $samaccountname -Remove #{proxyAddresses=$SMTP}
Set-ADUser $samaccountname -Add #{proxyAddresses=$SMTP}
}

Continuing from my comment, to replace those addresses you can do like below:
$Users = Import-Csv -Path "c:\temp\users.csv"
foreach ($user in $Users) {
$sam = $user.samaccountname
$adUser = Get-ADUser -Filter "SamAccountName -eq '$sam'" -Properties ProxyAddresses
if ($adUser) {
$proxies = $adUser.ProxyAddresses | ForEach-Object {
$_ -replace '^(smtp:nby.+)#olddomain\.com$', '$1#domainA.com'
} | Sort-Object -Unique
# $proxies needs to be a strongly typed string array, so cast to [string[]]
$adUser | Set-ADUser -Replace #{proxyAddresses = [string[]]$proxies}
}
else {
Write-Warning "Could not find user '$sam'.."
}
}

Related

List of Active Directory groups not showing from PowerShell code

I input a list of groups for each user in CSV, and tried to create users using PowerShell code.
This is the PowerShell code:
- name: Change group for AD users
ansible.windows.win_powershell:
script: |
[CmdletBinding()]
param (
[array]
$datalist
)
$output = foreach ($user in $datalist) {
$name = $user.SamAccountName
$groups = $user.Groups
$users = Get-ADUser -Filter "SamAccountName -eq '$name'"
Get-ADUser -Filter "SamAccountName -eq '$name'" -Properties MemberOf | ForEach-Object {$_.MemberOf | Remove-ADGroupMember -Members $users -Confirm:$false}
Add-ADGroupMember -Identity $groups -Members $users
}
parameters:
datalist: "{{ hostvars.localhost.list }}"
I ended up getting this error:
"message": "Cannot convert 'System.Object[]' to the type 'Microsoft.ActiveDirectory.Management.ADGroup' required by parameter 'Identity'. Specified method is not supported."
Also tried '$groups':
"message": "Cannot find an object with identity: '$groups' under: 'DC=adexample,DC=local'.",
And "$groups":
"message": "Cannot find an object with identity: 'CN=GroupA,OU=Groups,DC=adexample,DC=local CN=Test Group,OU=Groups,DC=adexample,DC=local' under: 'DC=adexample,DC=local'.",
This is how I input my list of groups into the CSV file:
Groups
CN=GroupA,OU=Groups,DC=adexample,DC=local;CN=Test Group,OU=Groups,DC=adexample,DC=local
CN=GroupA,OU=Groups,DC=adexample,DC=local;CN=Test Group,OU=Groups,DC=adexample,DC=local
What is the right way to write $groups so that my list of groups can be output correctly?
Updated with CSV in plain text:
FirstName,SamAccountName,path,UserPrincipalName,Groups
Greg,gre.b87,"OU=Temporary Users,DC=adexample,DC=local",gre.b87#gmail.com,"CN=GroupA,OU=Groups,DC=adexample,DC=local;CN=Test Group,OU=Groups,DC=adexample,DC=local"
Zee,zeef.cd,"OU=Temporary Users,DC=adexample,DC=local",zeef.cd#gmail.com,"CN=GroupA,OU=Groups,DC=adexample,DC=local;CN=Test Group,OU=Groups,DC=adexample,DC=local"
I adapted bhuvanachand komara's to mine and it worked for me:
$output = foreach ($user in $datalist) {
$name = $user.SamAccountName
$groups = $user.Groups -split ";"
Get-ADUser -Filter "SamAccountName -eq '$samname'"
$users = Get-ADUser -Filter "SamAccountName -eq '$samname'"
foreach ($group in $groups) {
Add-ADGroupMember -Identity $group -Members $user
}
Get-ADUser -Filter "SamAccountName -eq '$samname'" -Properties MemberOf | ForEach-Object {$_.MemberOf | Remove-ADGroupMember -Members $users -Confirm:$false}
}
The main thing is that I need to add $groups = $user.Groups -split ";" and another foreach loop for the groups.
$csvFile = 'path\to\csv\file.csv'
$users = Import-Csv -Path $csvFile
foreach ($user in $users) {
$samAccountName = $user.SamAccountName
$givenName = $user.GivenName
$surname = $user.Surname
$password = $user.Password
$email = $user.Email
$groups = $user.Groups -split ","
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
New-ADUser -SamAccountName $samAccountName -GivenName $givenName -Surname $surname -DisplayName "$givenName $surname" -EmailAddress $email -AccountPassword $securePassword -Enabled $true
foreach ($group in $groups) {
Add-ADGroupMember -Identity $group -Members $samAccountName
}
}
Example CSV
SamAccountName,GivenName,Surname,Password,Email,Groups
user1,chand,komara,Password1,user1#example.com,group1,group2
user2,bhuvan,unnava,Password2,user2#example.com,group2,group3
For each user in the $users array, the code creates a new Active Directory user using the New-ADUser cmdlet with the specified SamAccountName,
GivenName, Surname, DisplayName, EmailAddress, and account password.
It then adds the user to the specified groups using the Add-ADGroupMember cmdlet.

PowerShell: 'MemberOf' outputs a blank column instead of the 'Group Name' of the users

The below PowerShell script iterates through the groups listed in the test.csv file.
It pulls samAccountName and distinguishedName from each user in the various groups. However, when I try to pull groupName the output is "Microsoft.ActiveDirectory.Management.ADPropertyValueCollection". Not sure how to fix this-
$groups = Get-Content test.csv
$domains = (Get-ADForest).Domains
foreach ($group in $groups)
{
foreach ($domain in $domains)
{
if (Get-ADGroup $group -Server $domain)
{
Get-ADGroupMember $group -Server $domain | select groupName, samAccountName, distinguishedName | Export-Csv c:\temp\file.csv -notypeinformation -append
}
}
}
I have tried the below, but it just outputs an empty column instead:
$groups = Get-Content test.csv
$domains = (Get-ADForest).Domains
foreach ($group in $groups)
{
foreach ($domain in $domains)
{
if (Get-ADGroup $group -Server $domain)
{
Get-ADGroupMember $group -Server $domain | select samAccountName, distinguishedName |
Get-ADUser #{name = ‘MemberOf’;’expression={$_.MemberOf -join “;”}} |
Export-Csv c:\temp\file.csv -notypeinformation
}
}
}
Try this, I added some optimization to your code :)
Note, try {...} catch {...} is more or less needed here because both cmdlets Get-ADGroup and Get-ADGroupMember will throw if the object is not found.
$ErrorActionPreference = 'Stop'
$groups = Get-Content test.csv
$domains = (Get-ADForest).Domains
$result = foreach ($group in $groups)
{
foreach ($domain in $domains)
{
try
{
$adGroup = Get-ADGroup $group -Server $domain
$members = (Get-ADGroupMember $adGroup -Server $domain).where({
# Here, I assume your looking only for user objects
# since you're next cmdlet is Get-ADUser
$_.ObjectClass -eq 'user'
})
foreach($user in $members)
{
# !!! $adUser = Get-ADUser $user >> This is not needed,
# Get-ADGroupMember already brings you the samAccountName of
# each object
# Here you can cast the result, I assume
# you want your CSV to have the Name of the Group and
# the samAccountName and distinguishedName of each user
[pscustomobject]#{
GroupName = $adGroup.Name
samAccountName = $user.samAccountName
distinguishedName = $user.distinguishedName
}
}
}
catch
{
Write-Warning $_
}
}
}
$result | Export-Csv c:\temp\file.csv -NoTypeInformation
If you change your select statement to:
select-object #{n='groupName';expression={$group}}, samAccountName, distinguishedName
It should output the $group input of Get-ADGroupMember for that column.

Powershell script for getting AD Group Membership for usernames

I want to write script for getting AD Group Membership that is beginning with SSL_VPN for usernames listed in a CSV.
I have tried so far :
Import-Csv C:\Users.csv |
ForEach-Object -pv user { Get-AdUser -filter "displayname -eq '$($_.username)'"} |
Get-ADprincipalGroupMembership |
Select-Object #{ n = 'samaccountname'; e = { $user.samaccountname } }, name |
Export-csv -path C:\UserPermiss.csv -NoTypeInformation
Getting users by their DisplayName property is not the safest thing to do. It would be so much better if your CSV file has other, more unique properties to go by, like SamAccountName, UserPrincipalName, DistinguishedName or EmailAddress..
Anyway, in your loop, you should check if a user with that name can be found and only if so, get the group membership.
Import-Csv 'C:\Users.csv' | ForEach-Object {
$user = Get-ADUser -Filter "DisplayName -eq '$($_.username)'" -Properties DisplayName
if ($user) {
Get-ADprincipalGroupMembership -Identity $user.DistinguishedName |
Where-Object { $_.name -like 'SSL_VPN*' } |
Select-Object #{ Name = 'SamAccountName'; Expression = { $user.SamAccountName } },
#{ Name = 'Group'; Expression = { $_.name }}
}
else {
Write-Warning "User '$($_.username)' not found"
# if you want this message to also appear in your output CSV, do something like this:
[PsCustomObject]#{
'SamAccountName' = "User '$($_.username)' not found"
'Group' = ''
}
}
} | Export-Csv -Path 'C:\UserPermiss.csv' -NoTypeInformation
If you want to see a warning message when the user is not a member of the SSL_VPN group, you can do:
Import-Csv 'C:\Users.csv' | ForEach-Object {
$user = Get-ADUser -Filter "DisplayName -eq '$($_.username)'" -Properties DisplayName
if ($user) {
$group = Get-ADprincipalGroupMembership -Identity $user.DistinguishedName |
Where-Object { $_.name -like 'SSL_VPN*' }
if ($group) {
[PsCustomObject]#{
'SamAccountName' = $user.SamAccountName
'Group' = $group.name
}
}
else {
Write-Warning "User '$($_.username)' is not a member of ssl_vpn group"
}
}
else {
Write-Warning "User '$($_.username)' not found"
}
} | Export-Csv -Path 'C:\UserPermiss.csv' -NoTypeInformation
You can use something like this(frist line of csv must be samaccountname):
$users=Import-Csv D:\adusers.CSV
foreach($user in $users){
$groupname=Get-ADPrincipalGroupMembership -Identity $user.samaccountname |where {$_.name -like "SSL_VPN*"}|select -ExpandProperty name
if($groupname -ne $null){
foreach($group in $groupname){
[string]$data=($user|select -ExpandProperty samaccountname)+';'+$group
$data|Out-File -FilePath d:\stack.csv -Encoding utf8 -Append
}
}
}

What is method to use foreach on a txt file?

Below embedded foreach commands needs $user to come from list.txt, dump groups from AD into $user.txt file and remove.
How do I specify $user as each line in the list.txt whild also verifying the formatting of the list inside the list.txt is just one name per line, no comma?
foreach ($user in .\list.txt) {
$groups = (Get-ADUser $user -Properties MemberOf).MemberOf
Add-Content -Path C:\TEMP\RemoveGroups\$user.txt -Value $groups
foreach ($group in $groups) {
Remove-ADGroupMember $group -Member $user
}
$List = Get-Content .\List.txt
Foreach ($User in $List){
$Groups = (Get-ADUser $user -Properties MemberOf).MemberOf
Foreach ($GroupDN in $Groups){
Try {
$Group = Get-ADGroup $GroupDN
Remove-ADGroupMember $Group -member $user -ErrorAction Stop
$Succeed = $Succeed,$Group.Name -join ";"
}
Catch {
$Failed = $Failed,$Group.Name -Join ";"
}
}
$temp = New-Object psobject -ArgumentList #{
User = $User
Succeed = $Succeed
Failed = $Failed
}
Export-Csv -InputObject $temp -Path C:\TEMP\RemoveGroups\Result.csv -Encoding UTF8 -NoTypeInformation -Append
}
You will get the CSV file like this:
User,Succeed,Failed
user1,Group1;Group2,Group3;Group4
user2,Group2;Group3,Group1;Group4
You can use the following code.
# Read the list of users to an array of strings.
$users = Get-Content .\list.txt
foreach ($user in $users) {
# Validate that the username only contains a-z and 0-9.
if ($user -match "^[a-zA-Z0-9]+$") {
$groups = (Get-ADUser $user -Properties MemberOf).MemberOf
Add-Content -Path C:\TEMP\RemoveGroups\$user.txt -Value $groups
foreach ($group in $groups) {
Remove-ADGroupMember $group -member $user
}
}
}

Convert E-Mail Address to SamAccountName

I have a csv like this:
Group;User
TestGroup1;test1#domain.com
TestGroup2;test2#domain.com
Now I want to add the Group to the User. I cant add them by the mail address so I have to get the SamAccountName. This is what I've come up with:
Import-module ActiveDirectory
foreach ($item in (Import-CSV users.csv -delimiter ";"))
{
$userMail = $item.("User")
$userSAM = Get-ADUser -Filter {mail -eq $userMail} -Properties SamAccountName
Write-Host $item.("Group") $userSAM
}
But the Variable "UserSAM" stays emtpy.
This should return just the usernames which you can use to add the user to the group.
Import-Module ActiveDirectory
foreach ($item in (Import-CSV users.csv -Delimiter ";")) {
$userMail = $item.User
$userSAM = Get-ADUser -Filter {mail -eq $userMail} | Select-Object -ExpandProperty SamAccountName
Write-Host $item.Group $UserSAM
}
If this returns what you need just add this line into the end of the loop:
Add-ADGroupMember -Identity $item.Group -Members $UserSAM