Get-ADuser and export to multiple CSV files - powershell

I'm using the following command to grab users from an OU and export to csv file:
Get-ADUser -Filter * -SearchBase 'OU=Contoso Users,OU=Contoso,DC=domain,DC=local' -Properties * | Select UserPrincipalName, EmailAddress | Sort UserPrincipalName | Export-CSV $UsersToMigrate -NoTypeInformation -Force
Is there anyway to export to multiple csv files of 10 users per file?

Append to the respective output file in a loop and use a counter and integer division to determine the actual filename.
$i = 0
... | Sort UserPrincipalName | ForEach-Object {
$csv = "C:\path\to\output_$([Math]::Floor([int]$i/[int]10)).csv"
$_ | Export-Csv $csv -NoType -Append
$i++
}

$Users = Get-ADUser -Filter * -SearchBase 'OU=Contoso Users,OU=Contoso,DC=domain,DC=local' -Properties * | Select UserPrincipalName, EmailAddress | Sort UserPrincipalName
$Users | ForEach-Object -Begin {$i = 1} {
$_ | Export-CSV "$UsersToMigrate-$([Math]::Ceiling($i++ / 10)).csv" -NoTypeInformation -Append
}
Explanation
Iterates through the collection of users with ForEach-Object, initialising a counter variable $i as 1 in a Begin block first.
Divides the counter by 10 and rounds up to the nearest integer. Uses this as part of the CSV name and exports to the CSV with the -Append switch (requires PSv3+ I believe).

Related

Renaming computer based using Powershell and CSV

I'm trying to create a Powershell script that creates a CSV from a specific OU, takes the last created computer (ie computer-200), adds 1 (so computer-201) and renames the computer. I was able to create the CSV but haven't been able to add an increment of 1 to the name.
Here is the script so far:
Add-WindowsCapability –online –Name “Rsat.ActiveDirectory.DS-LDS.Tools~~~~0.0.1.0”
$OUpath = 'OU=Computers,OU=Test-Devices,DC=Test,DC=local'
$ExportPath = 'c:\temp\computers_in_ou.csv'
Get-ADComputer -Filter * -SearchBase $OUpath -Properties whenCreated | select-object Name,whenCreated | sort whenCreated | Export-Csv -NoType $ExportPath
$csvdata = Import-Csv 'c:\temp\computers_in_ou.csv'
$csvdata | Select-Object Name -Last 1 | Export-Csv -NoType 'c:\temp\renameWS.csv'
$name = Import-Csv 'c:\temp\renameWS.csv' | Select-Object Name -Last 1
The $name shows output of
Name: Computer-200
How can I take that 200 and add 1?
Thank you!
You can use replacing Regex.Replace with a script block to increment the digits in the computer's name by 1:
For example:
[regex]::Replace('computer-200', '\d+', {
param($s)
[int] $n = $s.Value; (++ $n)
})
# Results in: `computer-201`
If you have access to PowerShell Core, Replacement with a script block was added in PowerShell 6 and later:
'computer-200' -replace '\d+', {
$n = [int] $_.Value; (++ $n)
}
Following above examples, you could do the following to get the latest computer name and increment the digits by 1:
$computers = Get-ADComputer -Filter * -SearchBase $OUpath -Properties whenCreated |
Select-Object Name, whenCreated | Sort-Object whenCreated
[regex]::Replace($computers[-1].Name, '\d+', {
param($s)
[int] $n = $s.Value; (++ $n)
})
It really depends on the exact format/trustworthiness of your CSV data, but here's a non-regex way to accomplish this using your existing code.
$csvdata = Import-Csv 'c:\temp\renameWS.csv'
$split = $csvdata[-1].name.Split('-')
$addOne = [int]$split[1] + 1
$final = $split[0] + '-' + $addOne
You can then take that $final string output and append to your CSV, rename with other cmdlets, etc.

Output Powershell Domain Search on separate excel sheets

