Sunday, 8 March 2020

Create a custom PSObject in Powershell

Hey,

Want to create PSCustom Objects in Powershell? But why?
PowerShell is Object oriented, so the output most of the times would be in objects that can still be utilized for additional operations like methods or manipulation of the output to our desired needs.

So, a PSObject could be your way of creating a placeholder of Members which you need into an Object that can give you a desired output.

Simply, it's an Object where you can feed data from other variables and manage it with benefits of an Object than a string.

A small demo of an Object and not-Object

netstat -ano | find "80" -> checks and gives the output in text. [not-Object]

Similarly

Get-service -name Bits | select Name, Status -> output would be an Object [Object]



Method 1

Lets create a simple PSObject and build it from two sources and populate the Obj
1.ComputerName
2.OS Information

  #Declare the computername as localhost
$computername = "localhost"
  
  # get the OS
  $os = get-wmiobject win32_operatingsystem -computername $computername
  
  # create a new object
  $obj = new-object psobject
  
  # add properties
  $obj | add-member noteproperty ComputerName $computername
  $obj | add-member noteproperty BuildNumber ($os.buildnumber)
  $obj | add-member noteproperty Caption ($os.Caption)


Output:
$obj would contain the information from the sources as one data collector.






 Method 2

A different way to create a PSObject


$obj = [PSCustomObject]@{
 Property1 = 'one'
 Property2 = 'two'
 Property3 = 'three'
 }


Output:

 

Adding some or our needs.

$obj = [PSCustomObject]@{
 BitsStatus = (get-service -name bits).Status
 HostsPath = (test-path c:\windows\system32\drivers\etc\hosts)
 PSVersion = ($PSVersionTable.PSVersion)
 }


Output:
 




Method 3

Populate in a Loop.
This is the most used requirement when the query is against multiple targets.

#List of computers
$hosts = Get-Content C:\RunSpace\ServerList.txt

#Array Collector
$HostChanges = @()

#querying each host
foreach($host_ in $hosts)
{

$obj = [PSCustomObject]@{
 Hostname = $host_
 BitsStatus = (get-service -name bits).Status
 HostsPath = (test-path c:\windows\system32\drivers\etc\hosts)
 PSVersion = ($PSVersionTable.PSVersion)
 }
 # appending obj
 $HostChanges += $obj

}
#Final output outside of for.
$HostChanges



Output:



  

-Happy Scripting 

No comments:

Post a Comment