How to Format Powershell Code on ML



  • How do I do this so it appears nice and readable on ML?



  • For any code, just lead with three backticks on the line before the code. And put three backticks on the line after the code is done.



  • @alex-olynyk said in How to Format Powershell Code on ML:

    function Repair-SophosUpdate {
    
        [cmdletbinding()]
    
        Param(
    
             [Parameter(Mandatory=$True)]
             [string]$computername
        )
        $Services = Get-Service -Name 'Sophos*'
    
        ForEach ($Service in $Services) {
    
            If (($Service.Name -like 'Sophos*') -and ($Service.Status -eq 'running')) {
    
                Restart-Service -Name $Service -PassThru -Verbose -Force
    
            }
             Else
             {
    
                Start-Service -Name $Service -PassThru -Verbose
            }
        }
    
    } ; Repair-SophosUpdate -Verbose
    

    When I run this I get

    PS C:\Users\aolynyk\Desktop> C:\Users\aolynyk\Desktop\Repair-SophosUpdate.ps1
    cmdlet Repair-SophosUpdate at command pipeline position 1
    Supply values for the following parameters:
    computername: localhost
    Restart-Service : Cannot find any service with service name 'System.ServiceProcess.ServiceController'.
    At C:\Users\aolynyk\Desktop\Repair-SophosUpdate.ps1:16 char:13
    +             Restart-Service -Name $Service -PassThru -Verbose -Force
    +             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : ObjectNotFound: (System.ServiceProcess.ServiceController:String) [Restart-Service], ServiceCommandException
        + FullyQualifiedErrorId : NoServiceFoundForGivenName,Microsoft.PowerShell.Commands.RestartServiceCommand
    

    I can restart the services as an admin but when I run the script as an admin I get the same error

    PS C:\WINDOWS\system32> Restart-Service 'Sophos Agent' -PassThru
    
    Status   Name               DisplayName                           
    ------   ----               -----------                           
    Running  Sophos Agent       Sophos Agent                          
    
    
    
    PS C:\WINDOWS\system32> Restart-Service 'Sophos Message Router' -PassThru
    
    Status   Name               DisplayName                           
    ------   ----               -----------                           
    Running  Sophos Message ... Sophos Message Router                 
    
    
    
    PS C:\WINDOWS\system32> 
    

    Maybe put this in a new thread so you get help?


Log in to reply