Active Directory Powershell to fixed width txt file - powershell

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

Related

use samaccountnames to export user properties(mainly just first name and lastname) to csv file

I have a CSV file containing the samaccount name of some users.
From this list, I want to export the properties of these users to a CSV file.
Kindly share the simplest possible way to do so in Windows Powershell ISE.
I have tried this :
Import-ModuleActiveDirectory
Import-CSV C:\scripts\list.csv | ForEach{Get-ADUser -Identity $samaccountname-Filter*-Properties*|export-csv c:\ADusers.csv
}
Thank you!
You didn't show us the first couple of lines of the CSV file.
A proper CSV file has multiple fields and a header line like this:
"AccountName","EmailAddress"
"doe","john.doe#example.com"
"kent","clark.kent#example.com"
If this is the case, do:
Import-ModuleActiveDirectory
$userProperties = 'GivenName', 'SurName', 'Initials'
Import-Csv -Path "C:\Scripts\List.csv" | ForEach-Object {
$user = Get-ADUser -Filter "SamAccountName -eq '$($_.AccountName)'" -Properties $userProperties -ErrorAction SilentlyContinue
if ($user) {
$user | Select-Object -Property $userProperties
}
} | Export-Csv "C:\ADUsers.csv"
If the file you load only has SamAccountNames each listed on a new line, then this is not a CSV file and you should use:
Import-ModuleActiveDirectory
$userProperties = 'GivenName', 'SurName', 'Initials'
Get-Content -Path "C:\Scripts\List.csv" | ForEach-Object {
$user = Get-ADUser -Filter "SamAccountName -eq '$_'" -Properties $userProperties -ErrorAction SilentlyContinue
if ($user) {
$user | Select-Object -Property $userProperties
}
} | Export-Csv "C:\ADUsers.csv"
As you can see, I'm not using the -Identity parameter here, because in case a user with that SamAccountName is not found, an exception is thrown.
This way, output is only generated when the user actually exists.
Also, it is a bad idea to use -Properties * when you only want some of the properties returned.
Hope that helps
if you wanna do this in the ISE, you probably dont need/want to use oneliner for that.
I would suggest to import the CSV first, and then run foreach.
$list = Import-CSV -path $filePath
$result = New-Object System.Collections.ArrayList
foreach ($name in $list){
$adUser=Get-ADUser -Identity $name
$result += $adUser
}
From here, you can start thinking of error handling etc.
This will help you:
Import-ModuleActiveDirectory
Import-CSV -Path "C:\Scripts\List.csv" | Foreach {
Get-ADUser -Identity $_ -Filter * -Properties *
} | Export-CSV "C:\ADUsers.csv"
Your code was not working because $samaccountname was empty and blank not containing the username. So I replaced it with the automatic variable $_
Put each SamAccountName on its own line in the list file.
Example:
user1
user2
user3
Change list.csv to a text file (list.txt) and try this:
$username = Get-Content "C:\scripts\list.txt"
ForEach($user in $username){
Get-ADUser -Identity $user | Select GivenName,Surname,Initials | Export-CSV -Path "C:\ADUsers.csv"
}

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

Get-ADuser and export to multiple CSV files

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

Powershell Import-CSV and Foreach-Object, excluding with the CSV header

I'm trying to get the SAMAccountNames of one domain and compare them with their equals from another domain.
To get all users of dc1 I use:
Get-ADUser -Filter * -SearchBase $SearchBase | Select-Object SamAccountName |
Export-Csv -path $exports -encoding "unicode" -notype
and then I import the csv again and try to compare them for any differences
$readthat = Import-CSV $exports -Header SamAccountName | ForEach-Object {
$user1 = Get-ADUser -Identity $_.SamAccountName -Properties $attributes
$user2 = Get-ADUser -Identity $_.SamAccountName -Properties $attributes -Server $dc2
$modified = #{}
$attributes | Where-Object { $user1.$_ -ne $user2.$_ } | ForEach-Object {
$modified[$_] = $user2.$_
}
}
All that works great, except that it's also trying to find the SamAccountName which of course genereates an error because the SamAccountName = SamAccountName doesn't exit.
Any hints on how to avoid this or do you guys have a more elegant solution?
the .csv looks like this:
"SamAccountName"
"foo"
"bar"
Don't use the -Header SamAccountName option on your import-csv should help immensely. The -Header option is for when the CSV file you are importing doesn't have a header. The Export-CSV cmdlet puts the header in there for you, so you don't have to.

AD query Powershell and Export to txt file

Can someone help me?
I have to create a .txt file with the following format:
user("SamAccountName","GivenName Surname"){}
I'm able to create just this:
#Get AD Users Info
cls
$SamAccountName = New-Item 'c:\SamAccountName.txt' -type file -Force
Get-ADUser -Filter * -Properties SamAccountName |
select -First 15 | Sort-Object SamAccountName |
Format-Table SamAccountName | Out-File $SamAccountName
$content = Get-Content $SamAccountName
$content | Foreach {$_.TrimEnd() } | where {$_ -ne ""} | Select-Object -Skip 3 | Set-Content $SamAccountName
#Write quotes (make it nice and readable!)
$ACTIVEDIRECTORY = New-Item 'c:\ACTIVEDIRECTORY.lst' -type file -Force
Clear-Content $ACTIVEDIRECTORY
$quotes= '"'
(Get-Content $SamAccountName) |
ForEach-Object {Add-Content $ACTIVEDIRECTORY "$quotes$_$quotes"}
Get-Content $ACTIVEDIRECTORY
This give me this result:
"GivenName"
"GivenName"
"GivenName"
I agree with #notjustme about your question being a mess, but I'll throw an answer out there anyway.
Your first problem is how you set these two variables. They end up being objects, but you're trying to use them like file paths.
$SamAccountName = "c:\SamAccountName.txt"
$ACTIVEDIRECTORY = "c:\ACTIVEDIRECTORY.lst"
This will get you a comma separated list of your users, which is (sort of) what part of your code is doing.
Get-ADUser -Filter * | Select-Object SamAccountName, GivenName, SurName -First 15 | Sort-Object SamAccountName | Export-Csv $SamAccountName -NoTypeInformation
This will get you the list of users with the string format you specified at the top, which is odd, but whatever.
Import-Csv $SamAccountName | ForEach-Object {"user(`"$($_.SamAccountName)`",`"$($_.GivenName) $($_.Surname)`"){}"} | Out-File $ACTIVEDIRECTORY
Can't try it out myself at the moment but... from experience...
-properties * | select SamAccountName, GivenName, Surname
Should get ya in the ballpark.
Re-read your code a few times and well... it seems a mess to be honest. You state what you wanna accomplish and then there's a crud-load of other stuff that make close to no sense in this case. Maybe I'm just too tired, I'll check back in the morning and edit/delete if needed.
Allright, re-read a few more times and the headache is given but still...
In general I'd like to advise you (or anyone, really) if Powershell get's confuzzling to break it down in easily processable pieces.
For the users;
$users = Get-ADUser -Filter { Name -like '*' } -Properties * | select SamAccountName, Givenname, Surname
For the output;
foreach ($user in $users)
{
'("{0}""{1}{2}"' -f $user.SamAccountName, $user.GivenName, $user.Surname
}
Unfortunatly I have no way to try this out myself at the moment but it should be in the ballpark... if you end up getting some errors, lemme know and I'm sure I can guide ya through it. I'm not 100% sure about them single and doublequotes in this particular case... I'd have to try it out.