The–LiteralPath parameter

It’s 2013, we’ve got Powershell for a couple of years now, so it’s only natural to automate things, right? At least, that’s what I try to do. So, one of the things I’ve ended up doing some time ago was writing a simple script for copying files from an USB pen to a specific folder. As you can see, it’s really simple:

ls j:\ | foreach { 
  $itemName = $_.Name.Replace('.', ' ') 
  $destination = ls | where { $itemName -match $_.Name } | select -First 1 
  if( $destination -ne $null){       
   mi $_.PSPath $destination.PSPath -Verbose -WhatIf  
  } 
}

After some time where everything seemed to be running ok, I’ve noticed that some of the files weren’t being copied. After further analysis, I’ve noted that files contained the [ and ] chars weren’t being copied. Fortunately, we have StackOverflow and I’ve ended posting my question over there. One of the answers suggested to use the –LiteralPath parameter for the move-item cmdlet. According to the docs, the –LiteralPath parameter :

Specifies the path to the current location of the items. Unlike Path, the value of LiteralPath is used exactly as it is typed. No characters are interpreted as wildcards. If the path includes escape characters, enclose it in single quotation marks. Single quotation marks tell Windows PowerShell not to interpret any characters as escape sequences.

Did you notice the wildcards part? Yep, wildcards…unfortunately form me, I had completely forgotten that [] define wildcards which match a range of characters (note to self: do read the PowerShell docs). For instance, and this is just copied from the docs, here’s a quick example:

[a-l]ook matches book, cook or look, but not took.

Aha! ok, now it makes sense…that’s why those files which contained the [ ] on its name weren’t being copied. PowerShell was translating the values defined within [ ]  into ranges. Another note to self: don’t forget about wildcards when you’re writing PowerShell scripts.

And that’s it for now. Stay tuned for more.

About these ads

~ by Luis Abreu on February 15, 2013.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
Follow

Get every new post delivered to your Inbox.

Join 573 other followers

%d bloggers like this: