PowerShell: How to Check if String Contains a Date


You can use the following syntax in PowerShell to check if a string contains a date:

[boolean]($my_string -as [DateTime])

This particular example checks if the string variable named $my_string contains a date and returns either True or False as a result.

Here is how this syntax works:

First, we attempt to convert the string variable named $my_string to a DateTime object.

We then use the [boolean] command to force the output to be True if the string was able to be successfully convert to a date or False otherwise.

The following example shows how to use this syntax in practice in several different scenarios.

Example: Check if String Contains a Date in PowerShell

Suppose we create several strings named $string1, $string2 and $string3 in PowerShell:

$string1 = "July 4, 2024"
$string2 = "7/4/2024"
$string3 = "Zach"

We can use the following syntax to check if each of these strings contains a date or not:

[boolean]($string1 -as [DateTime])
[boolean]($string2 -as [DateTime])
[boolean]($string3 -as [DateTime])

The following screenshot shows how to use this syntax in practice:

PowerShell check if string contains date

From the output we can see:

  • The string “July 4, 2024” returns True because it contains a date.
  • The string “7/4/2024” returns True because it contains a date.
  • The string “Zach” returns False because it does not contain a date.

Note: You can find the complete documentation for the -as operator in PowerShell here.

Related Tutorials

The following tutorials explain how to perform other common tasks in PowerShell:

PowerShell: How to Check if String Contains Any Letters
PowerShell: How to Check if String Starts with Specific Value
PowerShell: How to Check if String Ends with Specific Value
PowerShell: How to Check if String Exists in List of Strings

Leave a Reply