Object, not Just Text (PowerShell)
Jul 29th 2007Desmond LeePowerShell
Object, object, object. This is one word that must get into the head of anyone trying to learn how PowerShell really works. Although on the surface everything is presented textually, objects are the way to go all over PowerShell. Trivial but important point to understand as this can help transform a script that deals with a single item to multiple ones.
As an illustration, take a look at this simple example.
PS C:\> ping -a (get-content list.txt)
Bad parameter mypcname.
The text file contains the name of servers, one on each line, and the Get-Content cmdlet is returning a collection of string objects identifying the name of each server (see below), something that ping does not understand. In order to make this work, the objects must be sent down a pipe and processed individually.
#will not work as ping does not understand objects in this manner
PS C:\> get-content list.txt | ping -a $_
IP address must be specified.PS C:\> get-content list.txt | foreach { ping -a $_ }
Pinging mypcname [127.0.0.1] with 32 bytes of data:
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128
Reply from 127.0.0.1: bytes=32 time<1ms TTL=128Ping statistics for 127.0.0.1:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0msPinging mypcname [192.168.100.66] with 32 bytes of data:
Reply from 192.168.100.66: bytes=32 time<1ms TTL=128
Reply from 192.168.100.66: bytes=32 time<1ms TTL=128
Reply from 192.168.100.66: bytes=32 time<1ms TTL=128
Reply from 192.168.100.66: bytes=32 time<1ms TTL=128Ping statistics for 192.168.100.66:
Packets: Sent = 4, Received = 4, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
Minimum = 0ms, Maximum = 0ms, Average = 0msPS C:\> $c = get-content list.txt
PS C:\> $c
localhost
mypcnamePS C:\> $c.gettype()
IsPublic IsSerial Name BaseType
——– ——– —- ——–
True True Object[] System.Array





