[英]Disable exists Winsows services - PowerShell
I created a script that disables Windows services.我创建了一个禁用 Windows 服务的脚本。
Their number may exceed 50 services.他们的数量可能超过 50 项服务。
There are some services whose name goes back to previous versions of Windows;有些服务的名称可以追溯到以前版本的 Windows; As these services changed their name in newer versions of Windows.由于这些服务在 Windows 的较新版本中更改了名称。 So I used if
: If the service name is present in $Services, it will be disabled.所以我使用了if
:如果服务名称存在于 $Services 中,它将被禁用。
With all this, the script does not work.. what is the reason?有了这一切,脚本不起作用..是什么原因?
I suspect in " if($Service.Name)
"我怀疑在“ 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
}
}
Let's walk through the code and see where the problem is.让我们看一下代码,看看问题出在哪里。
# 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)
So, what's wrong?那么,怎么了? It's the $Service.Name
.这是$Service.Name
。 Since $Service
is the variable containing the current item from the $services
collection, it doesn't have a .Name
property.由于$Service
是包含$services
集合中当前项目的变量,因此它没有.Name
属性。 What's more, the code is checking one by one if the collection contains all of its members.更重要的是,代码会一一检查集合是否包含其所有成员。 Which it always will.它总是会的。
To achieve disabling of wanted services, get a list of services and comnpare that to the list of services to disable.要禁用所需服务,请获取服务列表并将其与要禁用的服务列表进行比较。 Like so,像这样,
# 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.