Home > Mobile >  powershell, search a filename for 5 characters after the second. create a new directory if it is uni
powershell, search a filename for 5 characters after the second. create a new directory if it is uni

Time:07-28

I am very very new to powershell, and have managed to get some basic commands to run. However, i am stuck on this one.

I have a folder with hundreds of .txt files in them. Each .txt file has a specific naming format. 220401.tailnm.22JUN21.CALLSIGN.txt I need to be able to break these files out by month and year.

So how can I write: look at all of the text files, search each filename for the first 5 characters after the second "." If that directory doesn't exist, create a new one with that name and move the file into it. if the directory already exists, just move the file into it. ??

I have found some similar posts online, but I don't fully understand what they are doing, hence why what i have come up with probably doesn't make much sense?

$files = get-childitem {$_.name -like "011529.tailnm.*"} $files %{$date = $_.name.Split('.')[2] | if (-not(test-path $date)) {md $date} $_.fullname | move -destination $date}

I just keep getting the red error: Get-ChildItem : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Filter'.

Any help on this is greatly appreciated.

Many thanks in advance, Kind Regards

CodePudding user response:

Ok, this should do what you want. I have added inline comments on every step to help understand the code.

# specify the rootfolder for the subdirectories and files
$destination = 'X:\The folder where the subfolders should be and the files to be moved to'
# find the files that fit the naming format
Get-ChildItem -Path 'C:\users\xxxxxxx' -Filter "*.tailnm.*.txt" -File | ForEach-Object {
    $date = $_.Name.Split('.')[2]
    if ($date.Length -gt 5) { $date = $date.Substring(0,5) }
    # combine the target destination folder path
    $targetDirectory = Join-Path -Path $destination -ChildPath $date
    if (-not(Test-Path -Path $targetDirectory -PathType Container)) {
        # create the subfolder if it did not yet exist
        $null = New-Item -Path $targetDirectory -ItemType Directory
    }
    # finaly move the file (represented by $_)
    $_ | Move-Item -Destination $targetDirectory
}
  • Related