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
Related
I have a list of users in a CSV, but I need to collect the SamAccount attribute from each user by name in the ad.
CSV model
Script
Get-ADObject -Filter 'ObjectClass -eq "user" -and userAccountControl -eq "512"' -Properties * | Select-Object SamAccountName,CN,DisplayName, | Export-CSV -Path C:\Temp\UserAccounts.csv -Encoding UTF8 -NoTypeInformation
I'm a little lost I don't know how to do a foreach using name
I am trying but without success.
Trying to get samaccountname based on Name on csv file.
Import-Csv -Path C:\Temp\userteste.csv | foreach-Object {Get-ADUser -Filter {Name -like $_.name} -Properties Name | Select-Object samAccountName}
and export to csv file.
Why use Get-ADObject and not Get-ADUser for this? The latter gives you more of the desired properties you need in the CSV.
As aside, it is wasteful to do -Properties * if all you want is a small set of user attributes.
Something like this should work:
Get-ADUser -Filter "Enabled -eq $true" -Properties DisplayName, CN |
Select-Object SamAccountName, CN, DisplayName |
Export-Csv -Path C:\Temp\UserAccounts.csv -Encoding UTF8 -NoTypeInformation
As per your comment you need to get some extra attributes of the users listed in the CSV, you can do this:
Import-Csv -Path C:\Temp\userteste.csv | ForEach-Object {
Get-ADUser -Filter "Name -like '$($_.Name)'" -Properties DisplayName, CN |
Select-Object SamAccountName, CN, DisplayName
} | Export-Csv -Path C:\Temp\UserAccounts.csv -Encoding UTF8 -NoTypeInformation
Hope that helps
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
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).
I have this Powershell command:
Get-ADComputer -filter { Name -like 'srv*' } | Select -Expand dnshostname | Export-CSV -path ad_export.csv
In the CSV it only writes the length of the Strings. I read that I have to pipe an object to Export-CSV so it writes the Servernames and not only the length. How do I do that?
Based on the requirement , you can use :
Get-ADComputer -Filter 'ObjectClass -eq "Computer"' | Select -Expand DNSHostName | Export-CSV -path ad_export.csv
# Getting just the hostname
Get-ADComputer -Filter * | Select -Expand Name | Export-CSV -path ad_export.csv
# Getting a specific computer
Get-ADComputer -Filter { Name -eq 'server2012' } -Propert LastLogonTimestamp | Select DistinguishedName, LastLogonTimestamp | Format-Table -AutoSize | Export-CSV -path ad_export.csv
Note: You can use the "where" clause also if required.
Hope This suffice your need
I have a PowerShell script below
$ous = 'ou=office,dc=xxx,dc=com',`
'ou=shop0,dc=xxx,dc=com',`
'ou=shop1,dc=xxx,dc=com',`
'ou=shop2,dc=xxx,dc=com'
$outfile = 'c:\work\userinfo.csv'
New-Item -Force -type "file" -Path 'c:\work\userinfo.csv'
$ous | ForEach {
Get-ADUser -Filter * -SearchBase $_ |
Select-Object -Property CN,`
DisplayName,`
GivenName,`
Surname,`
SamAccountName,`
PasswordExpired,`
mail,`
Description,`
Office,`
EmployeeNumber,`
Title |
Sort-Object -Property Name |
export-csv -Append $outfile -NoTypeInformation
}
Then when I run it, I got error message "New-Item: access to the path c:\work\userinfo.csv" is denied.
What's the cause for this error?
Update:
In my case, somehow, PowerShell is case-sensitive....the output folder name is uppercase, in my script is lowercase, it works after I match them.
I am bypassing the reason for the error ( of which I'm not sure of the cause.). Another way to get what you want
each time I run script, I could get an fresh result without previous results
You just need to move the output code outside the loop and remove the append. Pipeline handles the Append for you.
$ous | ForEach {
Get-ADUser -Filter * -SearchBase $_ |
Select-Object -Property CN,`
DisplayName,`
GivenName,`
Surname,`
SamAccountName,`
PasswordExpired,`
mail,`
Description,`
Office,`
EmployeeNumber,`
Title
} | Sort-Object -Property Name |
export-csv -Append $outfile -NoTypeInformation
Noticed something
You are not calling all the properties you are using in your select statement. That should lead to some null columns in your output. I would update your code to something like this.
$props = "CN","DisplayName","GivenName","Surname","SamAccountName","PasswordExpired","mail","Description","Office","EmployeeNumber","Title"
$ous | ForEach-Object {
Get-ADUser -Filter * -SearchBase $_ -Properties $props | Select-Object $props
} | Sort-Object -Property Name |
export-csv $outfile -NoTypeInformation