Call a .NET method with part of the method name replaced by a variable

111 views Asked by At

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.

1

There are 1 answers

1
Sage Pourpre On

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)