Author Posts

November 15, 2013 at 3:19 am

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.

November 15, 2013 at 5:30 am

Try this:

$rootFolder = '.'

Get-ChildItem -Path $rootFolder -File |
ForEach-Object {
    $file = $_

    if ($file.Name -notmatch '^(.+)_(\d{8})\.ear$')
    {
        return
    }

    $folder = Join-Path -Path $rootFolder -ChildPath $matches[2]
    $name = "$($matches[1]).ear"

    if (-not (Test-Path -Path $folder -PathType Leaf))
    {
        try
        {
            $null = New-Item -Path $folder -ItemType Directory -ErrorAction Stop
        }
        catch
        {
            Write-Error -ErrorRecord $_
            return
        }
    }

    Move-Item -Path $file.FullName -Destination (Join-Path -Path $folder -ChildPath $name)
}