Error in Powershell with foreach loop
hi,
i use piece of code check if 1 or more services running on list of servers. if present , not running start service. list of servers in textfile. works well, seems check 1 time many, generates error :
get-wmiobject : cannot validate argument on parameter 'computername'. argument null or empty. supply argument th
@ not null or empty , try command again.
@ d:\scripts\ps\servicetest2.ps1:17 char:63
+ $objwmiservice = get-wmiobject -class win32_service -computer <<<< $computer
+ categoryinfo : invaliddata: (:) [get-wmiobject], parameterbindingvalidationexception
+ fullyqualifiederrorid : parameterargumentvalidationerror,microsoft.powershell.commands.getwmiobjectcommand
the code is:
# setup trap catch exceptions
trap [exception]
{
write-error $("trapped: " + $_.exception.message);
}
# read computers text file
$computers = (get-content d:\scripts\computers.txt);
$start = $true;
# setup service array service names want check running
$servicearray = 'spooler';
# powershell knows it's array working simple
foreach($computer in $computers)
{
write-host "checking $computer";
$objwmiservice = get-wmiobject -class win32_service -computer $computer
foreach($service in $objwmiservice)
{
# check each service specicfied in $servicearray
foreach($srv in $servicearray)
{
if($service.name -eq $srv)
{
write-host "$srv present on $computer.";
if($service.state -eq "running")
{
write-host "$srv running on $computer";
}
else
{
write-host "$srv not running on $computer";
# if $start true script attempt start service if stopped
if($start -eq $true)
{
# attempt start current service on current computer
$serviceinstance = (get-wmiobject -computer $computer win32_service -filter "name='$srv'");
$name = $serviceinstance.name;
write-host "attempting start $name on $computer."
$serviceinstance.startservice() | out-null;
# refresh object instance new data
$serviceinstance = (get-wmiobject -computer $computer win32_service -filter "name='$srv'");
$state = $serviceinstance.state;
write-host "$name ""$state"" on $computer.";
end if
}
}
}
}
}
}
what can rid of error?
i hope 1 can me out
thanks,
jansietje
this structure:
if ($computer) {code}
ensures code not run on lines only a character return. if possible lines have 1 or more spaces, need use trim() function.
$computer = $computer.trim() if ($computer){code}
richard mueller - mvp directory services
Windows Server > Windows PowerShell
Comments
Post a Comment