Powershell Script help

Hi All
I need some guidance with this script I have been working on for some time. Basically what the script does in its simplest terms is look at a list of servers and either start/stop services based on the arguments in the array. I am trying to make this a bit more scalable by pulling in server/service/Some_other_script. then once the operation is complete write out to a log file.

From my original script I have added a line.split  with 3 current variables using a comma as the delimiter. Im just having problems figuring out how to correctly pass these values in to the array and make it work. The code below is for my service restart script I have been working on. The original script uses the write-host cmdlet to post everything to the console. I am trying to remove that for obvious reasons.
Input file format is
Server_Name,W3SVC,SomePS.ps1

The main script is as follows.


# Setup trap to catch exceptions
trap [Exception]
{
      write-error $("TRAPPED: " + $_.Exception.Message);
}
 

$computers = Get-Content C:\scripts\servers.txt;

$computer = $line.split(',')[0]
$ServiceName = $line.split(',')[1]
$Operation = $line.split(',')[2]
 
# Setup the Service array with the service names we want to check are running
$serviceArray = '$ServiceName';
 
# Powershell Array
foreach($computer in $computers)
{
      #Write-Host "Checking $computer";
      $objWMIService = Get-WmiObject -Class win32_service -computer $computer
 
      foreach($service in $objWMIService)
      {
            # Check each service in $serviceArray
            foreach($srv in $computers)
            {
                  if($service.name -eq $srv)
                  {
                  
                        if($service.state -eq "running")
                        {
                        
                        }
                        else
                        {
                              
                              if($start -eq $true)
                              {
                                    
                                    $serviceInstance = (Get-WmiObject -computer $computer Win32_Service -Filter "Name='$srv'");
                                    $name = $serviceInstance.Name;
                                    
                                    $serviceInstance.StartService() | Out-Null;
                                    # Refresh the object instance
                                    $serviceInstance = (Get-WmiObject -computer $computer Win32_Service -Filter "Name='$srv'");
                                    $state = $serviceInstance.State;
                                    Write-Host "$name is ""$state"" on  $computer." >>C:\scripts\log.txt;
                              }
                        }
                  }
            }
      }
}
AjarnJonesyAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

QlemoBatchelor, Developer and EE Topic AdvisorCommented:
There are so many errors in that script that I don't know where to start.

$line is never set up, but that doesn't matter as you aren't using the resulting vars anyway ...

The usual way to read such a delimited file is by - import-csv! In your case (no column headers, comma-separated):
import-csv 'C:\scripts\servers.txt' -delimiter ',' -Header Computer, ServiceName, Operation

Open in new window

0
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
This is the revised code, but it does not contain the "operation" to perform. Don't know how you want that included here?
# Setup trap to catch exceptions
trap [Exception]
{
      write-error $("TRAPPED: " + $_.Exception.Message);
}

$start = $true
 
import-csv 'C:\scripts\servers.txt' -delimiter ',' -Header Computer, ServiceName, Operation | % {
  #Write-Host "Checking $computer"
  $objWMIService = Get-WmiObject -Class win32_service -computer $computer -Filter = "Name='$($_.ServiceName'")
  if ($objWMIService.State -eq "running")
  {
  } else {
    if ($start)
    {    
      $objWMIService.StartService() | Out-Null
      $objWMIService = Get-WmiObject -Class win32_service -computer $_.Computer -Filter = "Name='$($_.ServiceName'")
      Write-Output "$($objWMIService.Name) is ""$($objWMIService.state)"" on $($_.Computer)" >> C:\Scripts\log.txt
    }
  }
}

Open in new window

0
footechCommented:
Qlemo, is looks like you're headed the same way I was.  Here's my take.
# Setup trap to catch exceptions
trap [Exception]
{
      write-error $("TRAPPED: " + $_.Exception.Message);
}
 

$computers = Import-CSV C:\scripts\servers.txt
#Assuming headers of "name","service","operation"

foreach($computer in $computers)
{
    #Write-Host "Checking $computer";
    $objWMIService = Get-WmiObject -Class win32_service -computer $computer.name -filter "name = '$($computer.service)'"
    if($computer.operation -eq "start")
    {
        if($objWMIService.state -ne "Running")
        {
            $objWMIService.StartService() | Out-Null;
            # Refresh the object instance 
            $state = (Get-WmiObject Win32_Service -Filter "Name = '$($computer.service)'" -computer $computer.name).state
            Write-Output "$($computer.service) is ""$state"" on $($computer.name)" | Out-File C:\scripts\log.txt -append
        }
    }
    elseif($computer.operation -eq "stop")
    {        
    # do something
    }
    elseif($computer.operation -eq "restart")
    {        
    # do something
    }    
}

Open in new window

0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
AjarnJonesyAuthor Commented:
I'm not sure why I have so much trouble getting my head around Powershell.. But any way..
Thanks for the responses . Basically with the third entry in the servers.txt  Operation I want to basically be able to use that to call another Powershell Script. In this case, if I have a server then service listed. Lets say starting W3SVC the I want to call a powershell script that will invoke-webrequest to test the site.
So its basically Look at the server name, check the service w3svc and start then call a separate powershell script that will do something simple like PS C:\> Invoke-WebRequest http://mysite.com.... So essentially all I am trying to do with operation is call another powershell script... I'm trying to make this as scalable as possible where if I need to call different scripts with Operation (depending on the server and its requirements) I can go that route.   not sure that's the best way to do it but it is/has been a learning experience.

Thanks
0
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
Should Operation get applied only if the service is not running yet? Then insert as line 20 in my code:
      . .\$_.Operation

Open in new window

0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Development

From novice to tech pro — start learning today.