1

Currently having a really really hard time with something that looks very easy to fix but for some reason just doesnt work. I have an Excel file with a column called "Date" with uh...dates in it with the following format; 21-3-2021. All I want is to use these dates to set an AD account Expiration date.

So this is what I did:

import-CSV ".\Example.csv" | % {

$User = $._username
$ExpirationDate = [datetime]::Parse($_.Date).ToString('dd/MM/yyyy')

if ($_.Date -ne '') {
Set-ADAccountExpiration $User $ExpirationDate
}
else {
Clear-ADAccountExpiration $user
}

Exception calling "Parse" with "1" argument(s): "String was not recognized as a valid DateTime."

Please, if someone can tell me what I am doing wrong I would be really happy. This is driving me nuts!

Kamahl
  • 13
  • 2

1 Answers1

4

The single-argument [datetime]::Parse() overload - e.g.,
[datetime]::Parse('21-3-2021') - implicitly uses the date/time formats of the current culture[1], as reflected in $PSCulture and Get-Culture, and it seems that that current culture in effect for you doesn't recognize a date string such as '21-3-2021'.

A simple solution is to explicitly specify a culture in which such a date format is valid and pass that culture as the second argument:

# The German culture supports such a format.
# Sample output is from my en-US (US English system).
PS> [datetime]::Parse('21-3-2021', [cultureinfo] 'de-DE')

Sunday, March 21, 2021 12:00:00 AM


If you had a truly exotic format not recognized by any of the predefined cultures (which isn't the case here), you could use the [datetime]::ParseExact() method:

PS> [datetime]::ParseExact('21-3-2021', 'd\-M\-yyyy', [cultureinfo]::InvariantCulture)

Sunday, March 21, 2021 12:00:00 AM

Note:

  • The - instances are \-escaped to ensure that they are matched verbatim in the input; by default, they are treated as abstract placeholders for any of the date-component separators supported by the target culture.

  • The specific culture context passed as the 3rd argument - the invariant culture here - would only matter if the input string contained abstract placeholders and/or culture-specific month names, such as "März" for March; you can pass $null to use the current culture.


[1] Note that if you cast a string to a type in PowerShell - e.g., [datetime] '1/13' - the invariant culture is always used for parsing; in other words: [datetime] '1/13' is equivalent to:
[datetime]::Parse('1/13', [cultureinfo]::InvariantCulture).
The invariant culture is derived from the US-English culture and is designed to be both independent of the current culture and to be stable over time, which makes it suitable for programmatic use - see this answer for more.

mklement0
  • 382,024
  • 64
  • 607
  • 775