Home > front end >  powershell implement progressbar for filtered dirs
powershell implement progressbar for filtered dirs

Time:05-10


I created a script to copy file and dir/subdir in Powershell that works well.
Now I would like to try to implement it with a progressbar.
My directory structure is made in this way
test / dirfoo / file1, file2, subdir1, subdir2, ..  
     / dirbar / file1, file2, subdir1, subdir2, ..
     / @dirfoo / file1, file2, subdir1, subdir2, ..
     / @dirbar / file1, file2, subdir1, subdir2, ..
     / file1
     / file2
     / ..

SCRIPT

Function Copy-WithProgress
{
[CmdletBinding()]
Param
(
    [Parameter(Mandatory=$true,
        ValueFromPipelineByPropertyName=$true,
        Position=0)]
    $Source,
    [Parameter(Mandatory=$true,
        ValueFromPipelineByPropertyName=$true,
        Position=0)]
    $Destination
)

$Source=$Source.tolower()
$Filelist=Get-Childitem "$Source" –Recurse
$Total=$Filelist.count
$Position=0

foreach ($File in $Filelist)
{
    $Filename=$File.Fullname.tolower().replace($Source,'')
    $DestinationFile=($Destination $Filename)
    Write-Progress -Activity "Copying data from '$source' to '$Destination'" -Status "Copying 
    File $Filename" -PercentComplete (($Position/$total)*100)
    Copy-Item $File.FullName -Destination $DestinationFile
    $Position  
  }
 }

 $syncSource=c:\test
 $syncDest=d:\test

 Copy-WithProgress -Source $syncSource -Destination $syncDest

Now I would like to try to copy only the subdir and their files that have the character @ at the beginning of the name

To filter the names I usually make this way but I can't implement it in the copy-withprogress function

Get-ChildItem -Path $modSource | 
Where-Object { $_.Name -match '@' } | 
Copy-Item -Destination $modDest -Recurse -Force

How could I do?
Thanks

CodePudding user response:

Wrap the final call to Copy-Item with ForEach-Object so you can call Write-Progress immediately prior to copying:

Get-ChildItem -Path $modSource |
Where-Object { $_.Name -match '@' } |
ForEach-Object {
  Write-Progress -Status "Progress status message goes here" ...
  $_ | Copy-Item -Destination $modDest -Recurse -Force
}

If you simply wish to add optional name-based filtering to the existing function, do the following:

Add a -Filter parameter:

param(
    ...,

    [string]$Filter = '*'
)

And then change the statement where you resolve the file list to use the filter:

$Filelist = Get-Childitem "$Source" –Recurse |Where-Object { $_.Name -like $Filter }
  • Related