How can I use a variable containing a date to act like get-date function in powershell? I have a variable $date containing 2016-09-08. I want to subtract one day from the $date. something like:
$date = "2016-09-08" $date.AddDays(-1)
It doesn't work.
1"2016-09-08" is a string. You need to convert it to a datetime object. There are several ways to do so but below is an example of passing a string to the Get-Date cmdlet.
$date = Get-Date "2016-09-08" $date.AddDays(-1).ToString("yyyy-MM-dd")
See Custom Date and Time Format Strings for more details on all of the available options.
1Single line conversion and subtraction.
(Get-Date $date).AddDays(-1)
0This thread really helped me a lot and here's what I was trying to do. Sharing so others can see more things you can do with Get-Date and AddDays.
PS C:\Users\zzz> (Get-Date $date).AddDays(0).ToString("MMddyyyy") 07162019 PS C:\Users\zzz> (Get-Date $date).AddDays(-1).ToString("MMddyyyy") 07152019
Expanding on Mani Live's answer ... to use in a regular batch file:
for /F "usebackq" %%d in (`powershell -STA -ExecutionPolicy ByPass -command "echo ((Get-Date).AddDays(-10)).ToString(\"yyyy-MM-dd\")"`) do set ten_days_ago=%%d
Your variable is String. run $date.gettype()
it will output string.
$date = "2016-09-08" $date.gettype() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True String System.Object
to be able to use datetime functions you need a datetime variable.
$date = get-date("2016-09-08") $date.gettype() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True True Datetime System.Object $date.adddays(-1) Wednesday, September 7, 2016 12:00:00 AM
then you can start using formatting of your choice.
You can also cast the string to a datetime
:
$date = [datetime]"2016-09-08"
Or assign the string to a strictly-typed datetime
variable:
[datetime]$date = "2016-09-08"
ncG1vNJzZmirpJawrLvVnqmfpJ%2Bse6S7zGiorp2jqbawutJoanJraGaAdoSOqaawnaKotaa4y2aqrpqkp66kwIxqZJ2ZqWKzs7vMZq2aqpmWr62xjJ2YrZ0%3D