Wiktor
Wiktor

Reputation: 631

Powershell string not recognized as valid DateTime

I got a code to convert Date as below:

$DatePart = get-aduser -identity $AcountName -Properties * | Select-Object whenCreated
$DatePartSubs =$DatePart.whenCreated
$DatePartSubstring = $DatePartSubs.ToShortDateString()
$FinalDate = [datetime]::ParseExact($DatePartSubstring,'dd/MM/yyyy',$null)

But when i tried to format date i got below error

enter image description here

Where variable "$DatePartSubstring" equals :

enter image description here

What i did wrong and how to fix it ?

Upvotes: 2

Views: 3108

Answers (3)

Theo
Theo

Reputation: 61068

PowerShell conveniently maps quite a lot of LDAP attributes to more friendly names and on some of the attributes it converts them to more usable object types. Especially on attributes that we would like to use as DateTime objects and that are stored in AD as Generalized-Time strings like this comes in handy.

So in your case, I would do

$CreatedDate = Get-ADUser -Identity $AcountName -Properties Created | Select-Object -ExpandProperty Created

Below a table that shows you the most commonly used attributes on users and how PowerShell maps them:

Property Syntax R/RW LDAPDisplayName
AccountLockoutTime DateTime RW lockoutTime, converted to local time
AccountNotDelegated Boolean RW userAccountControl (bit mask 1048576)
AllowReversiblePasswordEncryption Boolean RW userAccountControl (bit mask 128)
BadLogonCount Int32 R badPwdCount
CannotChangePassword Boolean RW nTSecurityDescriptor
CanonicalName String R canonicalName
Certificates ADCollection RW userCertificate
ChangePasswordAtLogon Boolean W If pwdLastSet = 0
City String RW l
CN String R cn
Company String RW company
Country String RW c (2 character abbreviation)
Created DateTime R whenCreated
Deleted Boolean R isDeleted
Department String RW department
Description String RW description
DisplayName String RW displayName
DistinguishedName String (DN) R distinguishedName
Division String RW division
DoesNotRequirePreAuth Boolean RW userAccountControl (bit mask 4194304)
EmailAddress String RW mail
EmployeeID String RW employeeID
EmployeeNumber String RW employeeNumber
Enabled Boolean RW userAccountControl (bit mask not 2)
Fax String RW facsimileTelephoneNumber
GivenName String RW givenName
HomeDirectory String RW homeDirectory
HomedirRequired Boolean RW userAccountControl (bit mask 8)
HomeDrive String RW homeDrive
HomePage String RW wWWHomePage
HomePhone String RW homePhone
Initials String RW initials
LastBadPasswordAttempt DateTime R badPasswordTime, converted to local time
LastKnownParent String (DN) R lastKnownParent
LastLogonDate DateTime R lastLogonTimeStamp, converted to local time
LockedOut Boolean RW msDS-User-Account-Control-Computed (bit mask 16)
LogonWorkstations String RW userWorkstations
Manager String (DN) RW manager
MemberOf ADCollection R memberOf
MNSLogonAccount Boolean RW userAccountControl (bit mask 131072)
MobilePhone String RW mobile
Modified DateTime R whenChanged
Name String R cn (Relative Distinguished Name)
ObjectCategory String R objectCategory
ObjectClass String R objectClass, most specific value
ObjectGUID Guid R objectGUID converted to string
Office String RW physicalDeliveryOfficeName
OfficePhone String RW telephoneNumber
Organization String RW o
OtherName String RW middleName
PasswordExpired Boolean RW msDS-User-Account-Control-Computed (bit mask 8388608) (see Note 1)
PasswordLastSet DateTime RW pwdLastSet, local time
PasswordNeverExpires Boolean RW userAccountControl (bit mask 65536)
PasswordNotRequired Boolean RW userAccountControl (bit mask 32)
POBox String RW postOfficeBox
PostalCode String RW postalCode
PrimaryGroup String R Group with primaryGroupToken
ProfilePath String RW profilePath
ProtectedFromAccidentalDeletion Boolean RW nTSecurityDescriptor
SamAccountName String RW sAMAccountName
ScriptPath String RW scriptPath
ServicePrincipalNames ADCollection RW servicePrincipalName
SID Sid R objectSID converted to string
SIDHistory ADCollection R sIDHistory
SmartcardLogonRequired Boolean RW userAccountControl (bit mask 262144)
State String RW st
StreetAddress String RW streetAddress
Surname String RW sn
Title String RW title
TrustedForDelegation Boolean RW userAccountControl (bit mask 524288)
TrustedToAuthForDelegation Boolean RW userAccountControl (bit mask 16777216)
UseDESKeyOnly Boolean RW userAccountControl (bit mask 2097152)
UserPrincipalName String RW userPrincipalName

Get-ADUser by default returns objects with these properties: DistinguishedName, Enabled, GivenName, Name, ObjectClass, ObjectGUID, SamAccountName, SID, Surname, UserPrincipalName. If you want more, then you need to specify the extra's with the -Properties parameter. Best not use -Properties *

Upvotes: 1

Clint Oliveira
Clint Oliveira

Reputation: 702

Try this out it converts the date to the required format:

[datetime]$DatePartSubstring = "2019-06-13"
$FinalDate = $DatePartSubstring.ToString("dd/mm/yyy")
Write-Host $FinalDate -ForegroundColor Green

enter image description here

Upvotes: 3

Walter Mitty
Walter Mitty

Reputation: 18940

It looks like you are trying to get the date part, without the time, as a date-time object, where the time has been set to midnight. Converting to a sting and back again is the long way around. You might be better off to do the following:

$DatePart = get-aduser -identity $AcountName -Properties * | Select-Object whenCreated
$FinalDate = $DatePart.whencreated.Date

This should set final date to midnight of the day in question. Note, however, that if you attempt to display $FinalDate on the console, Powershell will implicitly convert it to a string before displaying it. In order to find out what it really is, do

$FinalDate.GetType()

Upvotes: 1

Related Questions