Guy recommends :
Free Solarwinds
VM Console

Solarwinds VM Console Free Download

Find out which of your VMs are a waste of space and which VMs need more resources.



PowerShell Get-Content

PowerShell Script Files - Get-Content

The ability to 'Get-Content' is useful for itself; moreover, this cmdlet illustrates how easily PowerShell deals with reading from text files.  This page also demonstrates looping, a classic job for automation via scripting, and a task that PowerShell delivers with deceptive ease.

 ♣

Mission For Get-Content

Our mission is to employ PowerShell and WMI for checking the status of the operating system's services.  The role of Get-Content is merely to read a list of hostnames, as a result we can run the WMI code against remote machines.  For ease of learning, and so that you could re-cycle the building blocks, I have broken down the mission into three self-contained tasks.

In order to understand my goal let us isolate the PowerShell commands that query the local computer to see which services are running.  Once that works we want to extend the scope of the script so that it queries other machines on your network.

Reading lines from a text file is a classic job for a loop.  In PowerShell we can initiate the loop with a 'Foreach' statement.  Inside that loop we use Get-Content to read the names of the computers held in a named text file. 

Pre-requisites

  • Create a text file, make a note of the path as well as the filename.
  • Another trivial point, you need to type a list of hostnames corresponding to the computers you wish to interrogate.
  • Disable the firewall on both the source computer, where the script executes, and also on the destination machine(s) which we wish to interrogate.

I don't want to stray too far from the main objective which is to master Get-Content, but as a separate mini-project you could obtain a list of computers which are active on your network by using WMI's Win32_PingStatus.  However, for now we will assume that you have a list of computers safely stored in a file called NetMachines.txt.

1) Pure Get-Content - List Names in a Text File

The only purpose of this script is to list the contents of a file line-by-line.

# PowerShell script to list each line of a file
$File = "E:\PowerShell\Loops\NetworkMachines.txt"
Get-Content $File | foreach-Object { $_
}

Note 1: All we want to achieve in this example is to practise our Get-Content technique.  Observe how the variable $File controls the source of the text.

Note 2: Foreach-Object provides the loop.  The contents of each cycle are controlled by $_, the resulting output is merely a list of names.

Guy Recommends: WMI Monitor and It's Free!Solarwinds Free WMI Monitor

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft operating systems.  Fortunately, Solarwinds have created a Free WMI Monitor so that you can discover these gems of performance information, and thus improve your PowerShell scripts.  Take the guess work out of which WMI counters to use when scripting the operating system, Active Directory or Exchange Server.

Download your free copy of WMI Monitor

2) A Reminder of WMI's Role in This Mission

In real life this is the portion of the script that you would amend in order to tackle a specific problem.

# WMI script to list services which are running on local machine
$Wmi=Get-wmiobject win32_service -filter "state='Running'"
$Wmi | Ft name, state, status -auto

Note 1: This is just a simple WMI script whose class is win32_service, just for fun we have filtered only those services that are running.

Note 2: To gain perspective, and ideas, you could try:
Get-wmiobject win32_service -filter "name='spooler' "

Note 3: The tiny vertical | tells PowerShell to output the contents of $WMI into the second part of that line.

3a) Problems of 'Remoting'

Running scripts on remote machines has never been easy.  Firewalls and administrative credentials mean that access to another machine is unlikely to be straight forward.  While PowerShell version 2.0 has much better 'Remoting' abilities, here we are dodging some of PowerShell 1.0's limitations by using WMI's -computername parameter.

Even with everything in our favour, please humour me and make a crucial configuration change to your machines. Just to get started, I advise that you suspend normal 'best practice' and disable the firewalls on both the source (server) and the remote (client) machines.  If the script works then you could investigate other options such as selectively opening ports, and using -credential.  (Incidentally, adding Impersonate and Credential to scripts rarely works for me.)  See how to disable Windows 8 firewalls with a Group Policy.

3b) Putting it All Together: Completing the Mission

If you remember, our mission was to create a PowerShell script, which ran WMI commands against a list of network machines.

# PowerShell script to check running services on a list of computers
# Author: Guy Thomas

