Modify Text Files

by spoony123 at 2013-03-19 12:26:27

Hi There,

I am trying to write a script thart will check a text file and modify a particular string by pullling the default printer name using WMI and then adding to the string, everything works fine but if i run the script again instead of replacing the line of code with the default printer again, it appends the printer name again so for example after the first run you get


iniPrinterName=Microsoft XPS Writer


Then after the second run you get


iniPrinterName=Microsoft XPS WriterMicrosoft XPS Writer

How do i stop the append happening? My code is below - any suggestions greatly recieved.

$defaultprinter = Get-WMIObject -class Win32_Printer -Filter Default=True | Select Name
$defaultprinter = $defaultprinter.name

$File = "c:\temp\text.txt"
foreach ($str in $File)
{
$content = Get-Content -path $str
$content | foreach {$_ -replace "iniPrinterName=", "iniPrinterName=$defaultprinter"} | Set-Content $str
}
Get-Content $File
by jonhtyler at 2013-03-19 13:00:53
I think what you want to use here is a regular expression (regex) in your match. Assuming that this string begins the line, I believe you could use something like this:

$_ -replace "^iniPrinterName=$", "iniPrinterName=$defaultprinter"

in your foreach loop. The "^" character tells Powershell that the line should begin with this string, and the "$" tells that this is the end of the string. Therefore, a string with the printer name already filled in would not be a match because the "=" sign is no longer the last character in the expression.
by mjolinor at 2013-03-19 13:06:12
When you use -replace, it will replace everthing that is part of the match with the replacement string. In this case, what you are matching, and therefore replacing is "iniPrinterName=". On the first pass nothing follows that string, so you effectively just append some text to it in the replacement. On the second pass there is following text, but it’s not part of the match, so it doesn’t get replaced. To fix it, make the following text part of the match:

$content | foreach {$_ -replace "iniPrinterName=.*", "iniPrinterName=$defaultprinter"} | Set-Content