Function for list services on multiple servers

Answered Function for list services on multiple servers

  • Thursday, June 21, 2012 1:59 PM
     
      Has Code

    Hi

    I'm trying to write function to list all services with status 'Auto' on multiple servers. For now i have that:

    Function running_services{
        Param(
        [Parameter(Mandatory=$true,
                   ValueFromPipeline=$true,
                   HelpMessage='Input path to the file with server list')]
        [ValidateScript({Test-Path $_ -PathType 'leaf'})]
        $input_patch
        ,
        [Parameter(Mandatory=$true,
                   ValueFromPipeline=$true,
                   HelpMessage='Input path to the file where result will be written')]
        [ValidateScript({
        Test-Path $_ -PathType 'leaf'
        })]
        $output_patch
        )
        $servers = Get-Content $input_patch
        
        foreach($s in $servers)
        {
            $service = Write-Output $s
            $service += gwmi win32_service -ComputerName $s | where {$_.startmode -eq "Auto"} | Select-Object name,state,status | sort state
        }
        $service | Out-File $output_patch
    }

    and couple questions:

    1. I want to verify if output file exist if not create it so i made a:

    [Parameter(Mandatory=$true,
                   ValueFromPipeline=$true,
                   HelpMessage='Input path to the file where result will be written')]
        [ValidateScript({
        if(!(Test-Path $_ -PathType 'leaf')){new-item $output_patch -type file}
        })]
        $output_patch

    but when i try run got: running_services : Cannot validate argument on parameter 'output_patch'. Cannot bind argument to parameter 'Path' because it is null.r

    2. How to write the list to the file. Now it's not working, writing only host names.

All Replies

  • Saturday, June 23, 2012 9:49 PM
     
     Answered Has Code

    1. It won't work like that. You use proper variable for test, but for some reason - you do not for file creation... ;) Use $_ there too:

    function Test-MyPath {
    param (
        [Parameter(Mandatory = $true)]
        [ValidateScript({
            if (!(Test-Path $_ -PathType Leaf)) {
                New-Item -ItemType File -Path $_ -Force
            }
        })]
        [string]$Path
    )
        'Foo' | Add-Content @PSBoundParameters
    }

    2. If you are building strings it may be a good idea to force output of command to become one:

    $S = 'localhost'
    
    $service = Write-Output $s
    $service += gwmi win32_service -ComputerName $s | 
        where {$_.startmode -eq "Auto"} | 
        Select-Object name,state,status | 
        sort state | Out-String