powershellrandomcommandinvoke

Randomly select command to execute?


Idea: I want to change the time randomly using set-date's three options, .AddHours(), .AddMinutes(), .AddSeconds(). My first thought was storing them in an array and referencing them randomly but it's not executing. It's just storing the string printing instead of executing it.

Code so far:

$test = "Set-Date -Date (Get-Date).AddHours($\(Get-Random -Maximum 25))", "Set-Date -Date (Get-Date).AddSeconds($\(Get-Random -Maximum 61))", "Set-Date -Date (Get-Date).AddMinutes($\(Get-Random -Maximum 61))"

Output:

$Test 
Set-Date -Date (Get-Date).AddHours(22)
Set-Date -Date (Get-Date).AddSeconds($\(Get-Random -Maximum 61))
Set-Date -Date (Get-Date).AddMinutes($\(Get-Random -Maximum 61))
$test[0]
Set-Date -Date (Get-Date).AddHours(22)
$(Get-Random -InputObject $test) 
Set-Date -Date (Get-Date).AddMinutes($\(Get-Random -Maximum 61))

If there is another way to do this, if you need further explanation, or if there are any other questions, feel free to ask :) THANK YOU!


Solution

  • You can use, invoke-expression/command.