我发现一些帖子建议使用Start-Process -Wait
或管道.EXE到Out-Null
,这适用于.EXE文件,但我有一个foreach循环,其中包含内置PowerShell cmdlet。在下一行代码开始执行之前,我该如何确保循环完成?如何在下一个命令运行之前完成一个代码块完成 - Powershell V5
作为参考,我正在使用一种名为rclone的工具将文件/文件夹复制到我们的团队驱动器中,但它目前不支持复制空目录。解决方法是在所有空目录中创建一个临时文件,运行该工具的同步命令,运行另一个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
}
代码的工作,但我必须手动运行2同步命令,否则一些temp.xyz文件不会从球队的驱动器中删除。它似乎应该工作,因为它从本地股份中删除。不知道这是否是PowerShell或应用程序的问题。