I'm executing a Get-ADComputer and trying to iterate through a loop that pulls computer names from individual rooms. I'm trying to output each room to a different Excel sheet.
I'm running PowerShell Version 5:
$results = for($room=102; $room -le 110; $room++) {
Get-ADComputer -SearchBase $oubase -Properties Name, Description -Filter * |
Where-Object {$_.description -clike "*RM $Room"}
}
$results |
Select-Object Name, Description |
Export-CSV '\\Desktop\Room_Hosts.csv' -NoTypeInformation -Encoding UTF8 -Append
What do I need to do to fix the Excel sheet output?
Your post says you want an Excel sheet, but your code is outputting to a CSV. You cannot add a second sheet to a CSV. You can export different CSV files per computer object.
$results = for($room=102; $room -le 110; $room++) {
Get-ADComputer -SearchBase $oubase -Properties Name, Description -Filter * |
Where-Object {$_.description -clike "*RM $Room"}
}
$results |
Select-Object Name, Description | Foreach-Object {
$_ | Export-CSV -Path ("\\Desktop\{0}.csv" -f $_.Name) -NoTypeInformation -Encoding UTF8 -Append
If the problem is getting the domain name, you can add some code to your Select-Object command.
$results = for($room=102; $room -le 110; $room++) {
Get-ADComputer -SearchBase $oubase -Properties Name,Description,DNSHostName -Filter * |
Where-Object {$_.description -clike "*RM $Room"}
}
$results |
Select-Object Name,Description,#{n='Domain';e={$_.DNSHostName -Replace $("{0}." -f $_.Name}} |
Export-CSV '\\Desktop\Room_Hosts.csv' -NoTypeInformation -Encoding UTF8 -Append
Explanation For Retrieving Computer Object's Domain:
The DNSHostName property contains the FQDN of the computer object. So you only need to remove the host name part of that string. Here, we simply replace the hostname and the following . character with nothing. Hostname is retrieved from the Name property of the computer object. The -f operator is used to simply append the . character to the name. The Select-Object uses a hash table to calculate the domain value and store it in a property called Domain.
Alternatively, you can apply the same concepts from above for getting the domain name but use the CanonicalName of the computer object with the -Split operator.
$results = for($room=102; $room -le 110; $room++) {
Get-ADComputer -SearchBase $oubase -Properties Name,CanonicalName,Description -Filter * |
Where-Object {$_.description -clike "*RM $Room"}
}
$results |
Select-Object Name,Description,#{n='Domain';e={($_.CanonicalName -Split "/")[0]}} |
Export-CSV '\\Desktop\Room_Hosts.csv' -NoTypeInformation -Encoding UTF8 -Append

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

Active Directory Powershell to fixed width txt file

Trying to export 4 objects from Ad to a fixed-width txt file with no header.
I need the following columns to be the width that follows.
Employee ID 10
Work Phone 10
Work Phone Extension 5
Work Email Address 50
User ID 20
The following gives me the best output, but doesn't size the columns the way I need. I have been digging around, and think what I need is a bit beyond what I'm comfortable with.
I'm not sure if i need to export with export-csv and then import that into reformat or if I can do out-file directly.
$DateTime = Get-Date -f "yyyyMMdd"
#// Set CSV file name
$CSVFile = "d:\scripts\workday\int002_"+$DateTime+".txt"
Get-ADGroup -Filter {(name -like "*Group Name*")} `
| Get-ADGroupMember -Recursive | Where { $_.objectClass -eq "user" } `
| Get-ADUser -properties * | where {$_.enabled -eq $true} `
| select employeeid,telephoneNumber,mail,sAMAccountName -unique | FT employeeid,telephoneNumber,mail,sAMAccountName -hidetableheaders -autosize | out-file $CSVFile
Sample Output:
8855 2122445710 xxxry.michalsen#companydomain.com michalsenm
You might need to do it manually...
$result = foreach($user in $users) {
$user.employeeid.PadRight(10),
$user.telephoneNumber.PadRight(10),
$user.mail.PadRight(50),
$user.sAMAccountName.PadRight(20) -join ' '
}
$result | Out-File $CSVFile
A revised version that also works if the property is not a string:
$result = foreach($user in $users) {
'{0,-10}{1,-10}{2,-50}{3,-20}' -f
$user.employeeid,
$user.telephoneNumber,
$user.mail,
$user.sAMAccountName
}
$result | Out-File $CSVFile

Powershell Active Directory get all users from my AD groups

I try since a while to create a csv file which contain:
"Group Name","SamAccountName"
Where GroupName is the name of the Group abd SamAccountName is the name of the user which is part of the Group.
I try this:
Get-ADUser -Filter * -Properties DisplayName,memberof | % {
$Name = $_.DisplayName
$_.memberof | Get-ADGroup | Select #{N="User";E={$Name}},Name
} | Export-Csv -NoTypeInformation -Encoding UTF8 -delimiter "," "All_Users_With_All_Their_Groups.csv"
However it doesn't work like I want.
I try to google many example but it's not pretty simple I think as I don't find some relevant example.
Do you have any idea?
This should do your work:
Import-Module ActiveDirectory ;
Get-ADGroup -Filter {name -like "*Your Group Name*"} -Properties Description,info | Select Name,samaccountname | Export-Csv D:\output.csv -NoTypeInformation
Get-ADGroupMember YourGroupName # to list members ;
I've created two ways, dunno which one You wanted
get-aduser -Filter * -Properties memberof |
%{[pscustomobject]`
#{'Groups Names'=$(($_.memberof | Get-ADGroup).name -join "," );
User=$($_.samaccountname)}}|
Export-Csv -NoTypeInformation -Encoding UTF8 -Delimiter ',' "output.csv"
Get-ADGroup -Filter * -Properties members |
%{[pscustomobject]#{'Group'=$($_.name);
'Members'=$(($_.members | Get-ADUser).samaccountname -join ",")}} |
Export-Csv -NoTypeInformation -Encoding UTF8 -Delimiter ',' "output.csv"