Search code examples
powershellfile-rename

Append string in file name using powershell


I am trying to append string in the file name.

$cstzone = [System.TimeZoneInfo]::FindSystemTimeZoneById("India Standard Time")
$csttime = [System.TimeZoneInfo]::ConvertTimeFromUtc((Get-Date).ToUniversalTime(), $cstzone)
$d = Get-Date $csttime -f "dd-MM-yyyy"
$t = Get-Date $csttime -f "HH:mm"
Write-Host "Date : " $d
Write-Host "Time : " $t

gci C:\Result.jtl | % { rename-item –Path $_.FullName –Newname ( $_.basename + $t + $_.extension) }

Expected

Result_14:42.jtl

Error

rename-item : Cannot rename the specified target, because it represents a path or device name.
At line:10 char:25
+ ... t.jtl | % { rename-item –Path $_.FullName –Newname ( $_.basename + $t ...
+                 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidArgument: (:) [Rename-Item], PSArgumentException
    + FullyQualifiedErrorId : Argument,Microsoft.PowerShell.Commands.RenameItemCommand

Solution

  • You can't have colons in file names, they are reserved for drive letters. You can use a tostring to get date in different format:

    (Get-Date).ToString("hh-mm")