Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell: moving items not working when filenames that have chars [ ]

Quick question about moving items with PowerShell: does anyone know why the following script does not work when the filename has the [ or ] chars 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 instance, it will move the file if it's called file1.txt but it will simply ignore files named file1[VT].txt. I'm under the assumption that it's not finding the path to the file when it has chars [ or ] on its name. Any ideas?

like image 567
Luis Abreu Avatar asked Feb 12 '13 22:02

Luis Abreu


People also ask

How do you rename a file in PowerShell?

To rename and move an item, use Move-Item . You can't use wildcard characters in the value of the NewName parameter. To specify a name for multiple files, use the Replace operator in a regular expression. For more information about the Replace operator, see about_Comparison_Operators.

How do I navigate to a folder in PowerShell?

Typing CD\ causes PowerShell to move to the root directory. As you can see, you can use the CD.. or CD\ command to move to a lower level within the folder hierarchy. You can also use the CD command to enter a folder. Just type CD, followed by the folder name.

What is robocopy in PowerShell?

Leos Marek Wed, Aug 10 2022 Sat, Aug 13 2022 commands, powershell 31. Robocopy (Robust File Copy) is a command line folder and file replication tool available as a standard Windows feature since Windows Server 2008.


1 Answers

Just using -literalpath parameter for move-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  
  } 
}
like image 139
CB. Avatar answered Sep 24 '22 19:09

CB.