11 Sep 2009

Remove blanks, find replace within a file using powershell

These two small Powershell functions could save an admins live at daily work 🙂

#---------------------------------------------------------------------------------------
Function find_replace($file,$findstr,$replacestr)
{
	$input =  get-content $file
	$output = $input -replace($findstr,$replacestr)
	set-content $file $output
}
#---------------------------------------------------------------------------------------

Example:
find_replace “C:\test.txt” “blaa” “fooo”

#---------------------------------------------------------------------------------------
Function trim($file,$mode)
{
	$input = Get-Content $file
	$output = $input | where {$_ -notmatch "^$" }
	If ($mode -eq 'includeblanks')
	{
		$output = $output -replace(' ','')
	}
	Set-Content $file $output
}
#---------------------------------------------------------------------------------------

Example 1:**
trim “C:\test.txt”
** (removes empty lines in the file)**

Example 2:
trim “C:\test.txt” includeblanks
** (removes also blank chars)

**