im writing a script to get services from local and remote machines. I’ve had to split the wmi call for local and remote machines (remote machines require different credentials). I want to output them as System.Object. How do i create a function for the output of system.object?
heres the code i have so far:
$objServicecol = @()
# how do i get AddService object back
Function AddServiceObjects
{
ForEach ($Service in $Services)
{
$objService = New-Object System.Object
$objService | Add-Member -MemberType NoteProperty -Name SystemName -Value $Services.SystemName
$objService | Add-Member -MemberType NoteProperty -Name Name -Value $Services.Name
$objService | Add-Member -MemberType NoteProperty -Name StartMode -Value $Services.StartMode
$objService | Add-Member -MemberType NoteProperty -Name StartName -Value $Services.StartName
$objService | Add-Member -MemberType NoteProperty -Name Status -Value $Services.Status
#$objServiceCol += $objService
AddServiceObjects += $objService
}
}
# Executes local WMI
If ($Servers -contains "localhost")
{
$Services = Get-WMIObject Win32_Service -ComputerName "localhost" | Select-Object SystemName, Name, StartMode, StartName, Status
AddServiceObjects $Services
}
...#execute remote wmi...
In .NET, System.Object is the root of the inheritance hierarchy so any type you output can be treated as a System.Object. You might want to consider creating a
psobjectinstead of aSystem.Objectin your loop (and simplify it):Note that by virtue of not assigning the
New-Objectoutput to a variable it will get output from the function – one object for every iteration through the loop. Also note that your foreach iteration variable was$servicebut your were referencing the global$Servicesin yourNew-Objectcommand.