[英]Disable exists Winsows services - PowerShell
我创建了一个禁用 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
}
}
让我们看一下代码,看看问题出在哪里。
# 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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.