2

I work for a law firm and we have a process that spits out text files with specific information on them in a specific pattern.

Let's say it's this: 1111.xxxxx_2222

I need to create a folder based on the characters that match the 'x' section and move the text files that have the same matching characters in the 'x' section into that folder, repeatedly. There's a couple hundred we have to go through a day so it gets a little tedious doing them by hand.

I've tried this:

$Source = 'Source folder'

(Get-ChildItem -Path $Source -File) | ForEach-Object {
    $destination = Join-Path -Path $Source -ChildPath $_.BaseName

    if(!(Test-Path $destination)){
        New-Item -ItemType Directory -Path $destination | Out-Null
    }
    $_ | Move-Item -Destination $destination
}

I left the source folder off because it is a network location that I can edit.

This script is not specific enough. It does sort them based on their entire name and it only moves them to a folder of that same name. It cannot run again because the name may be created already which will not work in my case. I'm VERY NEW to power shell and can code at a basic level so any help is appreciated!

1 Answers1

4

You can use a delay-bind script block:

$Source = 'Source folder'

Get-ChildItem -Path $Source -File | Move-Item -WhatIf -Destination {
  # Derive the target dir. from the input filename.
  $dirPath = Join-Path $Source ($_.BaseName -split '[._]')[1]
  # Make sure that the target dir. exists. Note that the
  # -Force switch ensures that no error occurs if the dir. already exists.
  $null = New-Item -Type Directory -Force $dirPath
  $dirPath # Output the target directory path.
}

Note the use of the -WhatIf common parameter, which previews the move operations, but note that only the moving of the files is previewed; the creation of the target directories still happens, because the delay-bind script block must be run even with WhatIf present, so as to be able to display the would-be destination path.

Once the preview signals that the moving would work as intended, remove -WhatIf from the Move-Item call.

($_.BaseName -split '[._]')[1] is what extracts the xxxxx from a file (base) name such as 111.xxxxx_2222, using -split, the regex-based string splitting operator

mklement0
  • 382,024
  • 64
  • 607
  • 775