Thursday 14 November 2013

Fix-FileName.ps1

  1. <# 
  2. .SYNOPSIS 
  3.     Defines a function to remove 'invalid' characters 
  4.     from a file name. 
  5. .DESCRIPTION 
  6.     Some programs do not like certain 'invalid' characters 
  7.     in a file name used by that application. The function 
  8.     takes a look at each the file name and replaces some invalid 
  9.     characters with '-'
  10.  
  11.     This function takes a file name and 'fixes' it and returns 
  12.     the 'fixed' file name. Needless to say the characters to match 
  13.     and what to replace them with is an application specific decision! 
  14. .NOTES 
  15.     File Name  : Fix-FileName.ps1 
  16.     Author     : Thomas Lee - tfl@psp.co.uk 
  17.     Requires   : PowerShell Version 3.0 
  18. .LINK 
  19.     This script posted to: 
  20.         http://www.pshscripts.blogspot.com 
  21. .EXAMPLE 
  22.     Psh> .\Fix-FileName.ps1 
  23.     File name was: 123{}{{{|[\] 
  24.     Fixed name is: 123-------- 
  25.  
  26. #> 
  27.  
  28.  
  29. Function Fix-FileName { 
  30. [CMdletbinding()] 
  31. Param ( 
  32. $fn = $(throw 'no file name specified - returning'
  33.  
  34. Switch -Regex ($fn) { 
  35.   "}"  { $fn = $fn -replace '{','-'  } 
  36.   "}"  { $fn = $fn -replace '}','-'  } 
  37.   "\]" { $fn = $fn -replace ']','-'  } 
  38.   "\[" { $fn = $fn -replace '\[','-'
  39.   "\\" { $fn = $fn -replace '\\','-' } 
  40.   "\|" { $fn = $fn -replace '\|','-' } 
  41. } 
  42. $fn 
  43. } 
  44.  
  45. $fn = "123{}{{{|[\]" 
  46. $fnf = Fix-FileName $fn 
  47. "File name was: $fn" 
  48. "Fixed name is: $fnf