[英]How to make a code block finish completely before next command runs - Powershell V5
我發現了一些建議使用Start-Process -Wait
或將.EXE傳遞到Out-Null
帖子,這對.EXE文件效果很好,但是我有一個包含內置PowerShell cmdlet的foreach循環。 如何確保在下一行代碼開始執行之前,循環首先完全完成?
作為參考,我正在使用一個名為rclone的工具將文件/文件夾復制到我們的團隊驅動器中,但是它目前不支持復制空目錄。 解決方法是在所有空目錄中創建一個臨時文件,運行該工具的sync命令,運行另一個powershell命令以從本地目錄中刪除該臨時文件,然后重新運行該工具的sync命令以將其從團隊驅動器中刪除。 下面的代碼參考:
$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
}
代碼可以工作,但是我必須手動運行2nd sync命令,否則某些temp.xyz文件不會從團隊驅動器中刪除。 似乎應該起作用,因為它已從本地共享中刪除。 不確定這是PowerShell還是應用程序問題。
除非應用程序執行異常操作,否則以正常的PowerShell命令運行該應用程序對您來說應該可以正常工作:
rclone.exe sync "\\servername\e`$\rootshare\$share" "$($share + ':')"
如果您需要應用程序的完整路徑,並且路徑中有空格,請使用invoke特殊字符:
& "C:\program files\rclone\rclone.exe" sync "\\servername\e`$\rootshare\$share" "$($share + ':')"
這將使PowerShell像對待任何本機PowerShell命令一樣,等待應用程序的執行。 您可以根據需要重定向輸出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.