« Previous 1 2
Working with objects in PowerShell
Useful Tool
Processing Data Downstream
When users start to deal with the properties and capabilities of objects in more detail, newcomers may gain the impression that PowerShell's object-oriented approach is a nice solution but hardly offers any practical advantages in comparison with the type of legacy shell programming that they may be familiar with from Linux/Unix systems. To illustrate the difference and the advantages, it is important to remember how information is displayed in the Bash shell, for example. A purely text-oriented program like IPconfig (or ifconfig on Linux derivatives) outputs all its results as plain text.
If you want to access or continue to use only on certain values from this output, you need to turn to filter programs like awk, grep, or sed. PowerShell offers a cmdlet Get-NetIPConfiguration
that basically outputs the same data (Figure 3). But because objects are output here, the user can directly access the members. The following call gives you an example of this:
> (Get-NetIPConfiguration).DNSServer
This only outputs the data for the DNS server configured on this computer. The type of call is particularly important here: The Get-NetIPConfiguration
cmdlet must be enclosed in brackets. Otherwise, PowerShell interprets the call as a complete name of the format Get-NetIPConfiguration.DNSServer
and outputs an error message, saying that it can't find any such command. Use of the brackets tells the PowerShell interpreter to first run the command within the bracket and generate a ServiceController object. PowerShell then directly accesses the properties of the DNSServer property and displays them.
This type of access works well if you only need the status of a particular process on your system for further processing in a script, for example. The following command
> (Get-Service - Name Teamviewer).Status
tells the cmdlet to display only the "Running" output if the TeamViewer service is active on the system.
Conclusions
Take a good look at the objects, their members, properties, and methods with the help of the Get-Member
cmdlet and experiment with the different access options and capabilities – you will soon see how many opportunities you have to put them into practice for fast and efficient scripting.
« Previous 1 2
Buy this article as PDF
(incl. VAT)