Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get-History inside a powershell script file

Tags:

powershell

I want to know the last executed command inside of my powershell script file.

For example my script file looks like

echo "hello"
$x=(Get-History)[-1]
echo $x

In real I am having a much larger script file

This should output me " echo 'hello' ". But it outputs me the last command executed in powershell terminal.

Is there a way to get last executed command inside a powershell script file. I actully want to use the StartExecutionTime property of the history.

like image 939
Debesh Mohanty Avatar asked Jul 20 '26 13:07

Debesh Mohanty


1 Answers

PowerShell does not natively support this, but if you need to trace out a number of commands to see which is the slowest in a script, you could use a construct like this one:

$commands = @(
    'write-host 123',
    'write-host 234',
    'set-location c:\git',
    'write-host 123',
    'set-location c:\temp'    
)

forEach ($c in $commands){
    $stopWatch = Measure-command -Expression {Invoke-Expression $c}
    Write-host "The last command [$c] was executed in [$($stopWatch.TotalMilliseconds)]"
}

This will execute all of commands within the array $commands one by one and run Measure-Command on them, which returns a rich TimeSpan object that has the TotalMilliseconds field you were looking to use. Outputs like this:

The last command [write-host 123] was executed in [2.3979]
The last command [write-host 234] was executed in [0.031]
The last command [set-location c:\git] was executed in [0.0236]
The last command [write-host 123] was executed in [0.021]
The last command [set-location c:\temp] was executed in [0.0171]

The snippet of code could be modified to work with a script too, so if we imagine we had a script like this:

#myCoolScript.ps1
write-host 123
start-sleep -Seconds 2
write-host 234
start-sleep -Seconds 1
set-location c:\git
write-host 123
set-location c:\temp    

You could modify the code like so to measure out each line:


$commands = get-content .\MyCoolScript.ps1
forEach ($c in $commands){
    $stopWatch = Measure-command -Expression {invoke-expression $c}
    Write-host "The last command [$c] was executed in [$($stopWatch.TotalMilliseconds)]"
}

Which would give this output:

The last command [write-host 123] was executed in [10.1866]
The last command [start-sleep -Seconds 2] was executed in [2000.178]
The last command [write-host 234] was executed in [1.1301]
The last command [start-sleep -Seconds 1] was executed in [999.5883]
The last command [set-location c:\git] was executed in [0.5302]
The last command [write-host 123] was executed in [0.9388]
The last command [set-location c:\temp    ] was executed in [0.3985]
like image 172
FoxDeploy Avatar answered Jul 23 '26 21:07

FoxDeploy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!