get a list of powershell date format outputs

I want to create a list of Powershell date formats and their outputs, for a quick reference doc.

I’ve collected a list of formats from the Powershell help text and other locations and put them in a big text file which looks like this:

get-date -Uformat %A   # Day of the week - full name 
get-date -Uformat %u   # Day of the week - number (Monday = 1)
get-date -Uformat %d   # Day of the month - 2 digits 
get-date -Uformat %e   # Day of the month - digit preceded by a space ( 5)
get-date -Uformat %j   # Day of the year 
get-date -Uformat %p   # AM or PM
get-date -Uformat %r   # Time in 12-hour format
get-date -Uformat %R   # Time in 24-hour format - no seconds
get-date -Uformat %T   # Time in 24 hour format

I’m going to order this in what I consider to be order of usefullness (to me), because I’m going to plug it into an about_dateformats help page in my Powershell-help-powered repository of notes and tips.

To generate a list with the command, output and comment, I did this:

$Dates = foreach ($L in $(Select-String -notmatch "^$" formats.txt)) 
{
  [string]$Line = $L.Line
  $Command = $Line.split('#')[0]
  $Comment = $Line.split('#')[1]

  $scriptBlock = $executioncontext.InvokeCommand.NewScriptBlock($Line)

  $Output = invoke-command $ScriptBlock

  # write-output "$Command $Output # $Comment"
  new-object PSObject -Property @{
     Command = $Command
     Output =  $Output
     Comment = $Comment
  }

} 

$Dates | ft -a

The output looks like this:

<br />Output                            Command                                             Comment                                                           
------                            -------                                             -------                                                           
10                                Get-Date -UFormat %d                                                                                                  
Wed Feb 10 12:44:52 2016          get-date -UFormat %c                                 Date and time - abbreviated (Fri Jun 16 10:31:27 2006)           
02/10/16                          get-date -UFormat %D                                 Date in mm/dd/yy format (06/14/06)                               
02/10/16                          get-date -UFormat %x                                 Date in standard format for locale (09/12/07 for English-US)     
20                                get-date -Uformat %C                                 Century (20 for 2006)                                            
2016                              get-date -Uformat %Y                                 Year in 4-digit format (2006)                                    
16                                get-date -Uformat %y                                 Year in 2-digit format (06)                                      
Feb                               get-date -Uformat %b                                 Month name - abbreviated (Jan)                                   
February                          get-date -Uformat %B                                 Month name - full (January)                                      
02                                get-date -Uformat %m                                 Month number (06)                                                
5                                 get-date -Uformat %W                                 Week of the year (00-52)                                         
6                                 get-date -Uformat %V                                 Week of the year (01-53)                                         
Wed                               get-date -Uformat %a                                 Day of the week - abbreviated name (Mon)                         
Wednesday                         get-date -Uformat %A                                 Day of the week - full name (Monday)                             
3                                 get-date -Uformat %u                                 Day of the week - number (Monday = 1)                            
10                                get-date -Uformat %d                                 Day of the month - 2 digits (05)                                 
10                                get-date -Uformat %e                                 Day of the month - digit preceded by a space ( 5)                
41                                get-date -Uformat %j                                 Day of the year - (1-366)                                        
PM                                get-date -Uformat %p                                 AM or PM                                                         
12:44:52 PM                       get-date -Uformat %r                                 Time in 12-hour format (09:15:36 AM)                             
12:44                             get-date -Uformat %R                                 Time in 24-hour format - no seconds (17:45)                      
12:44:52                          get-date -Uformat %T                                 Time in 24 hour format (17:45:52)                                
+00                               get-date -Uformat %Z                                 Time zone offset from Universal Time Coordinate (UTC) (-07)      
12                                get-date -Uformat %H                                 Hour in 24-hour format (17)                                      
12                                get-date -Uformat %I                                 Hour in 12 hour format (05)                                      
44                                get-date -Uformat %M                                 Minutes (35)                                                     
52                                get-date -Uformat %S                                 Seconds (05)                                                     
1455108292.3719                   get-date -Uformat %s                                 Seconds elapsed since January 1, 1970 00:00:00 (1150451174.95705)
10/02/2016 12:44:52               Get-Date -DisplayHint Date                                                                                            
10/02/2016 12:44                  Get-Date -Format g                                                                                                    
2016 / 02 / 10 / Wednesday / +00  Get-Date -UFormat "%Y / %m / %d / %A / %Z"                                                                            
366                               (Get-Date -Year 2000 -Month 12 -Day 31).DayOfYear                                                                     
False                             $(get-date).IsDaylightSavingTime()                                                                                    
10/02/2016 12:44:52               $(get-date).ToUniversalTime()                                                                                         
10/02/2016 12:44:52               (Get-Date).ToString()                                                                                                 
2016-02-10T12:44:52.3749035+00:00 Get-Date -Format o                                                                                                    
2016-02-10T12.44.52.3759036+00.00 Get-Date -Format o | foreach {$_ -replace ":", "."}                           

