Thursday, February 17, 2011

What can I do with windows powershell part4

Saving and Importing Data


The following articles provide a brief introduction to saving and/or importing data by using Windows PowerShell; these tasks include such things as reading and writing to text files as well as saving data in HTML or XML format. As is so often the case with Windows PowerShell, the code snippets found in these articles can either be included within a Windows PowerShell script or typed directly into the Windows PowerShell console.

Using the Add-Content Cmdlet

Appending Data to a Text File

One use of the Add-Content cmdlet is to append data to a text file. For example, this command adds the words “The End” to the file C:\Scripts\Test.txt:
Add-Content c:\scripts\test.txt "The End"
By default Add-Content tacks the new value immediately after the last character in the text file. If you’d prefer to have The End listed on a separate line, then simply insert `n (Windows PowerShell lingo for “new line”) into the value being written to the file. In other words:
Add-Content c:\scripts\test.txt "`nThe End"
Seeing as how you asked, here are some of the other special characters that can be used in Windows PowerShell output:
  • `0 -- Null
  • `a -- Alert
  • `b -- Backspace
  • `n -- New line
  • `r -- Carriage return
  • `t -- Horizontal tab
  • `' -- Single quote
  • `" -- Double quote
Keep in mind that some of these characters are intended for use only from the Windows PowerShell prompt. For example, the special character `a causes your computer to beep. Don’t believe us? Try this command and see what happens:
Write-Host `a
One nice feature of Add-Content is the fact that it accepts wildcard characters. For example, suppose you want to add a timestamp to the end of all the .log files in the C:\Scripts folder. This command will do just that:
$A = Get-Date; Add-Content c:\scripts\*.log $A
As you can see, here we’re simply assigning the current date and time to a variable named $A, then appending the value of that variable to all of the .log files in C:\Scripts.
Add-Content Aliases
  • ac

Using the Select-String Cmdlet

Checking for the Existence of a String Value

What can you do with the Select-String cmdlet? Well, one thing you can do is determine whether or not a specific string value exists in a text file. For example, suppose the file C:\Scripts\Test.txt is a log file that contains the following information:
Operation succeeded, 5/1/2006
Operation succeeded, 5/2/2006
Operation failed, 5/3/2006
Operation succeeded, 5/4/2006
Operation succeeded, 5/5/2006
You’d like to be able to quickly scan the contents of the file and see whether the word Failed appears anywhere. If it does, that means one of your operations failed; if it doesn’t, that means all of your operations succeeded. (And yes, seeing as how we’re talking about failed operations we do hope you’re not a surgeon.) Here’s how you can do that:
Get-Content c:\scripts\test.txt | Select-String "Failed" -quiet
What we’re doing here is using the Get-Content cmdlet to retrieve the contents of the file C:\Scripts\Test.txt. We’re then piping those contents to the Select-String cmdlet and asking Select-String to search for the target string. By adding the -quiet parameter we get back a True if the string is found and nothing if the string is not found. If we leave off the -quiet parameter then Windows PowerShell returns each line in the text file that includes the target string:
Operation failed, 5/3/2006
Another Select-String parameter that you might find useful is -casesensitive, which performs a case-sensitive search of, in this case, the text file. This particular command will return nothing, meaning that the target string Failed could not be found:
Get-Content c:\scripts\test.txt | Select-String "Failed" -quiet -casesensitive
Why couldn’t Failed be found in the text file? That’s easy: based on letter case, there’s no such string in the file. The file contains the string failed with a lowercase f, while the target search string is Failed with an uppercase F. If you change the target string to failed (or remove the -casesensitive parameter) the command returns True.

Using the Tee-Object Cmdlet

Display Data and Save That Data with One Command

The Tee-Object cmdlet enables you to display data in the Windows PowerShell window and to save that same data to a text file, all with a single command. For example, this command uses the Get-Process cmdlet to retrieve information about all the processes currently running on the computer, then uses Tee-Object to simultaneously display the data on-screen and save that data to the file C:\Scripts\Test.txt:
Get-Process | Tee-Object -file c:\scripts\test.txt

Tee-Object Aliases
  • tee
Using the Clear-Content Cmdlet

Erasing the Contents of a File

The Clear-Content cmdlet enables you to erase the contents of a file without deleting the file itself. For example, suppose you run this command:
Clear-Content c:\scripts\test.txt
When you execute that command the file Test.txt will still be in the folder C:\Scripts; there just won’t be any data of any kind in the file:
Windows PowerShell
Did we hear someone ask if wildcard characters can be used with Clear-Content? You bet; this command erases the contents of any file in C:\Scripts whose file name starts with the letter E:
Clear-Content c:\scripts\e*
And, no, you are not limited to erasing only text files. Want to delete all the data in an Excel spreadsheet? Hey, why not:
Clear-Content c:\scripts\test.xls
And this command erases contents of the Word document C:\Scripts\Test.doc:
Clear-Content c:\scripts\test.doc
Clear-Content Aliases
  • clc
Using the ConvertTo-Html Cmdlet

Saving Data as an HTML File

