Tuesday, September 27, 2016

How do you get date and time information using PowerShell?

PowerShell has a cmdlet for most of the usual things including date and time.

The basic cmdlet to get the current date and time is Get-Date.

Start Windows PowerShell by typing powershell in the search box (Windows 10).


PowershellSearch.png

Click Windows PowerShell ISE to open the window shown.


PowershelSE.png

Enter Get-Date in the top pane and click the right pointing arrow to run the script.



PowersheGetDateCmdLet.PNG

You immediately get the response in the bottom pane as shown.

 PowerShellGetDateResponse.png

Now you can the date and time parts of current date using the DisplayHint parameter specifying which part you need. Here is the modified script to get the date part.

The ISE has intellisense and you do get support as shown

PowersheGetDateDisplay.PNG


PowersheGetDateParams.png
Click on DisplayHint and enter a space to get the params that you can access with the DisplayHint


PowershellDisplayHintParams.png

Run the script as shown below in the top pane and hitting the 'green' arrow and you will see the following in the bottom pane.
Get-Date -DisplayHint Date
The response in the bottom pane: 
PS C:\Users\Jayaram> Get-Date -DisplayHint Date
Tuesday, September 27, 2016

How to get the year part of the date?
If you pick year from the drop-down box, you end up with an error

PS C:\Users\Jayaram> Get-Date -Year
Get-Date : Missing an argument for parameter 'Year'. Specify a parameter of type
'System.Int32' and try again.
At line:1 char:10
+ Get-Date -Year
+          ~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Get-Date], ParameterBindingExcept
   ion
    + FullyQualifiedErrorId : MissingArgument,Microsoft.PowerShell.Commands.GetDateCo
   mmand

In order to get around this, you change it to:
PS C:\Users\Jayaram> $x=Get-Date
$x.Year
2016

Another way would be to get the date in a string; split it and take the last part as in the following:

$g="Tuesday, September 27, 2016"
$y=$g.Split()
$y[3]
PS C:\Users\Jayaram> $g="Tuesday, September 27, 2016"
$y=$g.Split()
$y[3]
2016

No comments: