Creating a variable from part of a file name.

This topic contains 1 reply, has 2 voices, and was last updated by  Dave Wyatt 4 years, 8 months ago.

  • Author
  • #11501

    Jonathan Cook

    Hi All,

    I'm trying to create a script to take file names that come in to us with a date on them and rename them without the date, however use the date from the original names and create a folder out of them.

    Original Names: Name_20131115

    Renames to: Name

    Creates folder based on the "20131115" portion of the original name, so: Folder 20131115.

    I only want it to take the date portion of the original filename to use as the folder.. I've tried a few things but without success, here is the script so far;

    rename-item -Force File_*************.ear -NewName "File.ear"

    ***'s are wildcards so that it picks up any dates and doesn't need to prompt user to specify the date as a variable.

    Hope someone can help! Thank you.

  • #11503

    Dave Wyatt

    Try this:

    $rootFolder = '.'
    Get-ChildItem -Path $rootFolder -File |
    ForEach-Object {
        $file = $_
        if ($file.Name -notmatch '^(.+)_(\d{8})\.ear$')
        $folder = Join-Path -Path $rootFolder -ChildPath $matches[2]
        $name = "$($matches[1]).ear"
        if (-not (Test-Path -Path $folder -PathType Leaf))
                $null = New-Item -Path $folder -ItemType Directory -ErrorAction Stop
                Write-Error -ErrorRecord $_
        Move-Item -Path $file.FullName -Destination (Join-Path -Path $folder -ChildPath $name)

You must be logged in to reply to this topic.