Need help with powershell script

Hello,

I am trying to do a search and replace of a complete line in a text file, but it does not work.

Objective:

Parse a text file, and if a match is found, one a line, then replace entire line with new text

Example:

Text File contents:

MinimumPasswordAge = 10
MaximumPasswordAge = 999
MinimumPasswordLength = 888
PasswordComplexity = 777
PasswordHistorySize = 222

Code:

$Filepath= "c:\test"
$name = hostname
$cbefore = $Filepath + "\before-" + $name + ".inf"
$cafter = $FilePath + "\after-" + $name + ".inf"
$cpolicy = Get-content $cbefore

$cpolicy -replace '^MinimumPasswordAge.$', 'MinimumPasswordAge = 9'
$cpolicy -replace'^MaximumPasswordAge.$', ("MaximumPasswordAge = 9")
$cpolicy -replace '^MinimumPasswordLength.$',("MinimumPasswordLength = 9")
$cpolicy -replace '^PasswordComplexity.$',("PasswordComplexity = 9")
$cpolicy -replace '^PasswordHistorySize.$',("PasswordHistorySize = 9")


$cpolicy | Set-content $cafter

The data is not properly written afterwards, nor does the variable cpolicy have the update text

Desired results:

MinimumPasswordAge = 9
MaximumPasswordAge = 9
MinimumPasswordLength = 9
PasswordComplexity = 9
PasswordHistorySize = 9
LVL 1
mbudmanAsked:
Who is Participating?
 
oBdAConnect With a Mentor Commented:
Maybe a bit overengineered, but flexible; you can just change the $Replace hashtable as desired:
$Filepath= "C:\test"
$Name = hostname
$InFile = "$($Filepath)\before-$($Name).inf"
$OutFile = "$($Filepath)\after-$($Name).inf"
$Replace = @{
	'MinimumPasswordAge' = 9
	'MaximumPasswordAge' = 9
	'MinimumPasswordLength' = 9
	'PasswordComplexity' = 9
	'PasswordHistorySize' = 9
}

Get-Content $Infile | ForEach-Object {
	$ReplacedLine = $Null
	ForEach ($Key In $Replace.Keys) {
		If ($_ -match "\A$($Key)\s*=\s*\d+\s*\Z") {
			$ReplacedLine = "$($Key) = $($Replace[$Key])"
			Break
		}
	}
	If ($ReplacedLine) {$ReplacedLine} Else {$_}
} | Set-Content -Path $OutFile

Open in new window

0
 
QlemoConnect With a Mentor Batchelor, Developer and EE Topic AdvisorCommented:
You are looking for A string at the beginning of a line, followed by a single character, then end of line. Of course that does not work ;-). For example:
$cpolicy -replace '^MinimumPasswordAge =.*$', 'MinimumPasswordAge = 9' 

Open in new window

1
 
mbudmanAuthor Commented:
So how do i fix it?
0
 
QlemoBatchelor, Developer and EE Topic AdvisorCommented:
My example is the correct replacement for the first setting.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.