0

I have a single folder filled with PDF's, all their filenames contain a Pxxx-xx number.

Examples:

"P418-04 hingeblock.pdf"
"P293-21 corner profile.pdf"
"P810-18 bench support.pdf
"R5511-01 coat hook.pdf"

I want to create a folder structure based on these numbers and place every file inside its own folder.

I figured out how to create the folders using a sample folder structure when I have the matches:

$ItemNames | ForEach-Object{
    Get-ChildItem -Path ("$TargetPath\000 Sample Folder") | Copy-Item -Destination ("$TargetPath\$_") -Recurse -Container 

I get as far as selecting the files:

Get-Item -Path ("$SourcePath") | ls | where Name -match '[PR]\d?\d\d\d-?\d?\d?'

Only, how do i make it list ONLY the matching part of the filename instead of the entire filepath?

"Get-Item" always show s a list with columns "mode", "lastwritetime" and "name" and outputs the full filelocation.

I only want a simple list of:

P418-04
P293-21
P810-18
R5511-01

So I can use that list to create the folder names.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
  • Try `^(?:.*/)?'[PR]\d{3,4}-?\d{0,2}(?:\.\w+)?$'`. Maybe you need `\d{3}-\d{2}` instead of `\d{3,4}-?\d{0,2}` acc. to your description. – Wiktor Stribiżew Jul 14 '20 at 13:51
  • PLEASE, show two or three sample file names and the desired dir names you want from those items. you have not shown enuf detail about the inputs to test code ... [*grin*] – Lee_Dailey Jul 14 '20 at 13:59
  • `Get-Item -Path ("$SourcePath") | ls` this seems extremely unnecessary. `ls` is already an alias of `Get-ChildItem` and without `Get-Item` it would do the same thing. Do `Get-ChildItem $SourcePath` – Nico Nekoru Jul 14 '20 at 16:11

1 Answers1

0

You can try this code:

$prefixes = Get-ChildItem "Filepath" -Directory | Foreach {$_.Name.ToString().Split(" ")[0]}

Now $prefixes will contain those beggining pattern matches.

Wasif
  • 14,755
  • 3
  • 14
  • 34
  • `$_.Name` is already a string, so there is no need for `ToString()` there. As aside, for newcomers, it is helpful not to shorten `ForEach-Object` into `ForEach`, because there is always much confusion between the two ([Difference between foreach and ForEach-Object in powershell](https://stackoverflow.com/a/29148614/9898643)) – Theo Jul 14 '20 at 19:53