0
votes

Hi am not able to rename a file using the below code. Please help me on this

    $date = Get-Date -format "yyyyMMdd"
    $path='D:\Users\user\Desktop\Working\'
    $fn = $path+'xxx_'+$date+'.txt'
    $tn = $path+'yyy'+$date+'.dat'
    Rename-Item -Path $fn -NewName $tn

Am getting the below error.

Rename-Item : Cannot process argument because the value of argument "path" is not valid. Change the value of the "path" argument and run the operation again. At line:1 char:1 + Rename-Item -Path $fn -NewName $tn + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidArgument: (:) [Rename-Item], PSArgumentException + FullyQualifiedErrorId : Argument,Microsoft.PowerShell.Commands.RenameItemCommand

1
the file exist? - Victor Silva
Right before the rename, do this Write-Host ('$fn = {0} - $tn = {1}' -f $fn, $tn) - EBGreen
Please update your question with the result of the instruction in EBGreen's comment. - pfx
Try Remove-Variable path prior to defining path, in case something is casting $path to something besides a [string]. I had some code in my profile caused some similar issues by not cleaning up the $path variable. Using alternative methods of building the string like LotPings solution work by verifying that $path is of the expected type before use. (LotPings answer even has some extra validation to validate the path prior to use) - BenH

1 Answers

2
votes

I'd use Join-Path and Test-Path

$date = Get-Date -format "yyyyMMdd"
$path='D:\Users\user\Desktop\Working\'
$fn = Join-Path $path ("xxx_{0}.txt" -f $date)
$tn = Join-Path $path ("yyy_{0}.txt" -f $date)
If ((Test-Path $fn) -and !(Test-Path $tn)){
    Rename-Item -Path $fn -NewName $tn
} else {
    "{0} exists is {1}, `n{2} not exists is {3}" -f $fn,(Test-Path $fn),$tn,(!(Test-Path $tn))
}

There is no output on a successful rename, on error the output is like:

D:\Users\user\Desktop\Working\xxx_20180606.txt exists is False,
D:\Users\user\Desktop\Working\yyy_20180606.txt not exists is False