[英]PowerShell - Start rocopy only if all services have stopped
I'm new to PowerShell and was wondering if anyone can assist me with the following since I was unable to find any previous thread for this question on the site. 我是PowerShell的新手,我想知道是否有人可以为我提供以下帮助,因为我无法在该站点上找到有关该问题的任何先前主题。
Question: Is there a way to write out a robocopy command so that it will only start if the services in $stopservices have all stopped? 问题:有没有办法写出robocopy命令,以便仅在$ stopservices中的服务全部停止后才能启动? Below is what I have but at some points the service is still running when the robocopy starts and then errors out for "The process cannot access the file because it is being used by another process.". 以下是我所拥有的,但是在自动复制启动时某些时候该服务仍在运行,然后错误提示“该进程无法访问该文件,因为该文件正在被另一个进程使用。”。
<## Stop all services ##>
write-host `r`n "Stopping services on "$server `r`n
foreach ($service in $stopservices)
{
set-service $service -ComputerName $server -StartupType Disabled -Status Stopped -PassThru
}
<## Copy all files ##>
$robocopy = "{0} {1} {2} /XF {3} {4} {5} /XD {6} {7} /MIR /MT /TEE /LOG:{8}" -f $robocopy, $source, $destination, $logPath
Invoke-Expression $robocopy
Pause
If the services aren't stopping you could try using the Stop-Service
Cmdlet after Set-Service
. 如果服务没有停止,则可以尝试在Set-Service
之后使用Stop-Service
Cmdlet。
Get-Service -Name $service -ComputerName $server | Stop-Service -Force
Then you could wait for the services to stop by using the following while loop just before the Robocopy
. 然后,您可以通过在Robocopy
之前使用以下while循环来等待服务停止。
While($stopservices | Get-Service | ? {$_.Status -eq "Running" -or $_.Status -eq "Stopping"}){
Sleep -Seconds 5
}
This will sleep the script for 5 seconds if 1 of the services in $stopservices
are still running. 如果$stopservices
中的服务之一仍在运行,它将使脚本休眠5秒钟。 Once all services do not have a Running
or Stopping
status the Robocopy
will start. 一旦所有服务都不处于“正在Running
或“正在Stopping
状态,则Robocopy
将启动。 So the whole script might look something like this: 因此,整个脚本可能如下所示:
# Stop all services #
write-host `r`n "Stopping services on "$server `r`n
foreach ($service in $stopservices)
{
set-service $service -ComputerName $server -StartupType Disabled -Status Stopped -PassThru
Get-Service -Name $service -ComputerName $server | Stop-Service -Force
}
While($stopservices | Get-Service | ? {$_.Status -eq "Running" -or $_.Status -eq "Stopping"}){
Sleep -Seconds 5
}
# Copy all files #
$robocopy = "{0} {1} {2} /XF {3} {4} {5} /XD {6} {7} /MIR /MT /TEE /LOG:{8}" -f $robocopy, $source, $destination, $logPath
Invoke-Expression $robocopy
Pause
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.