In addition to what has been said already, I would strongly suggest to improve your function to be an advanced function as follows:
function Get-SqlServerInstance {
param (
[Parameter(
ValueFromPipeline = $true,
ValueFromPipelineByPropertyName = $true
)]
[string]$Computer = "localhost" # (default)
)
process {
Get-WmiObject win32_Service -Computer $Computer | where {
$_.DisplayName -match "SQL Server"
}
}
}
Then you can do this:
$instances = $servers | where {
Test-Connection $_ -Count 1 -Quiet
} | Get-SqlServerInstance | select -Unique -ExpandProperty Name
"Instans/er: $($instances -join ', ')"
If that is too long for you, wrap that in a small helper function:
function Print_ServiceStatus ([string[]]$servers) {
$instances = $servers | where {
Test-Connection $_ -Count 1 -Quiet
} | Get-SqlServerInstance | select -Unique -ExpandProperty Name
Write-Host "Instans/er: $($instances -join ', ')"
}
But, I am very sure it would make sense to output the Computer name too:
$servers | Get-SqlServerInstance | select PSComputerName, Name
IMHO, this would be the best practice and most "PowerShell-ish" way to do it.
Benefits:
Get-SqlServerInstance is a more appropriate name describing what the function does
- The function now returns objects, not strings (the way to go in PowerShell!)
- It works with the pipeline now (always preferred for performance)
- The
Test-Connection is not really part of the function's purpose. Your function should throw if it cannot connect! So I moved it to outside the function.
format-list