No offense to the console window or a text file, but sometimes it’s hard to beat HTML as an output device (for one thing, HTML gives you more formatting options and flexibility). Fortunately the ConvertTo-Html cmdlet makes it very easy to view Windows PowerShell output in a Web page. For example, this command uses the Get-Process cmdlet to retrieve information about all the processes running on the computer. The output from Get-Process is piped to the ConvertTo-Html cmdlet, which creates an HTML table out of that data. In turn, that table is piped to the Set-Content cmdlet, which saves the information as a Web page (C:\Scripts\Test.htm). That sounds like a lot of work, yet the command is as simple as this:
Get-Process | ConvertTo-Html | Set-Content c:\scripts\test.htm
The resulting Web page looks something like this:
Windows PowerShell
Good point: the table is a bit unwieldy; that’s because the large number of properties returned by Get-Process results in a corresponding large number of columns in the table. This revised command limits the properties displayed in the table to Name, Path, and FileVersion:
Get-Process | ConvertTo-Html name,path,fileversion | Set-Content c:\scripts\test.htm

Our simplified Web page looks like this:
Windows PowerShell
Much better.
But not perfect. By default the title assigned to the Web page is the less-than-scintillating HTML Table. With that in mind, this command uses the -title parameter to change the window title to Process Information:
Get-Process | ConvertTo-Html name,path,fileversion -title "Process Information" | Set-Content c:\scripts\test.htm
Windows PowerShell
We’re definitely on the right track now.
Let’s do one last thing. As you can see, the only information we have on our Web page is the data table. If you’d like to preface the table with some explanatory information then simply include the -body parameter followed by the text you’d like to appear on the page:
Get-Process | 
ConvertTo-Html name,path,fileversion -title "Process Information" -body "Information about the processes running on the computer." | 
Set-Content c:\scripts\test.htm
Granted, we didn’t add much value here. But at least the resulting Web page gives you a hint of the kinds of things you can do:
Windows PowerShell
We should also point out that information configured using the -body parameter is HTML; that means the parameter can include any valid HTML tags. Want to display your preface using the <H2> style? Then just include the <H2> and </H2> tags:
Get-Process | 
ConvertTo-Html name,path,fileversion -title "Process Information" -body "<H2>Information about the processes running on the computer.</H2>" | 
Set-Content c:\scripts\test.htm
Or, to put it a bit more graphically:
Windows PowerShell
If you’ve ever wondered why the Scripting Guys aren’t Web page designers, well, consider the preceding screenshot Exhibit A. But now that you know how ConvertTo-HTML works you can do better.

Using the Get-Content Cmdlet

Reading a Text File

What can you do with the Get-Content cmdlet? Well, one thing you can do is quickly read and display the contents of a text file. For example, this command displays the contents of the file C:\Scripts\Test.txt:
Get-Content c:\scripts\test.txt
And here’s what you’ll get:
Windows PowerShell
Hey, we never said it was exciting, just that it was useful.
How useful? Here’s a simple, but telling example. Suppose you have a text file (C:\Scripts\Test.txt) that contains the names of two or more computers. You’d like to use WMI to retrieve information about the BIOS installed on each of those computers. Here you go:
Get-Content c:\scripts\test.txt | Foreach-Object {Get-Wmiobject -computername $_ win32_bios}
Assuming you have just two computers list in the text file you’ll get back information similar to this:
SMBIOSBIOSVersion : 68DTT Ver. F.0D
Manufacturer      : Hewlett-Packard
Name              : EPP runtime BIOS - Version 1.1
SerialNumber      : CND60723S7
Version           : HP     - 22110520

SMBIOSBIOSVersion : A03
Manufacturer      : Dell Computer Corporation
Name              : Phoenix ROM BIOS PLUS Version 1.10 A03
SerialNumber      : HTVNX41
Version           : DELL   - 7
Good question: how does that command work? The first part is pretty self-explanatory: we just use Get-Content to read the contents of the text file. Now, let’s take a look a look at the second half of the command:
ForEach-Object {Get-Wmiobject -computername $_ win32_bios}
What we’re doing here is passing the contents of the text file (our computer names) to the ForEach-Object cmdlet. As it turns out, Get-Content automatically creates an array based on the content it is retrieving; in the case of a text file, each line in the file will be a single item in the array. The ForEach-Object simply takes the contents of the file, one line at a time, and calls the Get-WmiObject cmdlet, providing Get-Wmiobject with a different line from the file (using the default pipeline variable $_) repeatedly until all lines have been read. Get-Wmiobject then connects to the computer and retrieves information from the Win32_BIOS class.
Confused? Try it on your set of computers and see what happens.
Because Get-Content automatically creates an array consisting of each line in the file, that means you can also use the Measure-Object cmdlet to easily count the number of lines in the file, a task people like to do on a regular basis:
Get-Content c:\scripts\test.txt | Measure-Object
The preceding command returns data similar to this:
Count    : 124
Average  :
Sum      :
Maximum  :
Minimum  :
Property :
Interesting question: what if you want to return only the first x number of lines in the file? In that case simply add the -totalcount parameter followed by the number of lines to retrieve. This command returns only the first five lines in the file Test.txt:
Get-Content c:\scripts\test.txt -totalcount 5
To get the last five lines in the text file simply read the file using Get-Content, then have Select-Object pick out the last five items for you:
Get-Content c:\scripts\test.txt | Select-Object -last 5
Get-Content Aliases
  • gc
  • type
  • cat

No comments:

Post a Comment