PowerShell Get-Content

PowerShell Script Files: Get-Content Cmdlet

The ability to ‘Get-Content’ is useful for itself; moreover, this cmdlet illustrates how easily PowerShell deals with reading from text files.  Incidentally, this page also demonstrates looping, which is 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.

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 content of each cycle is controlled by $_, the resulting output is merely a list of names.

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 | Format-Table Name, State, Status -auto

Note 3: 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 4: To gain perspective, and ideas, you could try:
Get-WmiObject win32_service -filter "name=’spooler’ "

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

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

SolarWinds’ Network 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.

What I like best is the way NPM suggests solutions to network problems.  Its also has 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 try NPM now.

Download a free trial of Solarwinds’ Network Performance Monitor

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 6: 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 7: Ft means Format-Table.  I have chosen just three properties, name of the service, its state (running) and status.

Summary
In order to understand my goal I isolated the PowerShell commands that query the local computer to see which services are running.  Once that works I extended the scope of the script so that it queried 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. 

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

See more PowerShell v 3 Aliases

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 Cmdlet

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  • PowerShell -Filter   • Test-Path

PowerShell Get-ChildItem   • Get-ChildItem -Include   • Get-ChildItem -Exclude   • Compare-Object

PowerShell Registry  • Get-Credential  • PowerShell ItemProperty  • PowerShell ItemPropery GCI

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.