Powershell:当具有字符[]的文件名时移动项目不起作用

Lui*_*reu 5 powershell filenames

关于使用PowerShell移动项目的快速问题:有没有人知道为什么当文件名上有[或]字符时,以下脚本不起作用?(例如: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  
  } 
}
Run Code Online (Sandbox Code Playgroud)

例如,它将移动文件,如果它被称为file1.txt,但它将忽略名为file1 [VT] .txt的文件.我假设当它的名字上有字符[或]时,它找不到文件的路径.有任何想法吗?

CB.*_*CB. 5

只需使用-literalpath参数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  
  } 
}
Run Code Online (Sandbox Code Playgroud)