Powershell script : read and insert value from txt file (on 30+ entry) - powershell

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

Related

Delete users from mailbox rule

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

Powershell: How to show output onscreen and output to file?

Hope you can help. Very new to PS, so please be patient :)
I have a problem with the script below. If I put the Out-File command on line 6, the results are printed in the powershell screen, but the txt file is blank. If I put the Out-File command at the end of Line 3, the text file is populated, but it doesn't output the results in the powershell window.
I'd like it to do both.
Frustrating :(
import-module activedirectory
$username = Read-Host 'Please enter Username!'
Get-ADPrincipalGroupMembership $username | Get-ADGroup -Properties * | select name, description | Format-Table -Wrap -AutoSize
$wsh = New-Object -ComObject Wscript.Shell
$wsh.Popup("List has been saved to C:\Group_List.txt")
Out-File C:\Group_List.txt
Read-Host -Prompt "Press Enter to exit"
First of all, you do not capture the results from the Get-ADPrincipalGroupMembership cmdlet anywhere and just send it out to screen using Format-Table.
Secondly, the output does not show the user that is a member of these groups, so if you are typing another user, the file would not reveal for which user these groups are valid..
Finally, insert a test to check if the inputted username actually is an existing user.
I would go for outputting a CSV file you can simply open in Excel. Something like this:
Import-Module activedirectory
$outFile = 'C:\Group_List.csv'
$username = Read-Host 'Please enter Username!'
# do some error checking to see if this is an existing user
$user = Get-ADUser -Filter "SamAccountName -eq '$username'" -ErrorAction SilentlyContinue
if ($user) {
$groups = Get-ADPrincipalGroupMembership -Identity $user.DistinguishedName |
Get-ADGroup -Properties Description | ForEach-Object {
# output an object with properties you need
[PsCustomObject]#{
User = $username
Group = $_.Name
Description = $_.Description
}
}
# show on screen
$groups | Format-Table -Wrap -AutoSize
# write to CSV file
$groups | Export-Csv -Path $outFile -UseCulture -NoTypeInformation
$wsh = New-Object -ComObject Wscript.Shell
$wsh.Popup("List has been saved to $outFile")
# clean up COM object after use
$null = [System.Runtime.Interopservices.Marshal]::ReleaseComObject($wsh)
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
}
else {
Write-Warning "User $username does not exist.."
}
You can use Tee-Object (inspired by the classic tee unix command-line tool) to fork an input stream into a variable or to a file on disk! If you want to write the formatted table to file as-is, simply tack it onto the end of the pipeline expression that outputs to the screen (you can skip the select command, Format-Table also takes a property list)
Get-ADPrincipalGroupMembership $username | Get-ADGroup -Properties description | Format-Table -Property name,description -Wrap -AutoSize | Tee-Object -FilePath C:\Group_List.txt
If the output file is intended for later consumption by another computer/program, I would change strategies and export to a CSV file instead. To capture the data and output to both, we can assign the results of the initial query to a variable and then output twice in separate statements:
$groupsWithDescription = Get-ADPrincipalGroupMembership $username |Get-ADGroup -Properties description |Select-Object Name,Description
# Output to screen, format as table
$groupData |Format-Table -Wrap -AutoSize
# Output to file, export data as CSV
$groupData |Export-Csv -Path C:\Group_List.txt -NoTypeInformation
Try adding the outfile command after your "Get-ADPrincipalGroupMembership".
Should look something like this.
Get-ADPrincipalGroupMembership $username | Get-ADGroup -Properties * | select name, description | Format-Table -Wrap -AutoSize| Out-File -FilePath $path
Using export-csv
`$result | export-csv -Path $csvFileName -NoTypeInformation`

Using powershell to change attribute

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

Exporting Membership groups for users from input file

