I've been experimenting more with my PSTypeExtensionTools module, finding more objects to enhance. You can check out the project on Github and install the module from the PowerShell Gallery. My current fun has been with the DateTime object – specifically converting a value into another culture. Apparently those of us in North America don't know how to format a date properly. But now with a few script methods added to the DateTime type, I can correct that oversight.
ManageEngine ADManager Plus - Download Free Trial
Exclusive offer on ADManager Plus for US and UK regions. Claim now!
How your dates are formatted is stored in a culture definition.
You can get information for other cultures by using the .NET Framework.
Let's reformat a date:
I can use the –f operator and specify a different pattern.
$n = Get-Date "{0:$([cultureinfo]::GetCultureInfo("en-gb").datetimeformat.fulldatetimepattern)}" -f $n
This isn't especially difficult. But it is a lot to type. So let's make this an extension to the DateTime type with my Add-PSTypeExtension command.
$sb = { Param ([string]$culture) "{0:$([cultureinfo]::GetCultureInfo("$culture").DateTimeFormat.fulldatetimepattern)}" -f $this } Add-PSTypeExtension -TypeName System.Datetime -MemberType ScriptMethod -MemberName ConvertCulture -Value $sb
Now this is much easier. All I need to do is invoke the script method and provide a culture.
I also added a method to convert to a short date pattern.
$sb2 = { Param ([string]$culture) "{0:$([cultureinfo]::GetCultureInfo("$culture").DateTimeFormat.ShortDatePattern)}" -f $this } Add-PSTypeExtension -TypeName System.Datetime -MemberType ScriptMethod -MemberName ConvertShortDate -Value $sb2
You use it the same way.
I'm not sure of an especially practical use for these methods, but they are fun to play with and help demonstrate the value in extending type definitions. I hope you'll give the PSTypeExtenstionTools module a spin and let me know what you think.
Jeff, this is interesting material, and something folks who work with dates would appreciate. Wish you would capture your transcript or otherwise make these samples copy-and-paste friendly so we can get these into our own snippet libraries easily.
You should be able to easily copy code samples. When you expand the code snippet there is a copy icon in the title bar. That should be all you need. At some point I’ll add these as samples to the project as well.