Powershell - excluding folders from string

I have a huge directory (several thousand folders), for example:

...\94000\abc\def\hig
...\95000\abc\def\hig 
...\96000\abc\def\hig
...\97000\abc\def\hig
...

      

So there is one part of the path that alternates, but the rest of the folder structure is the same. There are also many subfolders under abc and def, etc.

What I need to do is copy a specific file from the let say folder "hig".

I am completely new to Powershell, but I managed to put together the following:

$destination = "C:\Users\etc..."
   $source = "B:\94000"
   Get-ChildItem $source -Filter "LIVE*.docx" -File -Recurse | Foreach {
          Copy-Item $_.FullName $destination
   }

      

I know this is very simple, but it really works. The problem is that it is quite slow to give the number of folders to sift through.

Is there a way to speed things up? I thought to script the skipped folders which I know does not contain the file I want.

I was also wondering if I can use a wildcard in the path so that I can identify the exact folders, for example: \ 9 * 000abc \ Protect \ HIG

But it didn't work.

Any idea is greatly appreciated!

+3


source to share


3 answers


You can definitely use wildcards as you implied. You can do:

Get-ChildItem B:\9*000\abc\def\hig\live*.docx

      

This should return files like:



B: \ 94000 \ a \ protection \ HIG \ livesite.docx
B: \ 94000 \ a \ protection \ HIG \ live.docx
B: \ 95000 \ a \ protection \ HIG \ livefreeordie.docx
B: \ 96000 \ a \ protection \ HIG \ liverandonions.docx
B: \ 96000 \ abc \ def \ hig \ livesinmomsbasement.docx

Then you can just direct the ones that are on Copy-Item -Destination $destination

, for example:

Get-ChildItem B:\9*000\abc\def\hig\live*.docx | Copy-Item -Destination $destination

      

+2


source


With Get-ChildItem

you can use -Exclude

with string to skip folders / files with. This can speed up the process. Also, if you are using Powershell 2.0 Get-ChildItem

it is very slow. Upgrading to Powershell 3.0 or higher will make it much faster.



0


source


Wildcards in the path are supported by default. Plus, your filter is the fastest way to parse files (versus something like Where-Object

). Your call ForEach-Object

can actually slow you down. The other answer is correct to speed things up in this regard, since it can take input into the pipeline without adding another iteration step.

$destination = 'C:\Users\etc\'
$source = 'B:\94*00'
Get-ChildItem -Path $source -Filter "LIVE*.docx" -File -Recurse |
  Copy-Item -Destination $destination

      

0


source







All Articles