我創建了一個禁用 Windows 服務的腳本。
他們的數量可能超過 50 個服務。
有一些服務,其名稱可以追溯到以前的Windows版本; 由于這些服務在較新版本的 Windows 中更改了名稱。所以我使用if:如果 $Services 中存在服務名稱,它將被禁用。
有了這一切,腳本不起作用..是什么原因?
我懷疑在“ if($Service.Name)”
$Services = @(
"mpssvc"
"wscsvc"
"clipSVC"
#There are more services, but it's not necessary to show them here.
)
foreach ($Service in Services) {
if($Service.Name -NotIn $Services)
{
Stop-Service $Service
Set-Service $Service -StartupType Disabled
}
}
uj5u.com熱心網友回復:
讓我們遍歷代碼,看看問題出在哪里。
# An array containing service names
$Services = @(
"mpssvc"
"wscsvc"
"clipSVC"
#There are more services, but it's not necessary to show them here.
)
# Loop through the array. Pick a name one by one.
foreach ($Service in Services) {
# Compare the array contents with service's name. Here's the catch
if($Service.Name -NotIn $Services)
那么,怎么了?這是$Service.Name. 由于$Service是包含$services集合中當前專案的變數,因此它沒有.Name屬性。更重要的是,代碼會一一檢查集合是否包含其所有成員。它總是會的。
要禁用想要的服務,請獲取服務串列并將其與要禁用的服務串列進行比較。像這樣,
# An array containing service names
$ServicesToDisable = @(
"mpssvc"
"wscsvc"
"clipSVC"
)
# Get all running services
$RunningServices = Get-Service | ? {$_.Status -eq "Running"}
# Loop through running services. See if it is in the disable array
foreach($s in $RunningServices) {
if($s.Name -in $ServicesToDisable) {
Set-Service -Startuptype Disalbed -Name $s.Name
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/360777.html
