I am writing a basic function that should show the output older than or newer than X days
If I would like to parse as parameter Newer or Older, and in the end, it the same query just switching the operator from -lt or -gt.
Do I need to write two lines of code or would be a way to parameterized the comparison operator?
$vms | ? { $_.created -lt (get-date).AddDays(-$($daysback))} for something like
When you store a group of characters like -lt in a variable, PowerShell interprets it as a string and stores it as that type (see Type of Variables). When you expand that variable, it is expanded as a string, so when you try to include it as part of a command it will be interpreted as a string and not as an operator. For instance, if you wanted to do something like this:
However, you can use Invoke-Expression to execute a string stored in a variable as a command. So, what you can do is assemble your command as a string with the contents of your other variables and then execute the entire command with Invoke-Expression, like this:
Warning
Be sure to read the Caution message on the Invoke-Expression documentation page. You should validate the parameter input that you accept for this function to prevent a user from inserting arbitrary code.
For this function, you should cast $daysback to the integer type so that it will only accept numbers as inputs, and for the newer/older option you could simply use a switch parameter. That would look something like this:
With this setup, if you include the parameter -Newer when you call the function then it will use -gt, and if you do not include -Newer then it will default to -lt.
Yes, I just wanted to avoid typing two times the same command one for -lt and the same for -gt, and I was wondering if there would be an efficient way to do it.
Thanks, @grokkit for the detailed explanations and remarks. So even if in the end by using invoke-command is possible to achieve what I was asking for, It doesn’t seem to help in being a more efficient solution, so I will go for the approach of using “if” and typing the command twice.
we can eliminate the step of assigning the string to the $command variable and just execute it directly. However, we still need the if statement, so it doesn’t seem particularly more efficient than just writing the command out twice like this:
This should be more efficient, though it does require the user to specify an operator. The inputs for $Operator are limited by ValidateSet to prevent arbitrary strings from being executed; if not specified, it will default to lt.
This also makes the function more flexible, as you could get output for a specific day with eq.