clear-Host
$File = "E:\PowerShell\Loops\NetworkMachines.txt"
Get-Content $File | foreach-object {
$Wmi=Get-wmiobject win32_service -filter "state='Running'" -computername $_
"Computer $_ "; $Wmi | Ft name, state, status -auto
}

Note 1: This single script combines the tasks of the two previous scripts.  Observe how 'foreach' loops through the list of computer names controlled by the $File variable.  The WMI class win32_service retrieves services that are running.

Note 2: Ft means format-Table.  I have chosen just three properties, name of the service, its state (running) and status.

Guy Recommends:  A Free Trial of the Network Performance Monitor (NPM)Review of Orion NPM v10

Solarwinds' Orion performance monitor will help you discover what's happening on your network.  This utility will also guide you through troubleshooting; the dashboard will indicate whether the root cause is a broken link, faulty equipment or resource overload.

Perhaps the NPM's best feature is the way it suggests solutions to network problems.  Its second best feature is the ability to monitor the health of individual VMWare virtual machines.  If you are interested in troubleshooting, and creating network maps, then I recommend that you take advantage of Solarwinds' offer.

Download a free trial of the Network Performance Monitor.

Researching Similar PowerShell Content Cmdlets

# PowerShell Content Cmdlet Research
Clear-Host
Get-Command -noun Content

Results show:

Add-Content
Clear-Content
Get-Content
Set-Content

Also Recommended Out-File

Get-Content Alias 'Type'

With Microsoft, there are always at least three ways of doing everything, what seems like redundancy when you are an expert, seems like perspective when you are a beginner.  Get-Content has not one, but three aliases check thus:

# PowerShell Alias Type
Get-Alias -definition Get-Content

PowerShell -v- VBScript

In VBScript dealing with files was never straightforward.  However, with PowerShell it's so effortless that you may not realize that the Get-Content cmdlet opens and closes as part of its job description.

Incidentally, in PowerShell the mirror image of Get-Content would be out-File, that is where you append a command to save the output of a script into a named file.  To use Get-Content or out-File all you need is the path there is no need for any file open or file close commands because PowerShell takes care of them automatically.

Get-Content is a simple enough cmdlet to understand.  What it does is fetch data information stored in files, for example a list of names from a text file.  Just playing with Get-Content leads to questions such as 'Why bother', or 'What's the point?'  I hope that your answer to such questions will give you a PowerShell technique that you can incorporate in bigger more complex scripts.

Summary of PowerShell's Get-Content

If you are coming from scripting languages such as VBScript, you may not be aware of how easy it is to read from text files in PowerShell.  Get-Content not only reads the data line-by-line, but also deals with opening and closing the named file automatically.

There is also Out-File, a very useful command to save results to disk, rather than write to screen.

If you like this page then please share it with your friends

 


See more Microsoft PowerShell file tutorials:

PowerShell Home   • Add-Content  • Get-Content  • Set-Content  • Test-Path  • -recurse

Files  • PowerShell Registry  • PowerShell ItemProperty  • Compare-object

Get-Credential   • Windows PowerShell

Please email me if you have a better example script. Also please report any factual mistakes, grammatical errors or broken links, I will be happy to correct the fault.

Download my ebook:Getting Started with PowerShell
Getting Started with PowerShell - only $9.25

You get 36 topics organized into these 3 sections:
   1) Getting Started
   2) Real-life tasks
   3) Examples of Syntax.

In addition to the ebook, you get a PDF version of this  Introduction to PowerShell ebook  It runs to 120 pages of A4.

 *


Custom Search

Guy Recommends: WMI Monitor and It's Free!Solarwinds WMI Monitor

Windows Management Instrumentation (WMI) is one of the hidden treasures of Microsoft operating systems.

Fortunately, Solarwinds have created the Free WMI Monitor so that you can actually see and understand these gems of performance information.  Take the guess work out of which WMI counters to use for applications like Microsoft Active Directory, SQL or Exchange Server.

Download your free copy of WMI Monitor

 

Home Copyright © 1999-2012 Computer Performance LTD All rights reserved

Please report a broken link, or an error.