Brain teaser – one way to solve it

This is the command I had initially in mind when writing the last modified time teaser:

ls $pshome\powershell.exe|date

I also had this one, which is shorter:

ps -id $pid|gi|date

But I specifically asked for powershell.exe and the above might report the last modified time of hosts other than powershell.exe (e.g ISE). Some of the answers also used wildcards for the file name. It certainly shortens the command but may introduce false results if similar files were added to the PowerShell folder.

Anyway, the trick to make it work without having to refer to the LastWriteTime property is to pipe a file system object to the Get-Date cmdlet. Why does that work?

The Date parameter of the Get-Date cmdlet accepts pipeline input by property name (the parameter attribute ValueFromPipelineByPropertyName is set to $true). The Date parameter also defines a LastWriteTime alias. This means that the value of incoming objects that have a Date property (or a LastWriteTime property), is assigned to the Date parameter.

PS> (Get-Command Get-Date).Parameters.Date

Name            : Date
ParameterType   : System.DateTime
ParameterSets   : {[__AllParameterSets, System.Management.Automation.ParameterSetMetadata]}
IsDynamic       : False
Aliases         : {LastWriteTime}
Attributes      : {__AllParameterSets, System.Management.Automation.AliasAttribute}
SwitchParameter : False

And why date and not Get-Date? When PowerShell search for a command, if the command was not found it tries to prepend it with the default Get verb.

So, if PowerShell can’t find a command named ‘date’, it will try a second time with Get-Date.

You can see this in action if you execute any Get command without the verb. For instance, service vs. Get-Service, and so on.

That’s it. I hope you liked the challenge, I know I did!

This time the winner is Jakub Jareš. Jakub, I hope you had a good night sleep the other day, you nailed it! Head on to Jakub’s blog, he wrapped up his work on the teaser on his blog: http://powershell.cz/2012/12/07/last-modified-date-brainteaser

Sorry we don’t have any giveaways this time but you’ve got our respect 🙂

Share on: