0

I want to sort A-Z based on Name attribute. After I want to convert HTML table via | ConvertTo-Html -Fragment -As Table for object variable. How can I do that ?

thanks,

Script :

$cutoff = (get-date).AddDays(-200)

    $Objects = Get-ADUser -Filter {LastLogonDate -lt $cutoff -and Enabled -eq $True} -SearchBase 'DC=contoso,DC=com' -SearchScope Subtree -Properties 'SamAccountName' , 'Name'
    foreach ($_ in $Objects) {
       
        $LogonDate =  (Get-RealLogonDate -sAMAccountName $_.SamAccountName -Domain contoso.com).DateTime
        $Object = [ordered] @{
            DisplayName       = $_.Name
            LastLogon         = $LogonDate
    
        }
    
        [PSCUstomObject] $Object
    }
Arbelac
  • 1,698
  • 6
  • 37
  • 90
  • 1
    Change `foreach ($_ in $Objects)` into `$Objects | ForEach-Object`. `$_` is an [Automatic variable](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_automatic_variables?view=powershell-7.2#_) and cannot be used like that. To sort on the Name property, append `| Sort-Object Name` at the very end – Theo Apr 02 '23 at 10:43
  • 2
    Sorry, Since you created property `DisplayName` the sorting should be `| Sort-Object DisplayName`. P.S. You could emit the object easier using `PsCustomObject]@{ ... }`. Like that, the order of things is always kept – Theo Apr 02 '23 at 10:51

1 Answers1

0
$cutoff = (Get-Date).AddDays(-200)
$Objects = Get-ADUser -Filter { LastLogonDate -lt $cutoff -and Enabled -eq $True } -SearchBase 'DC=contoso,DC=com' -SearchScope Subtree -Properties 'SamAccountName' , 'Name'

$objlist = @() ## this stores all output

## change1
foreach ($obj in $Objects) {
   
    $LogonDate = (Get-RealLogonDate -sAMAccountName $_.SamAccountName -Domain contoso.com).DateTime
    $objlist += [ordered] @{
        DisplayName = $obj.Name  ## change2
        LastLogon   = $LogonDate
    }
}

$objlist| sort-object -property Displayname | ConvertTo-Html
TheGameiswar
  • 27,855
  • 8
  • 56
  • 94
  • 3
    Try to [avoid using the increase assignment operator (`+=`) to create a collection](https://stackoverflow.com/a/60708579/1701026) as might become pretty expensive. – iRon Apr 02 '23 at 12:57