There are similar questions like this question, example Rename-item: Cannot rename because item at ... does not exist which gives the same error as the one I have. Mine is specific as the script works for some files, example
NB. I am not advanced in powershell scripting
Files | Renamed |
---|---|
DbBackUpV4.bak | true |
LongNameUpTo50Chars.bak | true |
Db[BackUp]V4.bak | false |
AnyNameWithChars[].bak | false |
the database backup files are named differently, I just noticed that the ones with []
charaters generate the error Rename-Item : Cannot rename because item at '' does not exist.
out of curiosity I tried using just one of the characters [
and I got another type of error Message:"Cannot retrieve the dynamic parameters for the cmdlet. The specified wildcard character pattern is not valid: DbBackUp[be9e-Full.bak"
I also check for windows file naming rules the characters []
are used for file naming, which makes me conclude it has to be something with power shell scripting.
$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
This is the part of the script, it is inside a loop, and $_.FullName gives me the name of the original file.
What exactly am I missing? Thanks for helping
CodePudding user response:
Use the -LiteralPath
argument. instead.
LiteralPath
Specifies a path to one or more locations. 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 PowerShell not to interpret any characters as escape sequences.
-Path
with parse some special characters so the use of ?
, *
[
and ]
might get problematic.
References: