In the simplest case, all you need to do is insert a pipeline segment with a Get-Content
command:
Get-ChildItem -Path C:\Users\$env:UserName -Filter QA11test.hep |
Get-Content | # Send the lines of the input file(s) one by one to ForEach-Object
ForEach-Object { ...
However, there are problems with your approach:
If a file is found, the output file is unconditionally written - even if no modifications are made to the contents of the input.
- Additionally, due to the
exit
statements in your code, any remaining input lines are omitted from the output file.
If no file is found, the output file is either created as an empty file (0
bytes) or, if it already existed, replaced with an empty file.
Instead, I suggest using an approach based on the switch
statement, which is faster, more concise, and more flexible:
Notably, this solution only creates / replaces the output file if an input file was found and modifications were made to it.
Get-ChildItem -Path C:\Users\$env:UserName -Filter QA11test.hep | ForEach-Object {
$updated = $false
$newLines = switch -File $_.FullName -Regex { # Loop over all file lines
'SSL/TLS User Cipher Suites=DEFAULT' {
$_, "IP Port=2023", "Security Option=2" # send 2 additional lines
$updated = $true
}
default { $_ } # pass other lines through
}
# Rewrite the file only if modifications were made.
if ($updated) { $newLines | Set-Content C:\Users\$env:UserName\Telnet\QA11TestSecure.hep }
# Emit the appropriate status message.
Msg $env:UserName ('Nothing to update.', 'Your host explorer session has been updated.')[$updated]
}
Note: If you also need to know whether an input file was found at all - irrespective of whether it needed updating - set $found = $true
inside the script block and check it after the command: if (-not $found) { Msg $env:UserName 'QA11test.hep not found' }
switch -File $_.FullName -Regex
reads the input file line by line, and matches each line against the regex condition:
- If the regex matches, the original line (
$_
) is output, along with 2 additional lines; plus, flag $updated
is set to indicate that the content was modified.
- All other lines (the
default
conditional) are output as-is.
$newLines = ...
captures the (potentially modified) lines in an array.
- Note that this means that all lines are stored in memory at once, but with text files that is usually not a concern.
Only if $updated
is set is the output file written (Set-Content
).
Finally, the Msg
command is invoked with a status-appropriate message.
- Note the
('msg1', 'msg2')[$updated]
expression, which is a shortcut for choosing one of two values based on a flag: if $updated
is $true
, $true
is coerced to array index 1
and therefore selects 'msg2'
; if it is $false
, the index is 0
, and 'msg1'
is selected.