Ok, I'll be the first to admit you might not find a production use for this tip, but that's what makes it fun. Interactively, you can always hit the up arrow to get the last command in your command buffer. But what if you are running a script and for some reason want to re-rerun the last command? Using Get-History we can get a listing of all the commands. This cmdlet has an alias of 'h'. To re-run any command we use Invoke-History and specify the id number. Invoke-History has an alias of 'r'.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
[cc lang="PowerShell"]
PS S:\> r 163
get-service spooler
Status Name DisplayName
------ ---- -----------
Running spooler Print Spooler
[/cc]
For the programmatic approach, we need to find the last id number in history. Here's how:
[cc lang="PowerShell"]
PS S:\> (get-history)[-1].id
167
[/cc]
The Get-History expression returns an array. Using [-1] returns the last item in the array and then I'm only asking for the ID property. See where this is going? To run the last command we can pass this value to Invoke-History. We could do this, because the ID parameter accepts pipeline binding by property name:
[cc lang="PowerShell"]
(get-history)[-1] | invoke-history
[/cc]
Or like this (using aliases to shorten the command for an interactive session):
[cc lang="PowerShell"]
r (h)[-1]
[/cc]
Finally, we might want to turn this into a quicky function:
[cc lang="PowerShell"]
function rlast {
Invoke-History (Get-History)[-1]
}
[/cc]
Not life-changing, I know. But perhaps you'll pick up a tidbit or two about how PowerShell works.
What’s wrong with teh old standby:
& $^ $$
Or
.
or
or
I think there are too many ways to do this.
Have a good weekend Jeff.
What’s wrong with using r? By default Invoke-History executes the last command if you don’t pass it a parameter.
–Greg
Absolutely nothing! This is one of those little gems that are so easy to overlook. It never crossed my mind to try Invoke-History without any parameters. Another great example of why you should read cmdlet help, even for cmdlets you *think* you know.