1

I am trying to move files to a certain folder if they start with a letter and delete them if they start with anything other than a letter.

My code:

Function moveOrDelete($source, $dest)
{
    $aToZ = '^[a-zA-Z].*'
    $notALetter = '^[^a-zA-Z].*'

    Get-ChildItem -Path $source\$aToZ -Recurse | Move-Item -Destination $dest

    Get-ChildItem -Path $source\$notALetter -Recurse | Remove-Item
}

As I understand it the caret will match on the first character when it's outside of the brackets. In other words, the regex in the $aToZ variable will match anything that begins with a letter. the .* part will allow the rest of the file name to be anything. The caret inside the brackets negates the statement so if the file name begins with anything other than a letter it will match. I can't get it to work and I'm not getting any errors which leads me to believe that my regex is wrong.

I have checked this with online tools including this one: https://regex101.com/ and they check out.

I have also used variations of the regex like ^[a-zA-Z] that don't work. Some patterns like [a-zA-Z]* move the files but it's not the pattern that I want.

Here is how I'm calling the funcion:

moveOrDelete ".\source" ".\dest"

And here are the sample file names I'm using:

a.txt
z.txt
1.txt
.txt

1 Answer 1

2

The -Path argument doesn't understand regular expressions, it takes a string and can perform wildcarding but not complex string processing.

So, you need to check the name of each file against the regex with the -match operator. The following should help:

Function moveOrDelete($source, $dest)
{
    $aToZ = '^[a-zA-Z].*'
    $notALetter = '^[^a-zA-Z].*'
    Get-ChildItem -Path $source -Recurse | Where-Object { $_.name -match $aToZ } | Move-Item -Destination $dest
    Get-ChildItem -Path $source -Recurse | Where-Object { $_.name -match $notALetter } | Remove-Item
}

Here, you need to filter the file names with the Where-Object cmdlet, then pipe to the move or remove.

Sign up to request clarification or add additional context in comments.

2 Comments

Your ForEach-Object is unnecessary: you can pipe directly to Remove-Item. The same applies to Move-Item.
THANKS!! This fixed it. I ended up piping it like TheIncorribible recommended.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.