Link to home
Start Free TrialLog in
Avatar of SAM2009
SAM2009Flag for Canada

asked on

In PowerShell, how to convert to date a value in hash table

Hi,

I need to compare date but I don't know how to convert date from hash table likeUsersDate = @{}

Example:

$UsersDate = @{}
....
Where-Object {( get-date($UsersDate[$_.UPN].Date)) -lt $Date}


How can I do that?
Avatar of J0rtIT
J0rtIT
Flag of Venezuela, Bolivarian Republic of image

Any example of a value? and could you please add or rephrase your question?
Also,  could you use the code tags to separate code from text?

 likeUsersDate = @{} ? (any $ missing? or spaces?)
I don't even understand what you're trying to do here, what is your end goal please and we'll help you out :-)

Is this part of a bigger script? Because you're using a UPN wildcard so I assume you're trying to get something about AD users?
ASKER CERTIFIED SOLUTION
Avatar of oBdA
oBdA

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
You value can be all sorts of data types (so can your key), it doesn't just have to be a string. You could put in an array, a single object, a text string, integer, another hash table, and so on. I wouldn't be storing the date as a string if you can help it, I would be storing it as a date object from the outset at least in PowerShell.

I could be wrong but you're working with AD data? I'm assuming this because I'm guessing you're pairing up UPN to lastLogonDate or something similar with a date? If so I think you're going about this backwards. You would be better served building your data set from LDAP filters discarding anything that does not match. For example, if you want users with a date less than another date, do it during the LDAP search. Otherwise you're creating a whole bunch of unnecessary processing.

Another issue is I would argue a hash table is not fit for purpose for the type of evaluation I think you're doing. You might as well just work with an array. Hash tables are best for key/value lookups where they will be super fast vs. filtering through key values which will be very slow.. But it can be done.

$Date = (Get-Date).Date.AddDays(-5)
UsersDate = @{}
Get-ADUser -Filter * -Properties lastLogonDate | ForEach-Object {
   UsersDate.Add($_.userPrincipalName,$lastLogonDate)
}
ForEach ($UPN in $UsersDate.Keys){
   if ($UsersDate.Item($UPN) -lt $Date){
      $UPN
   }
}

Open in new window


Where you're sourcing the data from would be very helpful. If I were to do this via AD directly, I would just do.

$Date = (Get-Date).Date.AddDays(-5)
Get-ADUser -Filter {lastLogonDate -le $Date} -Properties lastLogonDate | Select-Object userPrincipalName, lastLogonDate

Open in new window

Avatar of SAM2009

ASKER

Thanks that clear enough!