Why does this PowerShell script fail to rename my files?

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of H Man H Man 3 years ago.

  • Author
    Posts
  • #16138
    Profile photo of H Man
    H Man
    Participant

    $SourceDir = "C:\somedir"

    Get-ChildItem -Path $SourceDir |
    foreach {
    if ($_ -match "(\d{10})" ) {

    $phone = "$($matches[0])$($_.Extension)"
    $day = (date).AddDays(-1).ToShortDateString()
    $newname = "$day" + '-' + "$oldname"
    Rename-Item -Path $_.FullName -newName $newname -Force
    }
    }

  • #16139
    Profile photo of Daniel Krebs
    Daniel Krebs
    Moderator

    The Rename-Item most likely fails due to the date in the $day variable.

    (date).AddDays(-1).ToShortDateString() returns 10/06/2014 on my PC and the slash is not a valid character for a file name. You need to use something like (date).AddDays(-1).ToString('yyyy-MM-dd') to get a valid date string for your file name.

    Regards
    Daniel

  • #16147
    Profile photo of H Man
    H Man
    Participant

    thank you that worked

You must be logged in to reply to this topic.