-1

I have a bunch os functions in a PowerShell script binded to an alias, as:

function Run
{
    # somethin that takes a while
}

set-alias r Run

I would like to measure the time of each call. To do that, I would like to use another function that creates a .NET Stopwatch, starts it, runs the specified action, stops the Stopwatch and prints out the time, as:

function Crono($action)
{
$sw = [Diagnostics.Stopwatch]::StartNew()

    & $action

$sw.Stop()
Write-Host "> Operation done in: " + $sw.Elapsed;
}

set-alias r Crono(Run)

But this alias throws the following error:

Set-Alias : A positional parameter cannot be found that accepts argument 'System.Object[]'. At ...\script.ps1:85 char:10 + set-alias <<<< r Crono(Run) + CategoryInfo : InvalidArgument: (:) [Set-Alias], ParameterBindingException + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.SetAliasCommand

Is it possible to do that? Is there any other way?

Thanks.

Edit:

Thank you all for the replies, with the feedback received I created the following:

function CronoRun()
{
    Crono(Run);
}
set-alias r **CronoRun**

But now, if the Run function is calling a .bat file it throws some exceptions because is trying to "interpreet" whats going on in the script, probably related to how the Run method is exeuted inside the Crono one. Any idea?

4

3 回答 3

3

您可以使用“Measure-Command”cmdlet 测量表达式、脚本块和 cmdlet 所花费的时间。

您还可以检查历史项目的 *ExecutionTime 属性:

PS> Get-History -Count 1 | fl *

Id                 : 31
CommandLine        : Get-History -Count 1
ExecutionStatus    : Completed
StartExecutionTime : 3/13/2013 2:50:11 PM
EndExecutionTime   : 3/13/2013 2:50:11 PM
于 2013-03-13T12:51:20.660 回答
2

get-help set-alias

*这些命令展示了如何将别名分配给带有参数的命令,甚至是许多命令的管道。您可以为 cmdlet 创建别名,但不能为包含 cmdlet 及其参数的命令创建别名。但是,如果将命令放在函数或脚本中,则可以创建有用的函数或脚本名称,并且可以为函数或脚本创建一个或多个别名。在此示例中,用户想要为命令“set-location c:\windows\system32”创建别名,其中“set-location”是一个 cmdlet,“C:\Windows\System32”是 Path 的值范围。为此,第一个命令创建一个名为“CD32”的函数,其中包含 Set-Location 命令。第二个命令为 CD32 函数创建别名“go”。然后,

 PS C:\> function CD32 {set-location c:\windows\system32}
 PS C:\>set-alias go cd32*
于 2013-03-13T12:31:41.767 回答
1

您只能对不带参数的命令进行别名。因此,您必须创建一个虚拟函数来调用该函数并为其命名Chrono(Run)

于 2013-03-13T12:35:15.133 回答