User Tools

Site Tools


windows:replace-line-in-file

Replacing a Line in a File Using PowerShell and Batch

This page explains how to use a PowerShell script to replace a specific line in a file by calling the script from a batch (.bat) file.

PowerShell Script

The PowerShell script below is used to replace a specific line in a file. The script searches for a line that starts with a certain string and replaces it with another specified line.

Replace-Line.ps1
Param (
    [string]$FilePath
)
 
# Define the search string and replacement line
$SearchString = '        <j2se version="1.6+" max-heap-size="256m"/>'
$ReplacementLine = '        <j2se version="1.8+" max-heap-size="512m" java-vm-args="-agentlib:jdwp=transport=dt_socket,server=y,suspend=n,address=8888"/>'
 
if (-not (Test-Path -LiteralPath $FilePath -PathType Leaf)) {
    Write-Error "File '$FilePath' does not exist."
    exit 1
}
 
try {
    # Read the file content
    $content = Get-Content -LiteralPath $FilePath -Encoding UTF8
 
    # Process each line
    $modifiedContent = $content | ForEach-Object {
        if ($_.StartsWith($SearchString)) {
            # Replace the line
            $ReplacementLine
        } else {
            $_
        }
    }
 
    # Write the modified content back to the file
    $modifiedContent | Set-Content -LiteralPath $FilePath -Encoding UTF8
 
    Write-Host "The file '$FilePath' has been updated."
    exit 0
} catch {
    Write-Error "An error occurred: $_"
    exit 1
}

Batch File

To call the PowerShell script from a batch file, you can use the following example batch script. This script checks for the existence of the file and then calls the PowerShell script to perform the replacement.

Replace-Line.bat
@echo off
setlocal
 
set "JNLP_FILE=C:\Path\To\Your\File.jnlp"
 
if not exist "%JNLP_FILE%" (
    echo Error: JNLP file not found.
    exit /b 1
)

rem Call the PowerShell script to perform the replacement
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "C:\Path\To\Your\Script\Replace-Line.ps1" -FilePath "%JNLP_FILE%"

rem Check the exit code of the PowerShell script
if errorlevel 1 (
    echo There was an error executing the PowerShell script.
    exit /b 1
) else (
    echo File updated successfully.
)
 
endlocal

Explanation

  • PowerShell Script Parameters: The script takes the path to the file to be processed as a parameter.
  • Search and Replace: The script searches for a line starting with the specified string and replaces it with the replacement line.
  • Calling from Batch: The batch script sets the path to the JNLP file and calls the PowerShell script using `powershell.exe` with options to bypass profiles and allow script execution.

This method is useful for automating changes in configuration files or other text files, leveraging PowerShell's text manipulation capabilities and the simplicity of batch scripts for automation.

windows/replace-line-in-file.txt · Last modified: 2024/09/18 13:50 by odefta