Maikel
Maikel

Reputation: 27

Powershell - directreports -recurse

Although I know some basic Powershell stuff, I still find it hard to do some more advanced stuff, like using If statements etc.
I have a simple code to get the directReports of a manager:

Get-ADUser -filter {CN -eq "TestMngr"} -properties directReports | 
Select-Object -ExpandProperty directreports |  
Get-ADUser -properties CN, DisplayName, Office, directReports |
Select-Object CN, DisplayName, Office, directReports

This code works fine and has the correct lay-out.
But now I want to also list the directReports of the first list of directReports, and so on...
I tried it with an If statement, but failed. Also tried with -recurse but also did not work. Also found some code somewhere online, but that was very complicated and did not work like I would.
Please help, thanks again :-)

Upvotes: 0

Views: 2041

Answers (2)

Maikel
Maikel

Reputation: 27

This is the code I finally use, thanks to @AdminOfThings.

$Manager = @{Name = "Manager"; Expression = {%{(Get-ADUser $_.Manager -Properties DisplayName).DisplayName}}}
$depth = 8
$UserCN = '<CN of User>'
$user = (Get-ADUser -Filter "CN -eq '$UserCN'").SamAccountName

$output = while ($depth -ge 1) {
    $temp = $user | Foreach-Object {
        Get-ADUser $_ -Properties CN, displayname, office, city, manager, DirectReports | 
            Select-Object -Property CN, displayname, office, city, Manager, DirectReports
    }
    $temp
    $user = $temp.DirectReports
    $depth--
}

$output |
    Select-Object CN, displayname, office, city, $Manager, @{Name='DirectReports';Expression={
       ($_.DirectReports -replace 'CN=|,OU=.*|,DC=.*|\\') -join '; '}} |
           Export-Csv -path C:Temp\Output.csv -Delimiter ";" -NoType

Upvotes: 0

AdminOfThings
AdminOfThings

Reputation: 25021

You could do something like the following:

$depth = 2
$UserCN = '<CN of User>'
$user = (Get-ADUser -Filter "CN -eq '$UserCN'").SamAccountName

$output = while ($depth -ge 1) {
    $temp = $user | Foreach-Object {
        Get-ADUser $_ -Properties CN,DirectReports | Where DirectReports |
            Select-Object -Property CN,DirectReports
    }
    $temp
    $user = $temp.DirectReports
    $depth--
}

$output |
    Select-Object CN,@{Name='DirectReports';Expression={
       ($_.DirectReports -replace 'CN=|,OU=.*|,DC=.*|\\') -join '; '}} |
           Export-Csv output.csv -NoType

Explanation:

$depth would be the number of recursions you want to perform. Currently, $UserCN holds the CN value of an AD user object. An initial query for that user is done to store a value in $user that can be passed into the -Identity parameter. The collection of DirectReports is joined by ;, which you can change to whatever you want.

This currently does not output the Get-ADUser results for users who do not have a direct report. You can change that by removing the Where DirectReports.

Upvotes: 2

Related Questions