Thursday, February 17, 2011

What can I do with windows powershell part5

Using the Import-Csv Cmdlet

Read in a Comma-Separated Values File

The Import-Csv cmdlet provides a way for you to read in data from a comma-separated values file (CSV) and then display that data in tabular format within the Windows PowerShell console. For example, suppose you have a file named C:\Scripts\Test.txt, a file that contains the following data:
Name,Department,Title
Pilar Ackerman,Research,Manager
Jonathan Haas,Finance,Finance Specialist
Ken Myer,Finance,Accountant
You say you’d like to view that data on-screen, and in a table, to boot? Then just call Import-Csv followed by the path to the file you want to open:
Import-Csv c:\scripts\test.txt
In turn, Windows PowerShell will give you output that looks like this:
Name                       Department                 Title
----                       ----------                 -----
Pilar Ackerman             Research                   Manager
Jonathan Haas              Finance                    Finance Specialist
Ken Myer                   Finance                    Accountant
That’s cool. But if you really want to have some fun - well, good point: if you really want to have some fun you’d probably do something other than import CSV files. Let’s put it this way: if you want to have some relative fun, pipe the imported data to the Where-Object cmdlet. For example, this command retrieves only those employees who work for the Finance department:
Import-Csv c:\scripts\test.txt | Where-Object {$_.department -eq "Finance"}
Here’s what the resulting dataset looks like:
Name                       Department                 Title
----                       ----------                 -----
Jonathan Haas              Finance                    Finance Specialist
Ken Myer                   Finance                    Accountant
Granted, the right side of the pipeline is bit cryptic looking. However, it’s not all that hard to interpret. The $_ is simply Windows PowerShell notation for the current object; the current object, of course, is the text file C:\Scripts\Test.txt. The .department is standard “dot” notation; this is no different than referring to a WMI property by saying something like objItem.Name. All we’re saying is that, for the text file in question, we want to check the value of the Department property (i.e., the Department field). If the field is equal to (-eq) Finance we want to see it; if it’s not equal to Finance then we don’t want to see it.
Suppose we wanted to see the records for all employees except those from the Finance Department. In that case we’d use this command, with -ne meaning “not equal to”:
Import-Csv c:\scripts\test.txt | Where-Object {$_.department -ne "Finance"}
That command returns the following data:
Name                       Department                 Title
----                       ----------                 -----
Pilar Ackerman             Research                   Manager
Can you have more than one item in a where clause? Sure: just combine the two criteria with -and or -or. For example, this command returns only accountants who work in the Finance department:
Import-Csv c:\scripts\test.txt | Where-Object {$_.department -eq "Finance" -and $_.title -eq "Accountant"}
What does that mean? That means you’ll get back information like this:
Name                       Department                 Title
----                       ----------                 -----
Ken Myer                   Finance                    Accountant
Meanwhile, this command returns a list of employees who either work in the Research department or are accountants:
Import-Csv c:\scripts\test.txt | Where-Object {$_.department -eq "Research" -or $_.title -eq "Accountant"}
You can probably guess what information we get back when we run that command:
Name                       Department                 Title
----                       ----------                 -----
Pilar Ackerman             Research                   Manager
Ken Myer                   Finance                    Accountant
Cool.
Import-Csv Aliases
  • ipcsv
Using the Import-Clixml Cmdlet

Reading in an XML File

Here’s a tough one for you. If the Export-Clixml cmdlet enables you to save data as an XML file, then what do you suppose the Import-Clixml cmdlet lets you do? OK, so maybe it wasn’t all that tough after all. At any rate, you’re right: Import-Clixml will import an XML file that was saved using Export-Clixml and then rebuilds the Windows PowerShell object for you. For example, suppose you use the Get-ChildItem cmdlet to retrieve a collection of files found in the folder C:\Scripts; you then use the Export-Clixml cmdlet to save that information as an XML file:
Get-ChildItem c:\scripts | Export-Clixml c:\scripts\files.xml
Any time you feel like it you can retrieve that data using Import-Clixml; simply call the cmdlet followed by the name of the file to import. For example, this command retrieves the data and stores it in a variable named $A:
$A = Import-Clixml c:\scripts\files.xml
So what will $A be equal to? It will be equal to the collection of files that were in C:\Scripts at the time you originally ran Get-ChildItem. Take a look at our Windows PowerShell session:
Windows PowerShell
The best part is that $A is not simply a collection of string data, but an actual Windows PowerShell object. How do we know that? Try piping $A through the Sort-Object cmdlet and see what happens:
$A | Sort-Object length


Using the Export-Csv Cmdlet

Saving Data as a Comma-Separated Values File

