Powershell – how to fetch details from multiple domain

active-directorypowershell

I am trying to create AD report in html via powershell but unable to fetch details from multiple domain,

below is my code,

# HTML Style
$a = "<style>"
$a = $a + "BODY{background-color:SkyBlue;font-family: calibri; font-size: 10pt;}"
$a = $a + "TABLE{border-width: 1px;border-style: solid;border-color: grey;border-collapse: collapse;}"
$a = $a + "TH{border-width: 1px;padding: 5px;border-style: solid;border-color: black;}"
$a = $a + "TD{border-width: 1px;padding: 5px;border-style: solid;border-color: black;}"
$a = $a + "</style>"


# Query Range
$dt = (get-date).adddays(-3)

# Domain Selection
$Domains = 'test1.test.com' , 'test2.testuat.com'

ForEach ($domain in $Domains) {

$report += get-aduser -Server $domain -filter 'whencreated -ge $dt' -Properties * | 

# Attributes selection
select whenCreated,
SamAccountName,
GivenName,
Surname,
DisplayName,
Description,
EmployeeID,
mail,
Office,
City,
Title,
Department,
Company,
ScriptPath,
@{name=”MemberOf”;expression={$_.memberof -join “;”}}
}
$report | convertto-html -head $a | Out-File C:\scripts\ad.html
Invoke-Expression C:\scripts\ad.html

Best Answer

Everytime this pipeline is executed:

convertto-html -head $a | Out-File C:\scripts\ad.html

you generate a whole new html document and the file (C:\scripts\ad.html) is being overwritten.

Replace the foreach(){} loop with the ForEach-Object cmdlet and move the |ConvertTo-Html |Out-File commands outside the loop:

$Domains |ForEach-Object {
  $Domain = $_
  Get-ADUser -Server $domain -Filter {whencreated -ge $dt} -Properties * | Select-Object whenCreated # and so on.
} |ConvertTo-Html -Head $a |Out-File C:\scripts\ad.html