在更改密码之前搜索某些服务

时间:2015-03-04 20:38:21

标签: powershell service

我想更改名称中包含“syn”的所有密码。我知道你可以通过我正在做的状态来做到这一点,但无论如何通过搜索字符串的名称来做到这一点?

$acctname = "domain\user"
$svcpwd  = "password"
#Text file
$servers = (gc serverlist.txt) 
#from AD 
#Import-Module ActiveDirectory
#$servers = (Get-ADComputer -Filter *)

foreach ($server in $servers) 
{
  #Query service
  gwmi win32_service -computername $server | % { 
  if ($_.StartName -eq $acctname)
  {
    $servicename = $_.Name
    write-host "updating $servicename"
    $svcnm = gwmi win32_service -computername $server -filter "name='$servicename'"
    #Update Service
    $svcnm.change($null,$null,$null,$null,$null,$null,"$UserName",$svcpwd,$null,$null,$null) 
    #Stop Service
    $svcnm.stopservice
    #Start Service
    $svcnm.startservice
  }
}

1 个答案:

答案 0 :(得分:0)

要获取以特定名称开头的所有服务,您可以将$_.Name -like '*syn*'添加到if检查中,如此

if (($_.StartName -eq $acctname) -and ($_.Name -like '*syn*'))

只有当您要查找的服务的StartName等于$acctname且其中包含'syn'的名称时,新的if语句才会触发,这是您的完整代码可能是什么样的

$acctname = "domain\user"
$svcpwd  = "password"
#Text file
$servers = (gc serverlist.txt) 
#from AD 
#Import-Module ActiveDirectory
#$servers = (Get-ADComputer -Filter *)

foreach ($server in $servers) 
{
  #Query service
  gwmi win32_service -computername $server | % { 
  if (($_.StartName -eq $acctname) -and ($_.Name -like '*syn*'))
  {
    $servicename = $_.Name
    write-host "updating $servicename"
    $svcnm = gwmi win32_service -computername $server -filter "name='$servicename'"
    #Update Service
    $svcnm.change($null,$null,$null,$null,$null,$null,"$UserName",$svcpwd,$null,$null,$null) 
    #Stop Service
    $svcnm.stopservice
    #Start Service
    $svcnm.startservice
  }
}