【问题标题】:Power Shell script not renaming file with [] characters [duplicate]Powershell脚本没有用[]字符重命名文件[重复]
【发布时间】:2021-11-22 15:53:58
【问题描述】:

有类似的问题,例如Rename-item: Cannot rename because item at ... does not exist,它给出的错误与我的错误相同。 我的是特定的,因为脚本适用于某些文件,例如

注意。我在 powershell 脚本方面并不先进

Files Renamed
DbBackUpV4.bak true
LongNameUpTo50Chars.bak true
Db[BackUp]V4.bak false
AnyNameWithChars[].bak false

数据库备份文件的命名不同,我只是注意到带有[] 字符的那些会生成错误Rename-Item : Cannot rename because item at '' does not exist. 出于好奇,我尝试只使用[ 中的一个字符,但我得到了另一种类型的错误Message:"Cannot retrieve the dynamic parameters for the cmdlet. The specified wildcard character pattern is not valid: DbBackUp[be9e-Full.bak"

我还检查了 Windows 文件命名规则,字符 [] 用于文件命名,这让我得出结论,它必须与 power shell 脚本有关。

$Now = Get-Date -Format "ddMMyyyyhhmmss"
$NewFileName = $FileNameWithoutExtensionShort + "_DWArchive_" + $Now + $num + $BackupFileExtention;
$num = $num + 1; 

if ($NewFileName.Contains("[") -or $NewFileName.Contains("]") -or $NewFileName.Contains("-")) {
  #Remove special characters from name before renaming
  Log -Message "Remove special characters from name ($NewFileName) before renaming"
  $NewFileName = $NewFileName.replace("[", "_").replace("]", "_").replace("-", "_")
}
# if($_.Exists){
#   Rename-Item -Path $_.FullName -NewName  $NewFileName. #This also fails
# }
Rename-Item -Path $_.FullName -NewName  $NewFileName

这是脚本的一部分,它在一个循环中,$_.FullName 给了我原始文件的名称。

我到底错过了什么?感谢您的帮助

【问题讨论】:

  • 改用Rename-Item -LiteralPath

标签: powershell


【解决方案1】:

使用-LiteralPath 参数。而是。

文字路径

指定一个或多个位置的路径。 LiteralPath 的值为 完全按照键入的方式使用。没有字符被解释为 通配符。如果路径包含转义字符,请将其括在 单引号。单引号告诉 PowerShell 不要 将任何字符解释为转义序列。

-Path 会解析一些特殊字符,因此使用 ?* [] 可能会出现问题。

参考资料:

About wildcards

Rename-Item

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-25
    • 1970-01-01
    • 2015-06-03
    • 1970-01-01
    • 1970-01-01
    • 2013-04-16
    • 2015-06-21
    • 2018-04-21
    相关资源
    最近更新 更多