How to assign Date variable in PowerShell

You can set a DateTime value to a variable by using the Get-Date cmdlet and we can also convert a date string to a DateTime object using simple DateTime casting.

This assigns the current date time value to the variable $a.

$a = Get-Date

Use the below script if you want to get a date object from a specific date time value.

$a = Get-Date "07/06/2022 05:00 AM"

You can also achieve this by using simple DateTime casting.

$a = [DateTime] "07/06/2022 05:00 AM"

The Get-Date uses the local computer’s culture settings (date time format) to parse the string input. To view your computer’s settings, use (Get-Culture).DateTimeFormat.

You will get the following error message if you provide the input date string in a different date-time format.

$a = Get-Date “17/06/2022 05:00 AM”
Get-Date: Cannot bind parameter ‘Date’. Cannot convert value “17/06/2022 05:00 AM” to type “System.DateTime”. Error: “String was not recognized as a valid DateTime.”

To overcome this problem, provide the input date string in local date time format or provide the date components (Year, Month, and Day) as individual parameters.

$a =(Get-Date -Year 2022 -Month 6 -Day 17)

Use the following command to get the datetime object for the last date which is N days before the current date.

#Get the date of the day in 30 days before the current date
$Days = 30;
$time = (Get-Date).Adddays(-($Days))

The below command returns the date object for the future date which comes in 7 days after the current date.

#Get the date of the day in 7 days after the current date
$Days = 7;
$time = (Get-Date).Adddays($Days)
Advertisement

3 thoughts on “How to assign Date variable in PowerShell”

  1. Found this really helpful as I have been trying to find a way to get this done all morning and lots of googling.
    Many of the threads refer to [datetime] casting but I found none of them work.
    Problem appears to be that this works if you are using US datetime format (mm/dd/yyy)
    Just using $a = Get-Date “… seems to work and recognizes our local time format.

    Reply
  2. Does this depend on the locale? Only in UK we have DD/MM/YYYY … US is MM/DD/YYYY, Japan AFAIK is YYYY/MM/DD.. And some places don’t use slashes.

    Reply

Leave a Comment