Cmdlet在ISE中的运行速度比控制台快得多

时间:2018-01-31 17:22:16

标签: powershell

我开发了一个Powershell Cmdlet和一个驱动它的脚本。我发现Cmdlet的功能在Powershell ISE中运行得非常快,并且还通过命令行调用的包装器EXE(比如2分钟)运行。但是,如果我通过powershell.exe -File在CMD中调用脚本,则相同的操作需要6-7分钟。

脚本基本上通过System.Reflection.Assembly.LoadFile加载一些DLL,通过Add-Type加载一个完整的配置信息类型,然后调用自定义Cmdlet(一次不在循环中)。 Cmdlet功能涉及大量数据库访问,网络存储访问和处理。我无法发布任何类型的源代码。

我发现在ISE和命令行中,ApartmentState都是STA,主机版本(Major,Minor,Build,Revision)是(3,0,-1,-1)。

我的问题是:有哪些进一步的检查可以确定执行时间差异的原因?

1 个答案:

答案 0 :(得分:1)

  

我的问题是:有哪些进一步的检查可以确定执行时间差异的原因?

您是否考虑过现有的调试选项?

您可以在战略位置打包几个WriteVerbose()语句:

using System;
using System.Management.Automation;
using System.Diagnostics;

class DoDatabaseStuffCommand : PSCmdlet
{
    private Stopwatch stopWatch;

    //
    // ... parameter definitions go here
    //

    protected override void BeginProcessing()
    {
        stopWatch = Stopwatch.StartNew();
        // load whatever you need 
        this.WriteVerbose(String.Format("Loading dependencies: {0}s", stopWatch.Elapsed.TotalSeconds));
    }

    protected override void ProcessRecord()
    {
        this.WriteVerbose(String.Format("Processing item at {0}s", stopWatch.Elapsed.TotalSeconds));
        // process input 
        this.WriteVerbose(String.Format("Done processing item at {0}s", stopWatch.Elapsed.TotalSeconds));
    }

    protected override void EndProcessing()
    {
        this.WriteVerbose(String.Format("Starting cleanup at {0}s", stopWatch.Elapsed.TotalSeconds));
        // clean up
        this.WriteVerbose(String.Format("Done cleaning up at {0}s", stopWatch.Elapsed.TotalSeconds));
        stopWatch.Stop();
    }
}

在调用脚本中,您可以改为使用Write-Verbose

$stopwatch = [System.Diagnostics.StopWatch]::StartNew()
foreach($assembly in $assemblies){
    Add-Type -Path $assembly
    Write-Verbose "Done loading $assembly after $($stopwatch.Elapsed.TotalSeconds)s"
}
# and so on

使用-Verbose执行以查看正在进行的操作:

powershell.exe -File "\path\to\script.ps1" -Verbose
相关问题