Why does this PowerShell script fail to rename my files?

Welcome Forums General PowerShell Q&A Why does this PowerShell script fail to rename my files?

This topic contains 2 replies, has 2 voices, and was last updated by

 
Participant
4 years, 7 months ago.

  • Author
    Posts
  • #16138

    Participant
    Points: 0
    Rank: Member

    $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

    Moderator
    Points: 24
    Team Member
    Rank: Member

    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

    Participant
    Points: 0
    Rank: Member

    thank you that worked

The topic ‘Why does this PowerShell script fail to rename my files?’ is closed to new replies.