[英]Powershell Subtract 1 day from variable date
How can I use a variable containing a date to act like get-date function in powershell? 如何在Powershell中使用包含日期的变量来充当get-date函数? I have a variable $date containing 2016-09-08.
我有一个包含2016-09-08的变量$ date。 I want to subtract one day from the $date.
我想从$ date减去一天。 something like:
就像是:
$date = "2016-09-08"
$date.AddDays(-1)
It doesn't work. 没用
"2016-09-08" is a string. “ 2016-09-08”是一个字符串。 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.
有几种方法可以这样做,但是下面是将字符串传递到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. 有关所有可用选项的更多详细信息,请参见自定义日期和时间格式字符串 。
单行转换和减法。
(Get-Date $date).AddDays(-1)
Your variable is String. 您的变量是String。 run
$date.gettype()
it will output string. 运行
$date.gettype()
它将输出字符串。
$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. 那么您就可以开始使用自己选择的格式了。
扩展Mani Live的答案...以在常规批处理文件中使用:
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
This 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.
共享,以便其他人可以看到您可以使用Get-Date和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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.