Powershell: move items not working when filenames with [] characters

Quick question about moving items using PowerShell: does anyone know why the following script doesn't work when the filename has [or] characters on it? (ex: file1 [VT] .txt )

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  
  } 
}

      

For example, it moves a file if it is named file1.txt , but it simply ignores files named file1 [VT] .txt . I suppose it doesn't find the file path when it has [or] characters in its name. Any ideas?

+3


source to share


3 answers


Just using a parameter -literalpath

formove-item



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

      

+4


source


What if you change this line:

mi $_.PSPath $destination.PSPath -Verbose -WhatIf

      



:

mi "$($_.PSPath)" "$($destination.PSPath)" -Verbose -WhatIf

      

0


source


When you use the -match operator, it treats the pattern you are looking for ($ _. Name in your example) as a regular expression. In a .NET regular expression, the [and] characters are used to match a character to a group of tokens. For example, the regular expression

{"file1[vt]"} 

      

will match the strings "file1v" and "file1t". To use

0


source







All Articles