I'm trying to pump out a list of users in a specific OU along with their group memberships to a CSV. I wanted a list of groups but I get "Microsoft.ActiveDirectory.Management.ADPropertyValueCollection" My command is
Get-ADUser -Filter * -SearchBase "ou=Vendor Accounts,dc=mydomain,dc=com" -Properties * | Select ‘Name’,’DisplayName’,’SamAccountName’, #{Name=’MemberOf';Expression={[string]::join(“;”, ($_.MemberOf))}}| export-csv c:\temp\citrix_vendors.csv -NoTypeInformation -Append
I get all the other properties as expected, pretty columns and everything, but can't seem to get the multi-valued attribute to output the way I want. I'm running v4.
I looked at How to list AD group membership for AD users using input list? and tried implementing a similar fix,
$GroupMembership = ($user.memberof | % { (Get-ADGroup $_).Name; }) -join ';';
$user = Get-ADUser -Filter * -SearchBase "ou=Vendor Accounts,dc=mydomain,dc=com" -Properties *
$user.Samaccountname + ',' + $GroupMembership | export-csv c:\scripts\citrix_vendors.csv -NoTypeInformation -Append
but the output Changed from Columns with almost all the info I am grabbing to a single column titled "Length" with a number in each row.
Related
I have a computers that have assigned to users as managedby, I want to get list in JSON format where hostname is a key, and user attributes are values.
But I stuck to get that in one command :/ and put that in json, so use csv for a while.
I run these 2 commands succesfuly:
Get-ADComputer -Filter * -property managedby | select name, managedby > C:\Windows\Temp\computerowners.csv
Get-ADUser -Filter * -SearchBase 'CN=My User,DC=example,DC=com' -Properties SamAccountName | Format-Table -Property Name, samaccountname, userprincipalname -AutoSize
where search base is managedby value from first one.
I expect to have output like that:
hostname, name, samaccountname, userprincipalname
I try to combine above 2 commands like that:
Get-ADComputer -Filter * -property managedby | foreach {get-aduser -Filter * -SearchBase $managedby -Properties name, samaccountname, userprincipalname} | select name, samaccountname, userprincipalname > C:\Windows\Temp\computerowners.csv
but it want work - as not pickup managedby properly as I understand... any help with saving that in json will be more than welcome.
You didn't define the variable $managedby that you use in the ForEach-Object loop, hence the variable is $null. You need to use the property ManagedBy of the current object in the pipeline ($_.ManagedBy).
With that said, you're making the whole thing way more complicated than it needs to be. PowerShell can do a lot of the heavy lifting for you if you allow it to. Get-ADUser can read from the pipeline, so all you need to do is pass the owner's distinguished name. You also don't need to explicitly specify the properties Name, SamAccountName and UserPrincipalName, because Get-ADUser returns them by default. Plus, since you want CSV output anyway, use Export-Csv instead of the redirection operator.
Get-ADComputer -Filter * -Property managedby |
Select-Object -Expand ManagedBy |
Get-ADUser |
Select-Object Name, SamAccountName, UserPrincipalName |
Export-Csv C:\Windows\Temp\computerowners.csv -NoType
To include the computername in the output adjust the above code as follows:
Get-ADComputer -Filter * -Property managedby |
ForEach-Object {
$computer = $_.Name
if ($_.ManagedBy) { Get-ADUser $_.ManagedBy } else { '' }
} |
Select-Object #{n='ComputerName';e={$computer}}, Name, SamAccountName,
UserPrincipalName |
Export-Csv C:\Windows\Temp\computerowners.csv -NoType
To get a datastructure that can be exported to JSON using the computername as the key for the nested user attributes a different approach would be more elegant, though. Collect all relevant user attributes in a hashtable with the computername as the key:
$computers = #{}
Get-ADComputer -Filter * -Property managedby | ForEach-Object {
$computers[$_.Name] = if ($_.ManagedBy) {
Get-ADUser $_.ManagedBy | Select-Object Name, SamAccountName, UserPrincipalName
} else {
New-Object -Type PSObject -Property #{
Name = ''
SamAccountName = ''
UserPrincipalName = ''
}
}
}
Then create an object from that hashtable and convert it to JSON:
New-Object -Type PSObject -Property $computers | ConvertTo-Json
This should get you pretty far:
Get-ADComputer -Filter * -Property ManagedBy,CN | ForEach-Object {
# only query AD if there actually is a manager
if ($_.ManagedBy) {
$manager = $_.ManagedBy | Get-ADUser
} else {
$manager = $null
}
# return a custom object with 4 properties
[pscustomobject]#{
hostname = $_.CN
name = $manager.Name
samaccountname = $manager.SamAccountName
userprincipalname = $manager.UserPrincipalName
}
}
Note: Any value created in a script block and not explicitly captured in a variable or explicitly discarded via Out-Null automatically becomes a return value of that block. In this case, the ForEach-Object body will emit a series of PSCustomObject instances.
Use the result in any way you like, for example format it as JSON or CSV.
Related reading
How do I return a custom object in Powershell that's formatted as a table?
Jonathan Medd's Blog: PowerShell v3 – Creating Objects With [pscustomobject]
I am looking at a way to list how many times an AD property matching a certain value appears against each user.
Specifically - Users in our AD have a Custom Attribute distinguishing their company. I need to run monthly reports that will display a list of all companies and how many users are listed.
This is as close as I have it - but it is not user friendly for our Accounts team.
import-csv c:\HostedCompanyList.csv -header ID |
foreach {
$total = (get-aduser -filter "(extensionattribute1 -eq '$($_.ID)') -and (extensionattribute2 -eq 'billed')" -properties *).count
write-host $total $_.ID
}
This is the content of HostedCompanyList.csv
ID
Company1
Company2
Company3
My output shows as `
35 Company1
12 Company2
27 Company3
I'd like to output this information to a CSV or HTML file as opposed to displaying it on the PS window.
I appreciate this is likely already a very long winded way of running this query - could I perhaps have overlooked a much simpler method?
Bonus points if there's a way I can do this without having to import a CSV file at all - that would cut out the need to add additional entries into that list when new "companies" get added on or taken away!
Thank you for any help offered.
Untested, since I don't have the same extension attributes, but this shape:
query everyone, filter the billed people
group-object by company name
select properties and export to csv
should work with one query, no text file to read from, and csv export.
$filter = "extensionattribute2 -eq 'billed'"
$users = Get-ADUser -filter $filter -Property extensionattribute1, extensionattribute2
$groups = $users | Group -Property extensionattribute1
$groups | select Count, Name | Export-Csv out.csv -notypeinformation
I have a CSV file with a list of PC's in my domain. I wanted to get the "Description" Field information from AD for each of the machines listed in AD. This is what I have so far:
Import-Module ActiveDirectory
Get-ADComputer -Filter {OperatingSystem -NotLike "*Server*"} -SearchBase "OU=Active,OU=Regular Computers,OU=EPComputers,DC=epenergy,DC=net" -Properties * | Select-Object Name,OperatingSystem,CanonicalName | Export-Csv C:\PCList.csv -NoTypeInformation
I am not sure where I need to add in the get-ADObject and filter out the Description Field or even where to begin on that. Any help would be awesome!
Thank You!
You are currently only outputting the following properties: Name,OperatingSystem,CanonicalName to your CVS. If you add Description to the list of objects your are selecting you should also get the Description properties too.
Select-Object Name,OperatingSystem,CanonicalName,Description
this would make your block of code:
Import-Module ActiveDirectory
Get-ADComputer -Filter {OperatingSystem -NotLike "*Server*"} -SearchBase "OU=Active,OU=Regular Computers,OU=EPComputers,DC=epenergy,DC=net" -Properties * | Select-Object Name,OperatingSystem,CanonicalName,Description | Export-Csv C:\PCList.csv -NoTypeInformation
I did my testing using the following though, it returned the name, Description, OperatingSystem and CanonicalName of all of the machines on my domain:
Import-Module ActiveDirectory
Get-ADComputer -Filter * -Properties * | Select-object name,Description,OperatingSystem,CanonicalName | Export-Csv C:\PCList.csv -NoTypeInformation
You might find this website useful, I can almost always find answers to my powershell questions on ss64
I'm working in a test environment with about 1000 users and I'm trying to create a CSV with the following headers to be used in Elastix: Display Name, User Extension, Secret, Tech.
The users currently do not have extensions assigned to them and random extensions would be fine. The secret will be "123456" for all of them. The Tech will be "Sip" for all of them.
Currently I have this, but I'm struggling to strip the name off each user in my loop:
$users = get-aduser -filter * | Select Name
$outpath = "C:\scripts\users.csv"
$outputArray =#()
"Display Name, User Extension, Secret, Tech"|out-file $outpath -Force
$ext = 1000
foreach($row in $users)
{
$outputArray += "," + $ext++ + "," + "123456" + "," + "Sip"
}
$outputArray | out-file $outpath -Force
Use can do this using the Select-Object cmdlet with 'calculated properties' and the Export-Csv cmdlet.
(Note: In my original answer I did not specify the script scope for the randomExtension variable when modified in an expression. When trying to fix, I found the solution here: How can I increase the value of a variable in an expression?
$outputPath = "C:\test\users.csv"
$script:randomExtension = 1000
get-aduser -filter * |
Select #{n='Display Name';e={$_.Name}},
#{n='User Extension';e={$script:randomExtension++; $script:randomExtension}},
#{n='Secret';e={'123456'}},
#{n='Tech';e={'Sip'}} |
Export-Csv -Path $outputPath -NoTypeInformation
I have this script that will only list a user's groups on the ISE screen where the data can be copied and pasted elsewhere, but I'm trying to get the group membership names written into the Telephone Notes tab (or Info field). I'm thinking next that these probably need to be turned into string values since I'm getting errors about multi properties not allowed. Here is what I've been trying, but I keep getting errors. Thanks
Import-Module ActiveDirectory
$Users= Import-csv "C:\Scripts\UsersSAM-DisplayName.csv"
ForEach ($User in $Users) {
$SamAccountName=$User.SamAccountName
$DisplayName=$User.DisplayName
$TableFormat= #{E={$_.Name};L="$($DisplayName) - $($SamAccountName)"}
Get-ADUser -Identity $SamAccountName -Properties MemberOf | % {$_.MemberOf } | % {Get-ADGroup -Identity $_ } | % { Set-ADUser -Identity $SamAccountName -add #{info="$_.name"}} | Select Name |
Format-Table $TableFormat }
I figured this out. What they wanted was to first write out a terminated user's groups, then remove those. I did it like this and this code includes the semi-colon so if the user comes back, all you need to do to add them back to all the groups is copy and paste those from the output stored in the Telephones Tab, Notes field. I've also used a trimmed down version of this to export a user's groups to speed up duplicating a user's groups so they match with others on the same team. Hope this helps someone.
Import-csv "$Terms" | % {
$user = Get-ADUser -LDAPFilter ("(sAMAccountName=" + $_.samaccountname + ")") -Properties samaccountname,enabled,name,memberof,distinguishedname,info
#Grab all user group names
$user | ForEach-Object {
$grps = $_.MemberOf | Get-ADGroup | ForEach-Object {$_.Name} | Sort-Object
$arec = $_.Name,$_.SamAccountName
$aline = ($grps -join ";")
#Add info to Notes field Telephone Tab
Get-ADPrincipalGroupMembership -Identity $user | %{
If ($_.SamAccountName -ne "Domain Users") {
$Userinfo=$user.info
Set-ADUser $User -replace #{info= "$Userinfo | $a | Terminated via automated process | $aline"}
#Remove User Groups Process in Telephones Tab Notes Field.
Remove-ADPrincipalGroupMembership -Identity $user -MemberOf $_.SamAccountName -Confirm:$false
(" "+ $a +" [" + $User.samaccountname + "], Removed from group [" + $_.samaccountname + "]. ") | Out-File -FilePath $ErrorLog -Append
}
}}}