Tig*_*toy 6 powershell loops move
ls *.gif | Foreach { $newname = $_.Name -replace '\[','' -replace '\]',''
write-host $_.Name $newname
move-Item -Path $_.Name -Destination $newname; }
ls *.gif
Run Code Online (Sandbox Code Playgroud)
因此,在尝试帮助某人使用[]重命名文件时,我发现move-item在循环中不起作用.它似乎在循环外工作得很好.
想法?
更新:根据下面的评论,我想澄清一下:文件名中的特殊字符要求您使用-LiteralPath参数.-Path无法处理这些字符.在循环之外,-Path有效,因为你使用`来转义特殊字符.在走过一个集合时,这是不可能的.
在循环中,您需要使用-LiteralPath参数而不是-Path.
-LiteralPath <string[]>
Specifies the path to the current location of the items. Unlike Path, the value of
LiteralPath is used exactly as it is typed. **No characters are interpreted as
wildcards. If the path includes escape characters, enclose it in single quotation
marks.** Single quotation marks tell Windows PowerShell not to interpret any
characters as escape sequences.
Run Code Online (Sandbox Code Playgroud)
那么,这将是:
GCI -Recurse *.txt | % { Move-Item -LiteralPath $_.FullName -Destination "SomenewName" }
Run Code Online (Sandbox Code Playgroud)