Bart Eeltink
Bart Eeltink

Reputation: 11

PowerShell: How to find a word within a line of text and modify the data behind it

I'm looking for a way to find a word with a value behind it in a piece of text and then update the value. Example:

In the file the are multiple occurrences of 'schema="anon" maxFileSize="??????" maxBufferSize="123"' I want to find all the lines containing maxFileSize and then update the unknown value ?????? to 123456.

So far, I came up with this:

cls
$Files = "C:\temp1\file.config","C:\temp2\file.config"
$newMaxFileSize = "123456"

ForEach ($File in $Files) {
    If ((Test-Path $File -PathType Leaf) -eq $False) {
        Write-Host "File $File doesn't exist"
    } Else {
        # Check content of file and select all lines where maxFileSize isn't equal to 123456 yet
        $Result = Get-Content $File | Select-String -Pattern "maxFileSize" -AllMatches | Select-String -Pattern "123456" -NotMatch -AllMatches
        Write-Host $Result
        <#
            ROUTINE TO UPDATE THE SIZE
        #>
    }
}

Yet, I have no clue how to find the word "maxFileSize", let alone how to update the value behind it...

Upvotes: 1

Views: 196

Answers (1)

Mathias R. Jessen
Mathias R. Jessen

Reputation: 174445

Assuming the input file is actually XML, use the following XPath expression to locate all nodes that have a maxFileSize attribute (regardless of value):

# Parse input file as XML
$configXml = [xml](Get-Content $file) 

# Use Select-Xml to find relevant nodes
$configXml |Select-Xml '//*[@maxFileSize]' |ForEach-Object {
  # Update maxFileSize attribute value
  $_.Node.SetAttribute('maxFileSize','123456')
}

# Overwrite original file with updated XML
$configXml.Save($file.FullName)

If the config file is some archaic format for which no readily available parser exists, use the -replace operator to update the value where appropriate:

$Results = @(Get-Content $File) -creplace '(?<=maxFileSize=")[^"]*(?=")','123456'

The pattern used above, (?<=maxFileSize=")[^"]*(?="), describes:

(?<=             # Positive look-behind assertion, this pattern MUST precede the match
  maxFileSize="  # literal string `maxFileSize="`
)                # Close look-behind
  [^"]*          # Match 0 or more non-" characters
(?=              # Positive look-ahead assertion, this pattern MUST succeed the match
  "              # literal string `"`
)                # Close look-ahead

Upvotes: 1

Related Questions