Object Types (PowerShell)
Datetime
The object structure: http://msdn.microsoft.com/en-us/library/system.datetime.aspx
Improper (US) Formatting
Be aware that if you live somewhere dates are normally formatted properly (eg not the USA), then PowerShell (or probably the underlying DateTime object type as this sort of problem seems to rear its head at unexpected moments when working on Windows) has a nasty habit of returning a string formatted with day and month swapped around when coming from a script.
If you do a Get-Date
it all looks fine, but then you output a DateTime object in a script to some text and its wrong. Add the .ToString()
method to the end at it'll sort itself, though quite why when Powershell is converting the object into a string anyway in order to display, should the object need to be explicitly told to fix the issue, seems a bit superfluous. I obviously don't understand what the underlying bug is!
If your dates are getting mixed up, it may not be your mistake, and it may be that you've fallen fowl of the problem as well.
Formatting
To control how a DateTime is displayed you can pass it through Get-Date
with the -uFormat
option...
Get-Date $datetime -uFormat "%R hrs, %a %d %b %Y"
Useful formatting examples...
uFormat Specifier | Example |
---|---|
%R hrs, %a %d %b %Y |
07:25 hrs, Fri 24 Dec 2010
|
%Y-%m-%d |
2010-12-24
|
For the full list of formatting options see http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx
Or you can use the ToString
method provided by the object, to convert the date. If you use a generic specifier you should get a local format output (though see note above about Improper (US) Formatting if things aren't behaving expected)...
$datetime.ToString("s")
Useful formatting examples...
ToString Method Specifier | UK-Centric Example Output |
---|---|
<blank> |
17/02/2011 13:07:33
|
d |
17/02/2011
|
D |
17 February 2011
|
yyyy-MM-dd HH:mm:ss |
2011-02-17 13:07:33
|
HH:mm:ss.fff |
13:07:33.423
|
For the full list of formatting options see http://technet.microsoft.com/en-us/library/ee692801.aspx, and even more detail at http://msdn.microsoft.com/en-us/library/system.globalization.datetimeformatinfo.aspx
Converters
function ConvertLocalToUnix([datetime]$datetime)
{
($datetime.ToUniversalTime() - ([datetime]'1/1/1970 00:00:00')).TotalSeconds
}
function ConvertUnixtoLocal($sincepoch)
{
[timezone]::CurrentTimeZone.ToLocalTime(([datetime]'1/1/1970').AddSeconds($sincepoch))
}
IP Address
The object structure: http://msdn.microsoft.com/en-us/library/system.net.ipaddress
To create an IP address object...
$ip = [System.Net.IPAddress]::Parse("192.168.1.123")
To confirm a supplied address is valid...
if ( [System.Net.IPAddress]::TryParse($IP2test) ) {
Write-Host "$IP2test is a valid address"
}