Monthly Archives: December 2011

Using Powershell to search for lines in a text file

I wanted to find all the lines in a log file that contained a specific piece of text. It could have been done with something like Excel, but the text was all in the middle of long strings. So the easiest way was to do it with Powershell.

I started with the following line:

get-content "c:\test.txt" | where {$_ -match "findme"}

That actually worked really well so I built a simple script around it which should work with .txt or .csv files (or even .tsv!).

So here is some simple code to use, which even includes some help information, which can be accessed by running
<

help ./get-txtlines.ps1

Well assuming that you called the file that..

So here is get-txtlines.ps1:

Param ($filepath = "c:\text.txt", $textstr="test", $MatchCount = 0)
$lines = get-content $filepath | where {$_ -match "$textstr"}
If ($MatchCount -eq 1)
{$lines | measure-object}
Else
{$lines}

The file, including the help content can be downloaded here: http://dl.dropbox.com/u/20638386/get-TxtLines.ps1

Advertisements

Leave a comment

Filed under Microsoft, Powershell

Adding a new volume to an ESX host using Powershell

As I have a script already to create a new volume via Powershell, I wanted to extend it to add a new volume (datastore). The following function will do that:

Function vmAddStorage
{
    param ([string]$server, [string]$volname)
    #Example usage - vmAddStorage esxhost myNewVolume
    $myhost = get-vmhost $server
    $myhost | get-vmhoststorage -RescanAllHba
	
	$lunpath = Get-VMHost | Get-ScsiLun | Where { $_.Vendor -match "EQLOGIC"}
	new-datastore -vmfs -vmhost $myhost -path $lunpath.CanonicalName -Name $volname
	
    $myhost | get-vmhoststorage -RescanAllHba
}

This is for Equallogic storage, but you could adapt it for use with other storage vendors. to know what to use in the $lunpath line, you could run

Get-VMHost | Get-ScsiLun | format-list

Then look for the Vendor property. I ran this against ESXi 4.1 so far using version 1.0 of the pssnapin (vmware.viautomation.core).

Leave a comment

Filed under Equallogic, Powershell, VMware