I run this command and I get all computer hostnames in the names.txt file.
Each hostname in the file is on a separate line, but every hostname is followed with white spaces which cause an issue when I try to read this file. How can I output to this file without getting the white spaces on each line?
Get-ADComputer -Filter * | Select-Object -property name | Sort-Object -Property name | out-file -filepath C:\temp\names.txt
You have the problem that you don't just have names, you have objects with the property 'name', and you also have the problem that Out-File runs complex objects through some kind of formatting before sending them to the file.
To fix both, expand the name out to just text, and generally use Set-Content instead:
Get-ADComputer -filter * | Select-Object -ExpandProperty Name | Sort-Object | Set-Content C:\temp\names.txt
or in short form
Get-ADComputer -filter * | Select -Expand Name | Sort | sc C:\temp\names.txt
or
(Get-ADComputer -filter *).Name | sort | sc C:\temp\names.txt
expandproperty should get rid of the #()
Get-ADComputer -Filter * | sort Name | Select -expandproperty Name | %{ $_.TrimEnd(" ") } | out-file -filepath C:\temp\names
Untested no AD#home
Piping it through this should work (before piping to the out-file):
EDIT: Piping through % { $_.name } should convert #{name=VALUE} to VALUE:
% { $_ -replace ' +$','' } | % { $_.name }
Like this:
Get-ADComputer -Filter * | Select-Object -property name | Sort-Object -Property name | % { $_ -replace ' +$','' } | % { $_.name } | out-file -filepath C:\temp\names.txt
Related
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
I am looking to see what the cleaner way of writing this one liner would be.
Get-AdGroup -Filter * -Properties Name,Description,whenCreated,whenChanged,ObjectClass,GroupCategory,GroupScope,SamAccountName,DistinguishedName |
Sort-Object Name |
Select-Object Name,Description,whenCreated,whenChanged,ObjectClass,GroupCategory,GroupScope,SamAccountName,DistinguishedName |
Select *,#{Name="Members";Expression={Get-ADGroupMember $_.Name | %{$_.SamAccountName+';'}}} |
Export-Csv -Path .\Group.csv -NoTypeInformation
And assign the property names to a variable so they are written out in full twice, and combine Select-Object and select together:
$properties = "Name,Description,whenCreated,whenChanged,ObjectClass,GroupCategory,GroupScope,SamAccountName,DistinguishedName";
Get-AdGroup -filter * -properties $properties |
Select-Object $properties,#{Name="Members";Expression={Get-ADGroupMember $_.Name | %{$_.SamAccountName+';'}}} |
Sort-Object Name |
Export-Csv -Path .\Group.csv -NoTypeInformation
Note: It's a one liner command but I've spaced it out for readability.
I'm trying to get a dump of all user records and their associated groups for a user ID revalidation effort. My security officer wants it in CSV format.
This works great:
Get-ADUser -Filter * -Properties * | Select-Object -Property Name,SamAccountName,Description,EmailAddress,LastLogonDate,Manager,Title,Department,whenCreated,Enabled,Organization | Sort-Object -Property Name | ConvertTo-CSV
However, that does not include the groups the user is a member of.
Attempts at something like this have failed:
Get-ADUser -Filter * -Properties * | Select-Object -Property Name,SamAccountName,Description,EmailAddress,LastLogonDate,Manager,Title,Department,whenCreated,Enabled,Organization, #{$_.MemberOf |Get-Group|ForEach-Object {$_.Name}} | Sort-Object -Property Name | ConvertTo-CSV
This also failed:
Get-ADUser -Filter * -Properties * | Sort-Object -Property Name | ForEach-Object {
$_ | Format-List -Property Name,SamAccountName,Description,EmailAddress,LastLogonDate,Manager,Title,Department,whenCreated,Enabled
$_.MemberOf | Get-ADGroup | ForEach-Object {$_.Name} | Sort-Object
} | ConvertTo-CSV
I'm probably missing something simple.
Any help would be greatly appreciated.
Thanks!
From a Windows Server OS execute the following command for a dump of the entire Active Director:
csvde -f test.csv
This command is very broad and will give you more than necessary information. To constrain the records to only user records, you would instead want:
csvde -f test.csv -r objectClass=user
You can further restrict the command to give you only the fields you need relevant to the search requested such as:
csvde -f test.csv -r objectClass=user -l DN, sAMAccountName, department, memberOf
If you have an Exchange server and each user associated with a live person has a mailbox (as opposed to generic accounts for kiosk / lab workstations) you can use mailNickname in place of sAMAccountName.
For posterity....I figured out how to get what I needed. Here it is in case it might be useful to somebody else.
$alist = "Name`tAccountName`tDescription`tEmailAddress`tLastLogonDate`tManager`tTitle`tDepartment`tCompany`twhenCreated`tAcctEnabled`tGroups`n"
$userlist = Get-ADUser -Filter * -Properties * | Select-Object -Property Name,SamAccountName,Description,EmailAddress,LastLogonDate,Manager,Title,Department,Company,whenCreated,Enabled,MemberOf | Sort-Object -Property Name
$userlist | ForEach-Object {
$grps = $_.MemberOf | Get-ADGroup | ForEach-Object {$_.Name} | Sort-Object
$arec = $_.Name,$_.SamAccountName,$_.Description,$_.EmailAddress,$_LastLogonDate,$_.Manager,$_.Title,$_.Department,$_.Company,$_.whenCreated,$_.Enabled
$aline = ($arec -join "`t") + "`t" + ($grps -join "`t") + "`n"
$alist += $aline
}
$alist | Out-File D:\Temp\ADUsers.csv
csvde -f test.csv
This command will perform a CSV dump of every entry in your Active Directory server. You should be able to see the full DN's of users and groups.
You will have to go through that output file and get rid off the unnecessary content.
the first command is correct but change from convert to export to csv, as below,
Get-ADUser -Filter * -Properties * `
| Select-Object -Property Name,SamAccountName,Description,EmailAddress,LastLogonDate,Manager,Title,Department,whenCreated,Enabled,Organization `
| Sort-Object -Property Name `
| Export-Csv -path C:\Users\*\Desktop\file1.csv
HI you can try this...
Try..
$Ad = Get-ADUser -SearchBase "OU=OUi,DC=company,DC=com" -Filter * -Properties employeeNumber | ? {$_.employeenumber -eq ""}
$Ad | Sort-Object -Property sn, givenName | Select * | Export-Csv c:\scripts\ceridian\NoClockNumber_2013_02_12.csv -NoTypeInformation
Or
$Ad = Get-ADUser -SearchBase "OU=OUi,DC=company,DC=com" -Filter * -Properties employeeNumber | ? {$_.employeenumber -eq $null}
$Ad | Sort-Object -Property sn, givenName | Select * | Export-Csv c:\scripts\cer
Hope it works for you.
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
I am using the code below to get a list of computer names where they were last modified 181 days ago. I have a .csv file with 2 columns (ComputerName, UserName) Is there a way I can match the output from the code below with the computername column in the csv file and show the output/matches?
$Days = (Get-Date).AddDays(-181)
Get-ADComputer -Property Name,lastLogonDate -Filter {lastLogonDate -lt $Days} -Server DomainController -Searchbase "OU=US,DC=contoso,DC=net" | FT Name,lastLogonDate
Change ... | FT Name,lastLogonDate to ... | select Name,lastLogonDate. You can still pipe the result into ft to format it as a table, but separating selection from presentation will make it easier to put in additional filters.
For displaying just the computers that have matches in your CSV you could do the following:
$computers = Import-Csv 'your.csv' | % { $_.ComputerName }
Get-ADComputer -Property Name,lastLogonDate ... | select Name,lastLogonDate |
? { $computers -contains $_.Name } | ft
To include the username from the CSV with the result you could do something like this:
$computers = #{}
Import-Csv 'your.csv' | % { $computers[$_.ComputerName] = $_.UserName }
Get-ADComputer -Property Name,lastLogonDate ... |
? { $computers.Keys -contains $_.Name } |
select Name,lastLogonDate,#{n='Username';e={$computers[$_.Name]}} | ft