O'Reilly logo

Windows PowerShell Cookbook, 3rd Edition by Lee Holmes

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 8. Utility Tasks

Introduction

When you are scripting or just using the interactive shell, a handful of needs arise that are simple but useful: measuring commands, getting random numbers, and more.

Get the System Date and Time

Problem

You want to get the system date.

Solution

To get the system date, run the command Get-Date.

Discussion

The Get-Date command generates rich object-based output, so you can use its result for many date-related tasks. For example, to determine the current day of the week:

PS > $date = Get-Date
PS > $date.DayOfWeek
Sunday

If you want to format the date for output (for example, as a logfile stamp), see Format a Date for Output.

For more information about the Get-Date cmdlet, type Get-Help Get-Date.

For more information about working with classes from the .NET Framework, see Work with .NET Objects.

Measure the Duration of a Command

Problem

You want to know how long a command takes to execute.

Solution

To measure the duration of a command, use the Measure-Command cmdlet:

PS > Measure-Command { Start-Sleep -Milliseconds 337 }

Days              : 0
Hours             : 0
Minutes           : 0
Seconds           : 0
Milliseconds      : 339
Ticks             : 3392297
TotalDays         : 3.92626967592593E-06
TotalHours        : 9.42304722222222E-05
TotalMinutes      : 0.00565382833333333
TotalSeconds      : 0.3392297
TotalMilliseconds : 339.2297

Discussion

In interactive use, it is common to want to measure the duration of a command. An example of this might be running a performance benchmark on an application ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required