How to set Get-ADComputer result as object - powershell

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

Related

collect samaccount powershell

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

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

Export-Csv doesn't show AD group name while exporting its members

I have a list with AD groups in a CSV file: Input_ADGroup.csv
Column A looks like this:
CN
ADgroup1
ADgroup2
I already have some code which list all the users of the groups in the output.csv file, however I am missing the ADgroup name. So it is unclear which users are member of which group.
$Manager = #{Name = "Manager"; Expression = {%{(Get-ADUser $_.Manager -Properties DisplayName).DisplayName}}}
$Manager_Location = #{Name = "Manager_Location"; Expression = {%{(Get-ADUser $_.Manager -Properties Office).Office}}}
$Fields = #(
'SamAccountName'
'CN'
'DisplayName'
'Office'
'mail'
'Department'
$Manager
$Manager_Location
)
Import-Csv -Path H:\Test\Input_ADGroup.csv |
ForEach-Object {
Get-ADGroup -Filter "CN -eq '$($_.CN)'" -Properties * -ErrorAction SilentlyContinue |
Get-ADGroupMember | Get-ADUser -properties * | Select $Fields
} | Export-Csv -Path H:\Test\Output_ADGroup.csv -NoTypeInformation
H:\Test\Output_ADGroup.csv
So is it possible to get a column which shows the "source-ADgroup"... or another format which breaks the list with the ADGroup name or something?
IMO my other suggested solution is more efficient applyig the same CN from the input:
$Data = ForEach($CN in (Import-Csv -Path H:\Test\Input_ADGroup.csv).CN) {
Get-ADGroup -Filter "CN -eq '$CN'" -Properties CN -ErrorAction SilentlyContinue |
Get-ADGroupMember | Get-ADUser -Properties * | Select-Object ($Fields+#{n="Group";e={$CN}})
}
$Data
$Data | Export-Csv -Path H:\Test\Output_ADGroup.csv -NoTypeInformation
As you already have AD group name in $_, you can add one more calculated property to your Select-Object by changing this:
Get-ADGroup -Filter "CN -eq '$($_.CN)'" -Properties * -ErrorAction SilentlyContinue |
Get-ADGroupMember | Get-ADUser -properties * | Select $Fields
to this (saving first group name to variable to not mix up with $_ used later in pipeline):
$GroupName = $_.CN
Get-ADGroup -Filter "CN -eq '$($_.CN)'" -Properties * -ErrorAction SilentlyContinue |
Get-ADGroupMember | Get-ADUser -properties * | Select ($Fields+#{n="Group";e={$GroupName}})
Credits to #LotPings and #Maikel for pointing out the issue with incorrect $_ usage in comments
NOTE: remember about brackets, otherwise you'd receive an error like:
Select-Object : A positional parameter cannot be found that accepts argument n="Group";e={$GroupName}
#Lotpings #robdy - Thanks for your input, I got it working so many thanks. See code below
Import-Csv -Path H:\Test\Input_ADGroup.csv |
ForEach-Object {
Get-ADGroup -Filter "CN -eq '$($_.CN)'" -Properties CN -PipelineVariable name -ErrorAction SilentlyContinue |
Get-ADGroupMember | Get-ADUser -properties * | Select ($Fields+#{n="Group";e={$name}})
} | Export-Csv -Path H:\Test\Output_ADGroup.csv -NoTypeInformation
H:\Test\Output_ADGroup.csv
One last note: The AD group gets displayed as CN=Groupname,OU=...OU=… etc
I couldn't get it to show just "Groupname" but this really is not an issue.

How do I write this PowerShell query more efficiently?

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.

How to export list of group and users to CSV? [duplicate]

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.