jesper

jesper

  • NA
  • 89
  • 52.8k

Powershell, edit string to datetime

Jun 10 2020 3:36 PM
Hi,
 
I have this script that takes quser information and format it into an array. I have 1 problem i cant figure out. The IDLE TIME is in a decimal format E.G. 2.57 (HH.MM) but how do i make it a datetime, so i am able to sort on it ?
  1. $Servers = @(  
  2. "localhost"  
  3. )  
  4. #Initialize $Sessions which will contain all sessions  
  5. [System.Collections.ArrayList]$Sessions = New-Object System.Collections.ArrayList($null)  
  6. #Go through each server  
  7. Foreach ($Server in $Servers) {  
  8. #Get the current sessions on $Server and also format the output  
  9. $DirtyOuput = (quser /server:$Server) -replace '\s{2,}'',' | ConvertFrom-Csv  
  10. #Go through each session in $DirtyOuput  
  11. Foreach ($session in $DirtyOuput) {  
  12. #Initialize a temporary hash where we will store the data  
  13. $tmpHash = @{}  
  14. #Check if SESSIONNAME isn't like "console" and isn't like "rdp-tcp*"  
  15. If (($session.sessionname -notlike "console") -AND ($session.sessionname -notlike "rdp-tcp*")) {  
  16. #If the script is in here, the values are shifted and we need to match them correctly  
  17. $tmpHash = @{  
  18. Username = $session.USERNAME  
  19. SessionName = "" #Session name is empty in this case  
  20. ID = $session.SESSIONNAME  
  21. State = $session.ID  
  22. IdleTime = $session.STATE  
  23. LogonTime = $session."IDLE TIME"  
  24. ServerName = $Server  
  25. }  
  26. }Else {  
  27. #If the script is in here, it means that the values are correct  
  28. $tmpHash = @{  
  29. Username = $session.USERNAME  
  30. SessionName = $session.SESSIONNAME  
  31. ID = $session.ID  
  32. State = $session.STATE  
  33. IdleTime = $session."IDLE TIME"  
  34. LogonTime = $session."LOGON TIME"  
  35. ServerName = $Server  
  36. }  
  37. }  
  38. #Add the hash to $Sessions  
  39. $Sessions.Add((New-Object PSObject -Property $tmpHash)) | Out-Null  
  40. }  
  41. }  
  42. #Display the sessions, sort by name, and just show Username, ID and Server  
  43. $sessions | Sort Username | select Username, ID, ServerName, IdleTime | FT -AutoSize  

Answers (1)