gpt4 book ai didi

Powershell: two options: replace special characters of file names(PowerShell:两个选项:替换文件名的特殊字符)

转载 作者:bug小助手 更新时间:2023-10-24 19:07:21 26 4
gpt4 key购买 nike



I don't know Powershell and tend to do most of my fiddling in CMD.
I've come across two methods of what I think does the same thing in Powershell (replace an illegal with legal character compatible w/ Windows File Explorer)?
I'm wondering if one of the below is recommended over the other? Is either of them really NOT recommended at all?

我不了解PowerShell,我的大部分工作都是在CMD上完成的。我遇到了两种我认为在PowerShell中做同样事情的方法(用与Windows文件资源管理器兼容的合法字符替换非法字符)?我想知道下面的其中一个是不是被推荐的?他们中的任何一个真的根本不被推荐吗?


Get-ChildItem -File -Recurse | Rename-Item -NewName {$_.name -replace "\]", ")"}

Get-ChildItem-文件-Recurse|重命名项目-新名称{$_.name-Replace“\]”,“)”}


Get-ChildItem -File -Recurse | % { Rename-Item -Path $_.PSPath -NewName $_.Name.replace("\]", ")"}

Get-ChildItem-File-Recurse|%{Rename-Item-Path$_.PSPath-newname$_.Name.Replace(“\]”,“)”}


Also wondering why the below two are the way they are. Seems like one would error out.

我也想知道为什么下面的两个是他们的方式。看起来有人会犯错。


$_.name -replace

$_.name-替换


$_.Name.replace

$_.名称.替换


Thanks for any information.

谢谢你提供的任何信息。


更多回答

] isn't an illegal character tho. Both methods are Ok to use but .Replace is literal, so in your example it will only replace a literal \]

]不是一个非法的字符。这两种方法都可以使用,但.Replace是文本的,因此在您的示例中它将仅替换文本\]

优秀答案推荐

Both methods are Ok to use but the difference is that .Replace is literal replacement, in your example, it will try to find and replace a literal \], whereas -replace uses regular expressions and, if you want to match a literal ] then you need to escape that character with \. See Escaping characters.

这两种方法都可以使用,但不同之处在于。Replace是文字替换,在您的示例中,它将尝试查找和替换文字\],而-Replace使用正则表达式,如果您希望匹配文字],则需要使用\对该字符进行转义。请参见转义字符。


In both examples I would definitely recommend to perform a pre filtering to find only files containing a ]. If you want both to do exactly the same (replace ] for a ) from files) then:

在这两个示例中,我绝对建议执行预筛选,以仅查找包含]的文件。如果希望两者执行完全相同的操作(替换文件中的),则:


# With -replace:
Get-ChildItem -Filter *]* -File -Recurse |
Rename-Item -NewName { $_.Name -replace '\]', ')' }

# With .Replace:
Get-ChildItem -Filter *]* -File -Recurse |
Rename-Item -NewName { $_.Name.Replace(']', ')') }

更多回答

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com