data-bite
data-bite

Reputation: 417

Powershell Current time minus n seconds in specific format

I am looking to store value of current system time - 30 seconds in the format [yy.mm.dd hh:mm:ss] in a variable. This is a specific requirement as the log file i am working on has this format. Currently i have below code which allows me to store current system time in required format but unable to subtract 30 seconds.

$dateTime = Get-Date -f "[yy.MM.dd HH:mm:ss]"
$("Current time: " + $dateTime)
$("Current time - 30 second: " + $dateTime.AddSeconds(-31))

The line $("Current time - 30 second: " + $dateTime.AddSeconds(-31)) from above code throws below error

Method invocation failed because [System.String] does not contain a method named 'AddMinutes'.
At C:\Users\foo\log_mont.ps1:4 char:3
+ $("Current time - 30 second: " + $dateTime.AddSeconds(-31))
+   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : MethodNotFound

Upvotes: 5

Views: 17270

Answers (2)

user6811411
user6811411

Reputation:

If you don't have (direct) control over the the date time to subtract 30 seconds from you can use [datetime]::ParseExact() to convert the string to a [datetime] type you can subtract from and convert to string again.
(What only makes sense including seconds, what you did in your last edit)

$dtformat = "\[yy.MM.dd HH:mm:ss\]"
$dateTime = Get-Date -f $dtformat
$dateTime
[datetime]::ParseExact($datetime,$dtformat,$Null).AddSeconds(-30).ToString($dtformat)

Sample output:

[18.07.16 14:49:22]
[18.07.16 14:48:52]

Upvotes: 2

boxdog
boxdog

Reputation: 8432

Try this:

$dateTime = (Get-Date).AddSeconds(-31).ToString("[yy.MM.dd HH:mm]")

Note that this, and your original example, are not storing the date in this format. They are creating a string representation of the date. This is why you can't add seconds to it. If you want to manipulate the date later in your script, store it as a DateTime and only use the formatting when you need to output it. For example:

$dateTime = (Get-Date).AddSeconds(-31)

# other code - maybe some date manipulation

$dateTime.ToString("[yy.MM.dd HH:mm]")

Upvotes: 10

Related Questions