Powershell: moving items not working when filename

2019-06-24 02:44发布

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?

3条回答
\"骚年 ilove
2楼-- · 2019-06-24 02:56

What if you change this line:

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

to be this:

mi "$($_.PSPath)" "$($destination.PSPath)" -Verbose -WhatIf
查看更多
爷的心禁止访问
3楼-- · 2019-06-24 03:01

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  
  } 
}
查看更多
在下西门庆
4楼-- · 2019-06-24 03:13

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

{"file1[vt]"} 

will match the strings "file1v" and "file1t". In order to use the

查看更多
登录 后发表回答