The Export-Csv cmdlet makes it easy to export data as a comma-separated values (CSV) file; all you need to do is call Export-Csv followed by the path to the CSV file. For example, this command uses Get-Process to grab information about all the processes running on the computer, then uses Export-Csv to write that data to a file named C:\Scripts\Test.txt:
Get-Process | Export-Csv c:\scripts\test.txt
The resulting text file will look something like this:
#TYPE System.Diagnostics.Process
__NounName,Name,Handles,VM,WS,PM,NPM,Path,Company,CPU,FileVersion,ProductVersion,Description,Product,BasePriority,
ExitCode,HasExited,ExitTime,Handle,HandleCount, Id,MachineName,MainWindowHandle,MainWindowTitle,MainModule,
MaxWorkingSet,MinWorkingSet,Modules,NonpagedSystemMemorySize,
NonpagedSystemMemorySize64, PagedMemorySize,PagedMemorySize64,PagedSystemMemorySize,PagedSystemMemorySize64,PeakPagedMemorySize,
PeakPagedMemorySize64,PeakWorkingSet,PeakWorkingSet64, PeakVirtualMemorySize,PeakVirtualMemorySize64,
PriorityBoostEnabled,PriorityClass,PrivateMemorySize,PrivateMemorySize64,PrivilegedProcessorTime,ProcessName,
ProcessorAffinity, Responding,SessionId,StartInfo,StartTime,SynchronizingObject,
Threads,TotalProcessorTime,UserProcessorTime,VirtualMemorySize,VirtualMemorySize64,EnableRaisingEvents, 
StandardInput,StandardOutput,StandardError,WorkingSet,WorkingSet64,Site,Container
Process,alg,110,33714176,3698688,1273856,5400,C:\WINDOWS\System32\alg.exe,"Microsoft Corporation",0.046875, 
"5.1.2600.2180 (xpsp_sp2_rtm.040803-2158)",5.1.2600.2180,"Application Layer Gateway Service",
"Microsoft? Windows? Operating System",8,,False,,2140,110,788,.,0,,"System.Diagnostics.ProcessModule 
(alg.exe)",1413120,204800,System.Diagnostics.ProcessModuleCollection,5400,5400,1273856,1273856,65756,65756, 
1347584,1347584,3747840,3747840,35024896,35024896,True,Normal,1273856,1273856,00:00:00.0312500,alg,1,True,0,
System.Diagnostics.ProcessStartInfo,"5/19/2006 7:37:03 AM",,System.Diagnostics.ProcessThreadCollection,
00:00:00.0468750,00:00:00.0156250,33714176,33714176,False,,,,3698688,3698688,,
By default, data is saved in ASCII format. What if you’d prefer to save the data in Unicode format (or maybe UTF7 or UTF8)? No problem; just add the -encoding parameter followed by the desired format:
Get-Process | Export-Csv c:\scripts\test.txt -encoding "unicode"
You might have noticed that the first line in the resulting CSV file lists the .NET object type:
#TYPE System.Diagnostics.Process
If you’d just as soon not have the .NET object type in your output file then simply include the -notype parameter:
Get-Process | Export-Csv c:\scripts\test.txt -notype
Another parameter you might find useful is -force. Suppose Test.txt is a read-only file: that enables people to access, but not change, the contents of the file. That’s great, until it comes time to use Export-Csv and update the contents of the file. Here’s what happens if you try to export text to a read-only file:
PS C:\Documents and Settings\gstemp> Get-Process | Export-Csv c:\scripts\test.txt
Export-Csv : Access to the path 'C:\scripts\test.txt' is denied.
That’s where -force comes into play. Suppose you add -force to your export command:
Get-Process | Export-Csv c:\scripts\test.txt -force
In that case, Windows PowerShell will temporarily clear the read-only attribute from the file, update the contents, and then reset the read-only attribute. The end result: the file gets updated, but when Export-Csv is finished the file will still be marked as read-only.
Export-Csv Aliases
  • epcsv
Using the Export-Clixml Cmdlet

Saving Data as an XML File

Of course you can save Windows PowerShell output in XML format; what else would you use the Export-Clixml cmdlet for? This simple command uses the Get-Process cmdlet to retrieve information about all the processes running on the computer. That information is then piped to the Export-Clixml cmdlet, which in turn saves the data as an XML file named C:\Scripts\Test.xml:
Get-Process | Export-Clixml c:\scripts\test.xml
The resulting XML file will look something like this:
Windows PowerShell
By default Export-Clixml overwrites any existing copy of C:\Scripts\Test.xml. If you’d prefer not to overwrite Test.xml then simply include the -noclobber parameter in your command:
Get-Process | Export-Clixml c:\scripts\test.xml -noclobber
If you run this command and Test.xml already exists you’ll get back the following error message:
Export-Clixml : File C:\scripts\test.xml already exists and NoClobber was specified.

Using the Out-File Cmdlet

Saving Data Directly to a Text File

The Out-File cmdlet enables you to send pipelined output directly to a text file rather than displaying that output on screen. For example, this command retrieves process information using Get-Process, then uses Out-File to write the data to the file C:\Scripts\Test.txt:
Get-Process | Out-File c:\scripts\test.txt
By default Out-File saves the data exactly the way that data appears in your Windows PowerShell console. That means that some of the data could end up truncated. For example, take a look at the results of running Get-Process in the console:
Windows PowerShell
If you look closely, you’ll notice that the name of at least one process (PhotoshopElementsF …) could not be fully displayed onscreen. In turn, that’s exactly how this line will look in the saved text file:
61       5     1240        660    30     0.05   1084 PhotoshopElementsF...
That’s a problem, but it’s an easy problem to solve: just include the -width parameter and specify a different line width (in characters) for the text file. For example, this revised command sets the line width to 120 characters:
Get-Process | Out-File c:\scripts\test.txt -width 120
And here’s what that same line looks like in the new and improved text file:
61       5     1240        660    30     0.05   1084 PhotoshopElementsFileAgent


Using the Set-Content Cmdlet

Saving Data to a Text File

The primary use of Set-Content is to write data to a text file. For example, this command writes the text “This is a test” to the text file C:\Scripts\Test.txt:
Set-Content c:\scripts\test.txt "This is a test"
Note that this replaces the existing contents of Test.txt with the new text specified in the command. To append text to a file, use the Add-Content cmdlet.
Set-Content Aliases
  • sc

No comments:

Post a Comment