Friday, August 16, 2013

PowerShell - Copy files that contain square brackets in file name.

I tried to copy all mp3 files in iTunes music folder's subfolders onto another folder without subfolder structures. This was relatively straightforward task until I ran into files that contain square brackets in file names (i.e., "Tom's Diner [1990].mp3").  For example,

$folderItems = Get-ChildItem "C:\Users\John Doe\Music\iTunes\iTunes media\Music\" -Recurse
$newFolder = "C:\Users\John Doe\My Documents\MusicTemp\"
$foreach( $item in $folderItems )
    if( $item.Attributes -eq "Archive" )
        Copy-Item $item.FullName $newFolder

The code above kept failing due to PowerShell's de-escaping the strings multiple times internally and using special characters for pattern matching. Getting PowerShell to correctly recognize a literal square bracket in a path string turned out to be more complex than I thought.

I googled around and found a suitable workaround for this problem. Basically you would have to escape both open-square-bracket "[" and close-square-bracket "]" with backtick characters "`".

When using single-quote for string, two backticks are needed in front of a bracket in the string.
For double-quoted string, four backticks are needed in front of a bracket in the string.

The workaround PowerShell script is show below. I used double backticks to properly escape the square brackets.

$folderItems = Get-ChildItem "C:\Users\John Doe\Music\iTunes\iTunes Media\Music\" -Recurse
$newFolder = "C:\Users\Jone Doe\Music\iTunes\iTunes Media\MusicTemp\"
foreach($item in $folderItems)
    if( $item.Attributes -eq "Archive")
       $escapedFullName = $item.FullName.Replace('[', '``[').Replace(']', '``]')
       Copy-Item $escapedFullName $newFolder       

Here is the link that I got the workaround idea from.

Wednesday, August 7, 2013

CentOS - how to change computer name and static IP address (network settings)

To update computer name (hostname) and IP Address in CentOS, edit the following files.

  • Computer Name (host name)
  • IP Address and other network settings
    /etc/sysconfig/network-scripts/ifcfg-eth0  (or similar file)

Reboot the computer afterwards.