我做错了什么?如果服务状态停止,它将不会重命名文件夹?
$computers =("GT08544","GT08545")
$arrService = Get-Service -Name Spooler
Get-Service -ComputerName $computers Spooler | Select Displayname, Status
if ($arrService.Status -eq 'running')
{
Exit
}
If ($arrServie.Status -eq 'stopped')
{
Rename-Item \\GT08324\c$\Ken Ken.$(Get-Date -format "yyyy_MM_dd_hh_mm_ss") -Force
}
(Write-Host "Renaming completed successfully")
答案1
下面的代码将允许您执行您想要的操作。此代码对每个服务器单独运行服务检查。然后,如果该目录存在,它会重命名该目录。如果它们都停止,则会事先进行测试路径检查,如果文件夹已重命名,则第二次迭代不会出错。
$computers =("GT08544","GT08545")
foreach ($computer in $computers)
{
Invoke-Command -ComputerName $computer -ScriptBlock
{
$arrService = Get-Service -Name Spooler
Write-Host "Spooler Service is $arrService.Status on $computer"
if ($arrService.Status -eq "Running")
{
Write-host "Running. No Action being taken."
}
if ($arrService.Status -eq "Stopped")
{
if (Test-Path -Path "\\GT08324\c$\Ken")
{
Rename-Item \\GT08324\c$\Ken Ken.$(Get-Date -format "yyyy_MM_dd_hh_mm_ss") -Force
}
else
{
Write-host "The path does not exist or has already been renamed"
}
}
}
}
编辑以解决以下评论。此版本在每个服务器上运行服务检查。如果服务停止,它会添加到变量 $count。最后,如果 $count 变量为 2(意味着两个服务器都有一个停止的后台处理程序服务,那么只有满足此条件时它才会重命名文件夹。应该只需复制/粘贴到 powershell ise 或脚本中而无需编辑。
$computer1 = "GT08544"
$computer2 = "GT08545"
$serviceCount1 = ""
$serviceCount2 = ""
$Response = Invoke-Command -ComputerName $computer1 {
$arrService = Get-Service -Name Spooler
$count=0
if ($arrService.Status -eq "Running")
{
Write-host "$Using:computer1 - Running. No Action being taken."
}
if ($arrService.Status -eq "Stopped")
{
Write-Host "$Using:computer1 - Service is Stopped. Increasing Service count by 1."
$count++
Write-Host $count
}
Return @{serviceCount1 = $count}
}
$Response.GetEnumerator() | % { Set-Variable $_.Key -Value $_.Value}
$Response2 = Invoke-Command -ComputerName $computer2 {
$arrService = Get-Service -Name Spooler
$count=0
if ($arrService.Status -eq "Running")
{
Write-host "$Using:computer2 - Running. No Action being taken."
}
if ($arrService.Status -eq "Stopped")
{
Write-Host "$Using:computer2 - Service is Stopped. Increasing Service count by 1."
$count++
Write-Host $count
}
Return @{serviceCount2 = $count}
}
$Response2.GetEnumerator() | % { Set-Variable $_.Key -Value $_.Value}
$totalStoppedServices = $serviceCount1 + $serviceCount2
Write-Host "Total Stopped Services: $totalStoppedServices"
if($totalStoppedServices = 2){
if(test-path -Path "\\GT08324\c$\Ken"){
Rename-Item \\GT08324\c$\Ken Ken.$(Get-Date -format "yyyy_MM_dd_hh_mm_ss") -Force
}
}
else{
Write-host "Service is running on one or more servers. No Action."
}