Here's a simpler/more compact way of doing it:
Get-ChildItem | ?{$_.Name -match '(\D+)\d*\.txt'} | %{
md $matches[1] -ea SilentlyContinue
Move-Item $_ $matches[1]
}
A purist might say that it's "better practice" to Test-Path before attempting to create the directory, but I generally prefer more compact code; if no other decisions hinge on whether the directory already exists, it's quicker to just attempt to create it each time and ignore errors.
A couple of explanatory notes, in response to the OP's comment:
?{ }
is shorthand for Where-Object, which filters on a condition, i.e. only objects that meet the specified condition are passed down the pipeline. So in this case, it takes the listing of the current directory and selects only the objects whose Name property matches the regex.After the -match operator is used, the matches are stored in the automatic array variable $matches. $matches[0] contains the entire matched part of the string, and indices starting with 1 contain the match groups, numbered from the ordinal position of the left parenthesis, i.e. $matches[1] is the match group beginning with the first left parenthesis encountered, $matches[2] is the match group beginning with the second left parenthesis, etc.
In this case there is only one match group, and $matches[1] contains the part of the string matched by
(\D+)
, i.e. the sequence of consecutive non-digit characters prior to the first digit or dot.