My Friends,
I have an excerpt here from a script that works very well.
Now I would like to change it but I cannot figure out how to improve it.
After getting some users into a variable, this is what is in the variable:
SamAccountName ExpirDate SamX
Joe.Reynolds 02/20/2022 Joe.ReynoldsX
Mac.Channell 02/20/2022 Mac.ChannellX
George.Frimpong 10/28/2022 George.FrimpongX
Hans.Kunbargi 11/26/2022 Hans.KunbargiX
Elmer.Mark.Martin 12/10/2022 Elmer.Mark.Martinx
AFrazier 01/27/2023 AFrazierX
Susan.Soremekun 02/09/2023 Susan.SoremekunX
Bill.Cunningham 02/09/2023 Bill.CunninghamX
And here is the excerpt of the script that works just fine:
$getUsers = @{
Filter = "*"
SearchBase = $SEARCHBASE
Properties = "SamAccountName","AccountExpirationDate","description" , "DisplayName" , "extensionattribute3"
}
$Users = Get-ADUser @getUsers
# store queried objects in $Expired
$Expired =
$Users |
where-object {
$_.AccountExpirationDate -notlike '' -and
$_.AccountExpirationDate -lt $Tomorrow -and
$_.extensionattribute3 -match $ParticularUSMCAgency
} |
select-object SamAccountName, @{n="ExpirDate";e={get-date $_.AccountExpirationDate -Format "MM/dd/yyyy"}}, @{n="SamX";e={$_.SamAccountName + "X"}} |
Sort-object @{Expression = {$_."Expirdate" -as [datetime]}}, Samx
# display $Expired in table format
$Expired | Format-table -AutoSize
# output $Expired to CSV
$Expired |
Export-Csv $TimeStampx -NoTypeInformation
Now I want to refine the sort by testing each SamAccountName and putting the results in SamX - Then Sort by SamX
So I thought I would Isolate the Varible and loop through all the objects and change SamX. - Then Sort by SamX
I don’t know how to isolate the variable with all the objects and change all the values of SamX and write a new Varible.
Testing the SamAccountName is long, but all it does is separate SamAccountNames like this:
First.Last
First.Middle.Last
Last
Here it is:
{
$Split1 = $_.SamAccountName.Split(".")[0]
$Split2 = $_.SamAccountName.Split(".")[1]
$Split3 = $_.SamAccountName.Split(".")[2]
$Periodcount = 0
$PeriodCount = ($_.SamAccountName.ToCharArray() | Where-Object {$_ -eq '.'} | Measure-Object).Count
If ($PeriodCount -eq 0)
{
$_.SamX = "Z." + $_.SamAccountName
}
ElseIF
($PeriodCount -eq 1)
{
$_.Samx = $_.SamAccountName
}
ElseIF
($PeriodCount -eq 2)
{
$_.Samx = $Split1 + "." + $Split3
}
}
Surely this can be done. How can a variable with a collection of objects be isolated, each one be updated and written to and passed on to Sort ? I do not care if a new Variable/Collection must be created, but then, it needs to be Sorted.
Thanks in advance for your help on this. I have spent days on this problem.