fix for ‘Cannot convert value “System.Xml.XmlElement” to type “System.Xml.XmlDocument”‘

Quick fix

Change:

Param( [system.xml.xmlelement][Alias ("x")]$WordpressPostAsXml

to

Param( [system.xml.xmlelement]$XmlVariable

Slightly More Detail

I’m in the process of coding a Powershell module to convert an xml file containing the content of my old WordPress site to a set of Markdown files for Hugo.

I got the error:

get-wpHugoFileName : Cannot process argument transformation on parameter 'WordpressPostAsXml'. Cannot convert value "System.Xml.XmlElement" to 
type "System.Xml.XmlDocument". Error: "The specified node cannot be inserted as the valid child of this node, because the specified node is the 
wrong type."
At C:\users\matt\Documents\WindowsPowershell\functions\function-get-WordpressContent.ps1:43 char:63
+ ... goFileName = get-wpHugoFileName -WordPressPost $WordPressPost -Conten ...
+                                                    ~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [get-wpHugoFileName], ParameterBindingArgumentTransformationException
    + FullyQualifiedErrorId : ParameterArgumentTransformationError,get-wpHugoFileName

In summary, there are three relevant functions

  • convert-wpPostToHugo – receieves an exported WordPress site in Xml format. Calls get-wpMatchingWordpressPosts to extract the specified bits, then get-wpHugoFileName for each post
  • get-wpMatchingWordpressPosts – extracts the xml nodes for posts which match a specified string
  • get-wpHugoFileName – called for each xml ‘node’. Returns a file name for the markdown content

convert-wpPostToHugo:

function  convert-wpPostToHugo{ 

  [CmdletBinding()]
  Param( [xml][Alias ("xml")]$WordpressXML = "$wp_xml",
         [string][Alias ("string")]$PostString = "ramone" ,
         [string][Alias ("f")]$ContentFolder = "c:\temp"
) 
  write-debug "$(get-date -format 'hh:mm:ss.ffff') Function beg: $([string]$MyInvocation.Line) "

  $MatchingWordPressPosts = get-wpMatchingWordpressPosts -WordPressXml $WordPressXML -PostString $Poststring

  foreach ($WordPressPost in $MatchingWordPressPosts)
  {    
    [String]$HugoFileName = get-wpHugoFileName -WordPressPost $WordPressPost -ContentFolder $contentFolder
    write-verbose "`$HugoFileName: $HugoFileName"

get-wpMatchingWordpressPosts:

function get-wpMatchingWordpressPosts { 
  [CmdletBinding()]
  Param( [xml][Alias ("xml")]$WordpressXML = "$wp_xml",
         [string][Alias ("string")]$PostString = "ramone"         ) 

  write-debug "$(get-date -format 'hh:mm:ss.ffff') Function beg: $([string]$MyInvocation.Line) "

  $Nodes = select-xml -xml $WordpressXML -xpath "//channel/item" | select -expandproperty node | where-object title -like "*$PostString*"


  return $nodes

get-wpHugoFileName:

function get-wpHugoFileName { 

  [CmdletBinding()]
  Param( [xml][Alias ("x")]$WordpressPostAsXml,
         [string][Alias ("f")]$ContentFolder = "c:\temp" )

  write-debug "$(get-date -format 'hh:mm:ss.ffff') Function beg: $([string]$MyInvocation.Line) "

The fix was to change the definition of the $WordPressPost from xml to [system.xml.xmlelement]:
get-wpHugoFileName:

function get-wpHugoFileName { 

  [CmdletBinding()]
  Param( [system.xml.xmlelement][Alias ("x")]$WordpressPostAsXml,
         [string][Alias ("f")]$ContentFolder = "c:\temp" )

  write-debug "$(get-date -format 'hh:mm:ss.ffff') Function beg: $([string]$MyInvocation.Line) "

This makes sense….the variable returned from get-wpMatchingWordpressPosts is no longer a valid XML document – it is just elements of an XML document.

using powershell’s help system to stash your tips and tricks in ‘about_’ topics

There are a bunch of bits of syntax which I struggle to remember.

I’m not always online when I’m using my laptop, but I always have a Powershell window open.

This is a possibly not-best-practice way of using Powershell’s wonderful help system to store bits of reference material.

The problem

I’m moving a WordPress blog to Hugo, which uses Markdown, but I’m struggling to remember the Markdown syntax. It’s not difficult, but I’m getting old and I get confused with Twiki syntax.

In any case this ‘technique’ could be used for anything.

I could equally well just store the content in a big text file, and select-string it….but this is more fun :)

The content

In this instance I only need a few lines as an aide-memoire:

    ## The second largest heading (an <h2> tag)
    > Blockquotes
    *italic* or _italic_
    **bold** or __bold__
    * Item (no spaces before the *) or
    - Item (no spaces before the -)
    1. Item 1
      1. Furthermore, ...
    2. Item 2
    `monospace` (backticks)
    ```` begin/end code block
    [A link!](http://mattypenny.net).

create a module

The module path is given by:

$env:PSModulePath

Mine is:

C:\Users\matty\Documents\WindowsPowerShell\Modules;C:\Program Files\WindowsPowerShell\Modules;C:\Windows\system32\WindowsPowerShell\v1.0\Modules\;C:\Program Files (x86)\Microsoft SQL Server\110\Tools\PowerShell\Modules\

Pick one of this folders to create your module in and do this:

mkdir C:\Users\matty\Documents\WindowsPowerShell\Modules\QuickReference

Then create a dummy Powershell module file in the folder

notepad C:\Users\matty\Documents\WindowsPowerShell\Modules\QuickReference\QuickReference.psm1

The content of the module file is throwaway:

function dummy {write-output "This is a dummy"}

create the help file(s)

Create a language-specific folder for the help files

mkdir C:\Users\matty\Documents\WindowsPowerShell\Modules\QuickReference\en-US\

Edit a file called about_.help.txt

notepad C:\Users\mpenny2\Documents\WindowsPowerShell\Modules\QuickReference\en-US\about_Markdown.help.txt

My content looked like this:

TOPIC
    about_Markdown

SHORT DESCRIPTION
    Syntax for Markdown 

LONG DESCRIPTION

    ## The second largest heading (an <h2> tag)
    > Blockquotes
    *italic* or _italic_
    **bold** or __bold__
    * Item (no spaces before the *) or
    - Item (no spaces before the -)
    1. Item 1
      1. Furthermore, ...
    2. Item 2
    `monospace` (backticks)
    ```` begin/end code block
    [A link!](http://mattypenny.net).

Use the help

I can now do this (I’ll import the module in my $profile):

PS C:\Windows> import-module QuickReference

Then I can access my Markdown help from within Powershelll

PS C:\Windows> help Markdown
TOPIC
    about_Markdown

SHORT DESCRIPTION
    Syntax for Markdown 

LONG DESCRIPTION

    ## The second largest heading (an <h2> tag)
    > Blockquotes
    *italic* or _italic_
    **bold** or __bold__
    * Item (no spaces before the *) or
    - Item (no spaces before the -)
    1. Item 1
      1. Furthermore, ...
    2. Item 2
    `monospace` (backticks)
    ```` begin/end code block
    [A link!](http://mattypenny.net).

extracting post details from wordpress xml dump with powershell

Get the xml into a variable

[xml]$xmla = get-content D:\repair_websites\salisburywiltshireandstonehenge.wordpress.2015-10-03.xml                       

Extract the details

select-xml -xml $xmla -xpath "//channel/item" | select -expandproperty node | ? post_type -ne "attachment" | select title  

gives the following:

title                        
-----                        
Road names beginning with 'N'
Road names beginning with 'O'
Road names beginning with 'P'
Road names beginning with 'Q'
Road names beginning with 'R'
Road names beginning with 'S'
Road names beginning with 'T'
Road names beginning with 'U'
Road names beginning with 'V'
Road names beginning with 'W'

The properties of the expanded node are:
wordpress-xml-powershell-properties

For example:

select-xml -xml $xmla -xpath "//channel/item" | select -expandproperty node | ? post_type -ne "attachment" | ? title -like "*Ramone*"

outputs:

title          : 3rd June 1977 - the Ramones visit Stonehenge. Johnny stays on the bus
link           : http://salisburyandstonehenge.net/on-this-day/june/3rd-june-1977-the-ramones-visit-stonehenge-johnny-stays-on-the-bus
pubDate        : Tue, 04 Nov 2014 12:33:09 +0000
creator        : creator
guid           : guid
description    : 
encoded        : {content:encoded, excerpt:encoded}
post_id        : 9267
post_date      : 2014-11-04 12:33:09
post_date_gmt  : 2014-11-04 12:33:09
comment_status : open
ping_status    : closed
post_name      : 3rd-june-1977-the-ramones-visit-stonehenge-johnny-stays-on-the-bus
status         : publish
post_parent    : 6624
menu_order     : 3
post_type      : page
post_password  : 
is_sticky      : 0
postmeta       : {wp:postmeta, wp:postmeta, wp:postmeta, wp:postmeta}

To get the actual content of the post:

select-xml -xml $xmla -xpath "//channel/item" | select -expandproperty node | ? post_type -ne "attachment" | ? title -like "*Ramone*" | select -ExpandProperty encoded | fl

…gives:

#cdata-section : <a href="http://salisburyandstonehenge.net/images/Joey-Ramone-visited-Stonehenge.jpg"><img src="http://salisburyandstonehenge.net/images/Joey-Ramone-visited-Stonehenge.jpg" alt="Joey Ramone - 'visited' 
                 Stonehenge" width="320" height="455" class="alignright size-full wp-image-9702" /></a>On either the 3rdIn 'On the Road with 
                 the Ramones', Monte A. Melnick says that the visit occurred 

                 <blockquote>'On the '77 tour we had a day off and noticed Stonehenge was on the way'[URL <a href="http://books.google.co.uk/books?
                 id=N7m8AwAAQBAJ&lpg=RA1-PR24&dq=ramones%20stonehenge&pg=RA1-PR25#v=onepage&q=ramones%20stonehenge&f=false">'On the Road with the 
                 Ramones', by By Monte A. Melnick, Frank Meyer</a>].</blockquote>

                 This would have been when the Ramones were travelling back from Penzance to Canterbury - the free day being June 3rd [<a href="http://en.wikipedia.org/wiki/List_of_Ramones_concerts#1977">Wikipedia List Of Ramones Concerts</a>] or possibly the 
                 4th June 1977, the Ramones visited Stonehenge.

                 Pic: By en:User:Dawkeye [<a href="http://www.gnu.org/copyleft/fdl.html">GFDL</a>, <a href="http://creativecommons.org/licenses/by-sa/3.0/">CC-BY-SA-3.0</a> or <a href="http://creativecommons.org/licenses/by-sa/2.5">CC-BY-SA-2.5</a>], <a href="http://commons.wikimedia.org/wiki/File%3AJoeyramone.jpg">via Wikimedia Commons</a>

                 More:

                 <a href="http://books.google.co.uk/books?id=c7lgKVmD0yMC&lpg=PA170&dq=ramones%20stonehenge&pg=PA171#v=onepage&q=ramones%20stonehen
                 ge&f=false" title="http://books.google.co.uk/books?id=c7lgKVmD0yMC&lpg=PA170&dq=ramones%20stonehenge&pg=PA171#v=onepage&q=ramones%
                 20stonehenge&f=false">I Slept with Joey Ramone: A Family Memoir By Mickey Leigh</a>

                 <a href="http://books.google.co.uk/books?id=N7m8AwAAQBAJ&lpg=RA1-PR24&dq=ramones%20stonehenge&pg=RA1-PR25#v=onepage&q=ramones%20st
                 onehenge&f=false" title="http://books.google.co.uk/books?id=N7m8AwAAQBAJ&lpg=RA1-PR24&dq=ramones%20stonehenge&pg=RA1-PR25#v=onepag
                 e&q=ramones%20stonehenge&f=false">On the Road with the Ramones By Monte A. Melnick, Frank Meyer</a>

                 <a href="http://books.google.co.uk/books?ei=AxPJU5u3Jae60QXB1ICQBQ&id=QTjaAAAAMAAJ&dq=ramones+stonehenge&focus=searchwithinvolume&
                 q=+stonehenge" title="http://books.google.co.uk/books?ei=AxPJU5u3Jae60QXB1ICQBQ&id=QTjaAAAAMAAJ&dq=ramones+stonehenge&focus=search
                 withinvolume&q=+stonehenge">A Time to Rock: A Social History of Rock and Roll by David P. Szatmary</a>


#cdata-section : 

powershell to recursively spool out code in markdown format

A one-liner to recursively gather code from sub-folders and then output it in a Markdown-style

$Text = foreach ($file in $(dir .\themes\hyde -recurse -exclude "*.png" | ? attributes -ne 'Directory' | select fullname)) 
{
    [string]$filename = $file.fullname
    write-output "`#`#`# $filename"
    write-output "````````"
    get-content $filename
    write-output "````````" 
}

$Text > x.txt

Produces output a like this:

D:\hugo\sites\example.com\themes\hyde\archetypes\default.md

+++
Description = ""
Tags = ["Development", "golang"]
Categories = ["Development", "GoLang"]
menu = "main"
+++

D:\hugo\sites\example.com\themes\hyde\layouts_default\list.html

{{ partial "head.html" . }}
<body class="{{ .Site.Params.themeColor }}">

{{ partial "sidebar.html" . }}

<div class="content container">
<ul class="posts">
{{ range .Data.Pages }}

error 740 running DISM

As the error message says, if you get Error 740

PS C:\Users\matty> DISM /Online /Enable-Feature /FeatureName:NetFx3 /All /LimitAccess /Source:z:\sources\sxs

Error: 740

Elevated permissions are required to run DISM.
Use an elevated command prompt to complete these tasks.

…you just have to run your Command Prompt or Powershell window ‘as Administrator’. i.e. right-click on the icon and select ‘Run as administrator’

PS C:\Windows\system32> DISM /Online /Enable-Feature /FeatureName:NetFx3 /All /LimitAccess /Source:z:\sources\sxs

Deployment Image Servicing and Management tool
Version: 6.3.9600.17031

Image Version: 6.3.9600.17031

Enabling feature(s)
[==========================100.0%==========================]
The operation completed successfully.
PS C:\Windows\system32>