-1

I am newbie to powershell scripting and I did go through lot of articles here and not able to get much help.Can someone help me out on how to put files in specific folders:

file name example:

2008_11_chan_3748_NB001052_031_SIGNED.pdf 

put it in folders:

2008/11/NB001052-031/....

if it ends with "draft", e.g.

2008_11_chan_3748_NB001052_031_Draft.pdf 

put it in a separate draft folder as below

 2008/11/NB001052-031/Draft

Any help is really appreciated. Thanks in advance.

1 Answers1

0
Push-Location c:\2009

Get-ChildItem -File -Filter *_*_*_*_*_*.pdf |
  Move-Item -Destination {
    $tokens = $_.Name -split '_'
    $subdirNames = $tokens[0,1,4]
    if ($tokens[-1] -like 'Draft.*') { $subdirNames += 'Draft' }
    (New-Item -Force -Type Directory ($subdirNames -join '\')).FullName
  } -WhatIf

Pop-Location

Note: The -WhatIf common parameter in the command above previews the move operation, but the target subfolders are created right away in this case. Remove -WhatIf once you're sure the operation will do what you want.

(Partial) explanation:

  • The Get-ChildItem call gets those files in the current directory whose name matches wildcard pattern *_*_*_*_*_*.pdf.

  • Move-Item -Destination uses a delay-bind script block ({ ... }) to dynamically determine the target path based on the current input object, $_, which is of type System.IO.FileInfo

  • The code inside the script block uses the -split operator to split the file name into tokens by _, extracts the tokens of interest and appends Draft as appropriate, then creates / returns a subdirectory path based on the \-joined tokens joined in order to output the target directory path; note that -Force creates the directory on demand and quietly returns an existing directory.

mklement0
  • 382,024
  • 64
  • 607
  • 775