Sunday 10 January 2010

Working With Txt and Csv files.

One of the most useful things I've see so far from using powershell is the way you can work with external files such as txt or csv files. They can be used to both import data into powershell and output to.

We shall start by looking at importing from a txt file.
As the most basic thing we can do with a txt file just type "get-content " and it will display what is in the file - not much use on it's own but the cool stuff comes next. Try this:

get-wmiobject win32_operatingsystem -computername (get-content c:\computers.txt) | select __server,localdatetime
My "computers.txt" file just contains a list of computers names. This one line of script will come back to you and tell you the name of the computer (__server) and the time and date on that computer (localdatetime). That's just 2 of many options you can select. Try

get-wmiobject win32_operatingsystem | get-member
"Get-wmiobject -list" will give you a list of all wmiobject classes available. Your most likely to start looking at win32_operatingsystem and win32_bios.
If you are looking for a specific object like one related to bios type "get-wmiobject -list *bios*" and it will list only those objects with bios in the name.
Remember that if you use the -computer (get-content ) then you can pull in the list of computers you wish to audit.

Importing from CSV files:
For starters just type "import-csv ". The import-csv command on it's own will simply dump the file to screen and by default it will show it in a list format. it can also be viewed in a table like how it would apear in excel. Try:


Import-Csv c:\Book1.csv | format-table
This, like the "get-content " command on it's own, isn't much use without extra options to go with it. So how can a csv file be of use?
As a system admin I can make use of csv files as a way of creating users (I will go into detail in a future blog) in Active Directory. Other uses might will also be covered in future posts as examples come up (yes that does mean I can’t think other other uses atm).

Can I only import?
No… a useful cmdlet is “export-csv <path\file.csv>” and “out-file <path\file.txt>” Try:
get-help | out-file c:\pwrshell_help.txt
notepad.exe c:\pwrshell_help.txt

or

get-process | export-csv c:\processes.csv
import-csv C:\processes.csv format-table

You can also import and output to html and xml files.

If you stick with me on this blog then you will see many more examples when I get more in-depth into powershell.

Thanks for reading,
Dave.

No comments:

Post a Comment