Question

I am working on a PS script that does the following for each machine where hostname is a line in a file

  1. Stop Service
  2. Check .ini file for port number
  3. CONDITIONALLY update port number based on existing value
  4. Start Service

Where I am having a hard time is understanding the syntax for step 3: If 'ServerPort=443', change it to 'ServerPort=444' ElseIf 'ServerPort=444', change it to 'ServerPort=443'

Here is where I am so far:

$servers = Get-Content 'C:\Servers.txt'

   foreach ($server in $servers){
   # stop service and wait.
   (get-service -ComputerName $server -Name SERVICENAME).stop

   # Logic to see string. Looking for "ServerPort=%". Detect if Server port is 444 or 443. If one, set to other

   # Get Port from config file
   $port = get-content C:\config.ini | Where-Object {$_ -like 'ServerPort=*'}
    # Conditionally update port

    IF ($port -eq "ServerPort=443")
    {
        # update to 444
    }
    ELSEIF ($port -eq "ServerPort=444")
    {
        # update to 443
    }
    ELSE
    {
        Write-Host "Value not detected within Param"
    }

    #start service
    (get-service -ComputerName $server -Name SERVICENAME).start
}

Based on what I have going on here, I think that the syntax would have to REOPEN the file, re-search for the line and then update it... Quite inefficient when going over the network... perhaps there is a much more logical and simple way to go about this?

Your help is GREATLY appreciated!

-Wes

Was it helpful?

Solution

I rewrote some of your script. Check this out:

# Define the name of the service to stop/start
$ServiceName = 'wuauserv';
# Get a list of server names from a text file
$ServerList = Get-Content -Path 'C:\Servers.txt';

foreach ($Server in $ServerList){
    # Stop service and wait
    Get-Service -ComputerName $Server -Name $ServiceName | Stop-Service;

    # Logic to see string. Looking for "ServerPort=%". Detect if Server port is 444 or 443. If one, set to other

    # Read the config.ini file into $ConfigFile variable
    $ConfigFilePath = "\\$Server\c$\config.ini";
    $ConfigFile = Get-Content -Path $ConfigFilePath -Raw;

    if ($ConfigFile -match 'ServerPort=443')
    {
        # Change ServerPort to 444
        Set-Content -Path $ConfigFilePath -Value ($ConfigFile -replace 'ServerPort=443', 'ServerPort=444');
    }
    elseif ($ConfigFile -match 'ServerPort=444') {
        # Change ServerPort to 443
        Set-Content -Path $ConfigFilePath -Value ($ConfigFile -replace 'ServerPort=444', 'ServerPort=443');
    }
    else {
        Write-Host -Object ('Could not find matching ServerPort value in {0}' -f $ConfigFilePath);
    }

    Get-Service -ComputerName $server -Name $ServiceName | Start-Service;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top