问题
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?
回答1:
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
}
}
回答2:
What if you change this line:
mi $_.PSPath $destination.PSPath -Verbose -WhatIf
to be this:
mi "$($_.PSPath)" "$($destination.PSPath)" -Verbose -WhatIf
回答3:
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
来源:https://stackoverflow.com/questions/14842927/powershell-moving-items-not-working-when-filenames-that-have-chars