Need help with a broken ForEach

This topic contains 5 replies, has 3 voices, and was last updated by Profile photo of Dave Wyatt Dave Wyatt 3 years, 1 month ago.

  • Author
    Posts
  • #13562
    Profile photo of Mark Anderson
    Mark Anderson
    Participant

    I am attempting to write a script that takes a list of IP address's, finds alive hosts, then checks to make sure that a specific service is installed. If the service is NOT installed it should be adding the IP address to the $notinstalled array. This is not working as I thought it should.

    Could someone tell me what I am doing wrong in that specific ForEach section? This script is a learning / work in progress as I have never written a powershell script before.

    I have attached the entire script, such as it is.

    Thanks.

    Try
    {
    ForEach ($entry in $alivehosts){
    	$svc = Get-Service -Display $sname -ComputerName $entry -ErrorAction SilentlyContinue
    	IF( -not $sname) {$notinstalled += $entry}
    	else { $sname + " is installed on " + $entry}
    	}
    
  • #13565
    Profile photo of Don Jones
    Don Jones
    Keymaster

    You're checking $sname. I don't see you defining it anywhere.

    If the service doesn't exist, $svc would be null. $sname presumably contains the name of the service you're looking for. It'll never be empty.

  • #13566
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    if (-not $sname) is never going to be True; $sname is a string you've defined. I assume you meant to do if (-not $svc) in that conditional.

  • #13573
    Profile photo of Mark Anderson
    Mark Anderson
    Participant

    ***Pounds head on desk***

    Can't believe I did that. ($sname VS $svc)

    Is it kosher to ask why the try-catch-finally is only catching and logging one error? Do I have to do a ForEach for each error?

    Thanks!

  • #13574
    Profile photo of Don Jones
    Don Jones
    Keymaster

    Well, you've suppressed the error by using -EA SilentlyContinue. You have to use -EA Stop to trigger Try/Catch. See our free ebook on error handling – under the "Resources" menu on the site.

  • #13578
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    Your try/catch block should probably be inside the foreach loop, not the other way around (unless you want the whole loop to abort as soon as an error occurs.)

You must be logged in to reply to this topic.