Niag Ntawv
Niag Ntawv

Reputation: 337

How to make a code block finish completely before next command runs - Powershell V5

I found a few posts recommending either using Start-Process -Wait or piping the .EXE to Out-Null, which works well for .EXE files but I have a foreach loop that contains built-in PowerShell cmdlets. How do I go about making sure the loop finishes completely first before the next lines of code starts executing?

For reference, I am using a tool called rclone to copy files/folders into our team drives but it currently does not support copying empty directories. The work around is to create a temp file in all empty directories, run the tool's sync command, run another powershell command to delete the temp files from the local directories, then re-run the tool's sync command to remove it from the team drive. Code reference below:

$shares = "Office Operations","Training"

# iterate through each share and output full path name to empty shares
$emptyDirs = foreach ($share in $shares) {
    Get-ChildItem -Path "\\servername\e`$\rootshare\$share" -Recurse -Directory | Where-Object {$_.GetFileSystemInfos().Count -eq 0} | select FullName 
}

# iterate through each empty directory and create a temp.txt file with a random string
$emptyDirs | % {new-item $_.FullName -ItemType file -name temp.xyz -value "This is a test string"}

# initial rclone sync to copy over directory with temp.txt file
foreach ($share in $shares) {
    Start-Process "C:\program files\rclone\rclone.exe" -ArgumentList "sync `"\\servername\e`$\rootshare\$share`" `"$($share + ':')`"" -Wait -NoNewWindow
}

# iterate through each empty folder, cd accordingly and delete all .txt files
$emptyDirs | % {   
    Set-Location $_.FullName
    Remove-Item * -Include *.xyz
}

# second rclone sync to remove temp.txt file while maintaining folder structure
foreach ($share in $shares) {
    Start-Process "C:\program files\rclone\rclone.exe" -ArgumentList "sync `"\\servername\e`$\rootshare\$share`" `"$($share + ':')`"" -Wait -NoNewWindow
}

Code works, but I have to manually run the 2nd sync command otherwise some temp.xyz files are not deleted from the team drives. It seems like it should work because it is removed from the local shares. Not sure if this is an issue with PowerShell or the app.

Upvotes: 0

Views: 328

Answers (1)

JasonMArcher
JasonMArcher

Reputation: 14991

Running the application as a normal PowerShell command should work just fine for you, unless the application does something unusual:

rclone.exe sync "\\servername\e`$\rootshare\$share" "$($share + ':')"

If you need the full path to the application and it has spaces in the path, then use the invoke special character:

& "C:\program files\rclone\rclone.exe" sync "\\servername\e`$\rootshare\$share" "$($share + ':')"

This will make PowerShell wait for the execution of the application just like it would for any native PowerShell command. You can redirect the output if you need to.

Upvotes: 0

Related Questions