I have this script that reads samaccountnames from a file and outputs the name of the user with its membership information. However, the output file only shows the last record. It seems that my code is overwriting the previous record. What am I missing? Thank you so much.
ForEach ($user in $(Get-Content -Path C:\MyScripts\UsersInput.csv))
{
$username = Get-ADUser –Identity $user -Properties *
Get-ADPrincipalGroupMembership $user | select $username.DisplayName, name |
export-csv "C:\MyScripts\UsersAndTheirADGroups.csv" -NoTypeInformation
}
Export-Csv has an -append parameter, so you could use that. ie it would append to the csv file with every iteration of the loop. You would need to make sure the file didn't exist before you start the loop or it would just get bigger and bigger each time you ran the code.
Another way it to add the items to an object and then export that at the end. ie $username += Get-ADUser......
You are reading a CSV file using Get-Content. This lets me think the file is simply a list of user SamAccountNames, each on a separate line. No headings.
Something like this perhaps:
jdoe
jsmith
If that is the case, read the input file like this:
$users = Get-Content -Path 'C:\MyScripts\UsersInput.csv'
To get an array of user SAMAccountnames.
If however it is a proper CSV file with headers, looking something like this:
"SamAccountName","Email","More","Stuff"
"jdoe","john.doe#yourdomain.com","blah","blah"
"jsmith","jane.smith#yourdomain.com","blah","blah"
Then you should use the Import-Csv cmdlet to get the entries as objects and obtain an array of SamAccountNames from that:
$users = Import-Csv -Path 'C:\MyScripts\UsersInput.csv' | Select-Object -ExpandProperty SamAccountName
Once you have that array, loop through it and get the group membership info for each user
Untested
$result = foreach ($accountName in $users) {
Get-ADUser –Identity $accountName -Properties DistinguishedName, DisplayName |
Select-Object #{Name = 'User'; Expression = {$_.DisplayName}},
#{Name = 'Groups'; Expression = { ( $_ | Get-ADPrincipalGroupMembership | Select-Object -ExpandProperty name) -join ', '}}
}
$result | Export-Csv "C:\MyScripts\UsersAndTheirADGroups.csv" -NoTypeInformation
You are indeed overwriting the code ForEach user. You included Export-Csv in the ForEach. Instead export the whole array that ForEach creates:
ForEach ($user in $(Get-Content -Path C:\MyScripts\UsersInput.csv))
{
$username = Get-ADUser –Identity $user -Properties *
Get-ADPrincipalGroupMembership $user | select $username.DisplayName, name
} | export-csv "C:\MyScripts\UsersAndTheirADGroups.csv" -NoTypeInformation

search group membership for a list of users

I am quite new to PowerShell and on the site.
My issue is that I found a script which I have modified. The script is working, but only partial; it is not returning all the groups. Only 4 groups and after that is displaying "....." and no other info (you can see the picture).
Basically what I want to do is the following:
I have 100 users and I need to export the group membership of these 100 users.
[$users = Get-Content "D:\users.txt"
$adjob = foreach ($user in $users) {
Get-ADUser -server "myserver" –Identity $user –Properties MemberOf
}
$adjob | Select-Object Name,#{N='Group';E={$_.MemberOf -replace '^CN=(\[^,\]+),OU=.+$','$1'}} | Format-Table -AutoSize | out-file D:\users.csv][1]
Thise script should return:
name
user1
user2
user3
group
group1,group2,group3,rest of the groups for each User
group1,group2,group3,rest of the groups for each User
group1,group2,group3,rest of the groups for each User
Thank you for the help!
Try this:
$users = Get-Content "D:\users.txt"
$adjob = foreach ($user in $users) {
Get-ADUser -server "myserver" –Identity $user –Properties MemberOf
}
$adjob | foreach {"`n`n";$_.name, $((($_.MemberOf -split ",")| Select-String "CN") -replace "CN=","")}
The output should be username and group names right below. "`n`n" Will put two blank lines after every user.
For your particular case please try this:
Enter this on PowerShell first $FormatEnumerationLimit=-1 and then replace Format-Table -AutoSize in your original script with Format-Table -AutoSize -Wrap or Format-List