The Author Online Book Forums are Moving

The Author Online Book Forums will soon redirect to Manning's liveBook and liveVideo. All book forum content will migrate to liveBook's discussion forum and all video forum content will migrate to liveVideo. Log in to liveBook or liveVideo with your Manning credentials to join the discussion!

Thank you for your engagement in the AoF over the years! We look forward to offering you a more enhanced forum experience.

SOU630 (5) [Avatar] Offline
#1
I'm working on a script that transfers files between directories. I've got a flag that if invoked, PowerShell deletes everything in the destination directories before adding the new content.

However, the script is executing faster than remove-item can clear the directories. How do I pause the script and have it wait for remove-item to finish?

Start-sleep works somewhat, but if there's enough items to delete, it starts the script back up before remove-items is done. (Experienced that already.)

Thanks
Kiron (38) [Avatar] Offline
#2
Re: Waiting for commands to execute in scripts
Here is an idea.
$command contains the scriptBlock that gets child items depending on your objective:
a) remove all items (directories and files), or
b) remove all files only
Then the scriptBlock's return is compared to check for the presence of qualifying child items.
*Note that $command is not executed when it is declared.

# get all items (directories and files) in $destination recursively to remove
$command = {Get-ChildItem $destination -recurse -force}

# get all files only in $destination recursively to remove
$command = {Get-ChildItem $destination -recurse -force | Where-Object {!$_.PSIsConainer}}

# execute while qualifying child items exists
While (!!(& $command))
{
# get all qualifying child items and remove them
& $command | Remove-Item -force
}