且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

相当于 PowerShell 中的 Unix 时间命令?

更新时间:2022-01-25 04:59:54

我使用了 System.Diagnostics.ProcessGetProcessTimes 提供的时间来想出一个time 的实现:

I used both the times provided by System.Diagnostics.Process and GetProcessTimes to come up with an implementation for time:

$source=@'

using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

public class Timer
    {
        [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public static extern bool GetProcessTimes(IntPtr handle, out long creation, out long exit, out long kernel,
                                                  out long user);

        public static void Time(string file,string args)
        {
            long user,kernel,exit,creation;
            Process proc = null;
            proc = Process.Start(file,args);
            proc.WaitForExit();
            GetProcessTimes(proc.Handle, out creation, out exit, out kernel, out user);
            long real = exit - creation;
            Console.WriteLine("real {0}\nuser {1}\nsys {2}", real / 10000000.0, user/10000000.0,kernel/10000000.0);
        }
    }
'@

Add-Type -TypeDefinition $source -Language CSharpVersion3

function time ($scriptblock) {

    $file = "powershell";
    $args = $scriptblock;

    $startInfo = new-object Diagnostics.ProcessStartInfo;
    $startInfo.FileName = $file;
    $startInfo.Arguments = $args;
    $startInfo.CreateNoWindow = $true;
    $startInfo.UseShellExecute = $false;
    $startInfo.RedirectStandardOutput = $true;
    $process = [Diagnostics.Process]::Start($startInfo);
    $process.WaitForExit();
    write-host $process.StandardOutput.ReadToEnd();
    write-host real: ($process.ExitTime - $process.StartTime)
    write-host user: $process.UserProcessorTime;
    write-host sys:  $process.PrivilegedProcessorTime;
    write-host using GetProcessTimes
    [Timer]::Time($file,$args)
}

time {sleep 10}

它并不完美,因为我正在创建一个 powershell 进程并在其中运行命令,因此实时时间大约为 11 秒(对于 sleep 10 ).我会看看我是否可以为此实现一个 cmdlet 或其他东西.

It isn't really perfect as the real time comes out as about 11 seconds ( for sleep 10 ) since I am creating a powershell process and running the command in that. I will see if I can implement a cmdlet or something for this.