Home > OS >  Replace string in text file with PowerShell
Replace string in text file with PowerShell

Time:07-13

I am attempting to replace a string in a text file on a specific line number using PowerShell but the command is removing a majority of the content. I would like to leverage the line number because the string to be replaced occurs on several lines but only want the string on line 51 to be updated. I am currently attempting to use the following to perform the replacement:

$content = Get-Content "file.txt"
$contentUpdate = $content[51] -replace '"Endpoint": ""','"Endpoint": "bucket.s3.us-west-1.vpce.amazonaws.com",'
Set-Content file.txt $contentUpdate

When the above commands are run against the file referenced at the bottom of this question, only the following remains in the file:

        "Region": "",

File content:

{
    "Profile":{
        "ShareCreds" : true,
        "ShareProfile" : "",
        "ForceUpdateCreds" : false,
        "KeyAutoRotateDays": 0
    },
    "Mds": {
        "CommandWorkersLimit" : 5,
        "StopTimeoutMillis" : 20000,
        "Endpoint": "",
        "CommandRetryLimit": 15
    },
    "Ssm": {
        "Endpoint": "",
        "HealthFrequencyMinutes": 5,
        "CustomInventoryDefaultLocation" : "",
        "AssociationLogsRetentionDurationHours" : 24,
        "RunCommandLogsRetentionDurationHours" : 336,
        "SessionLogsRetentionDurationHours" : 336,
        "PluginLocalOutputCleanup": "",
        "OrchestrationDirectoryCleanup": ""
    },
    "Mgs": {
        "Region": "us-west-1",
        "Endpoint": "",
        "StopTimeoutMillis" : 20000,
        "SessionWorkersLimit" : 1000,
        "DeniedPortForwardingRemoteIPs" : [
            "169.254.169.254",
            "fd00:ec2::254",
            "169.254.169.253",
            "fd00:ec2::253"
        ]
    },
    "Agent": {
        "Region": "",
        "OrchestrationRootDir": "",
        "SelfUpdate": false,
        "TelemetryMetricsToCloudWatch": false,
        "TelemetryMetricsToSSM": true,
        "AuditExpirationDay" : 7,
        "LongRunningWorkerMonitorIntervalSeconds": 60
    },
    "Os": {
        "Lang": "en-US",
        "Name": "",
        "Version": "1"
    },
    "S3": {
        "Endpoint": "",
        "Region": "",
        "LogBucket":"",
        "LogKey":""
    },
    "Kms": {
        "Endpoint": ""
    }
}

CodePudding user response:

Well, seeing that this is a JSON you're working with, I would treat it as such:

$content = Get-Content "file.txt" -Raw | ConvertFrom-Json
$content.S3.Endpoint = "bucket.s3.us-west-1.vpce.amazonaws.com"
$content | ConvertTo-Json | Set-Content "file.txt"

This way you avoid trying to index through an array and work with the objects themselves.

  • Related