Skip to content

Commit a506e6e

Browse files
committed
Refactored ReplaceText.psm1 to return false is search text isn't found
1 parent f6b6166 commit a506e6e

3 files changed

Lines changed: 16 additions & 4 deletions

File tree

DSCResources/DSR_ReplaceText/DSR_ReplaceText.psm1

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -155,18 +155,26 @@ function Set-TargetResource
155155

156156
if ($null -eq $fileContent)
157157
{
158+
# configuration file does not exist
158159
$fileContent = $Text
159160
}
161+
elseif ( [regex]::Matches($fileContent, $Search).Count -eq 0 )
162+
{
163+
# configuration file exists but Text does not exist so lets add it
164+
$fileContent = "{0}`n`r{1}" -f $fileContent, $Text
165+
}
160166
else
161167
{
168+
# configuration file exists but Text not in a desired state so lets update it
162169
$fileContent = $fileContent -Replace $Search, $Text
163170
}
164171

165172
Set-Content `
166173
-Path $Path `
167174
-Value $fileContent `
168-
-NoNewline `
169175
-Force
176+
#-NoNewline `
177+
170178
}
171179

172180
<#
@@ -243,7 +251,7 @@ function Test-TargetResource
243251
Write-Verbose -Message ($localizedData.StringNotFoundMessage -f `
244252
$Path, $Search)
245253

246-
return $true
254+
return $false
247255
}
248256

249257
# Flag to signal whether settings are correct

DSCResources/DSR_ReplaceText/en-US/DSR_ReplaceText.strings.psd1

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
ConvertFrom-StringData @'
44
SearchForTextMessage = Searching using RegEx '{1}' in file '{0}'.
5-
StringNotFoundMessage = String not found using RegEx '{1}' in file '{0}', change not required.
5+
StringNotFoundMessage = String not found using RegEx '{1}' in file '{0}', change required.
66
StringMatchFoundMessage = String(s) '{2}' found using RegEx '{1}' in file '{0}'.
77
StringReplacementRequiredMessage = String found using RegEx '{1}' in file '{0}', replacement required.
88
StringNoReplacementMessage = String found using RegEx '{1}' in file '{0}', no replacement required.

Tests/Unit/DSR_ReplaceText.Tests.ps1

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -341,7 +341,7 @@ Setting3.Test=Value4
341341
}
342342

343343
It 'Should return true' {
344-
$script:result | Should -Be $true
344+
$script:result | Should -Be $false
345345
}
346346

347347
It 'Should call the expected mocks' {
@@ -537,6 +537,10 @@ Setting3.Test=Value4
537537
}
538538
}
539539

540+
Context 'File exists and search text cannot be found' {
541+
542+
}
543+
540544
Context 'File does not exist' {
541545
# verifiable (should be called) mocks
542546
Mock `

0 commit comments

Comments
 (0)