2

Here is a simple command that I would like to use a variable in.

(Get-Date).AddDays(-30)

What I'm trying to do is substitute a variable $Time for the word Days.

$Time="Days" OR $Time="Hours"

Then run something like this:

(Get-Date).Add$Time(-30)

Is there a simple way to do this in 1 line?

Obviously I could write an If statement to do this but it seems like there should be a way to make this work in a single command.

zett42
  • 25,437
  • 3
  • 35
  • 72

1 Answers1

3

You had the right idea, except you need to use the method name 100% from a string or not as a string.

You can do what you seek like this.

$Time = "Days"
(Get-Date)."Add$Time"(-30)

Or

$Time = "AddDays"
(Get-Date).$Time(-30)
Sage Pourpre
  • 9,932
  • 3
  • 27
  • 39
  • 3
    Note: This works because the right side of the "." operator is considered an expression and evaluated as such. – Steven Jun 25 '22 at 13:59