P. Grunder P. Grunder - 1 year ago 109
PowerShell Question

Overwriting specific Line in multiple Files using PowerShell with User Input

Im trying to get my PowerShell Script to read the specific line 8 on different

files in multiple folders and overwrite it using a premade text and an input made by the user in a textbox.

PowerShell Script:

if ($textbox1.TextLength -eq 0)
$listBox1.Items.Add("Please Register your Release Number!")
#saving the number in releasenr
$releasenr = $textbox1.Text

#TODO: Loop which goes into every file on different Folders and replaces
#line 8 in all .ctl files with following text: "rel_nr constant "$releasenr""

$listBox1.Items.Add("Release Number has been overwritten")
$listBox1.Items.Add("You can now proceed your Upload")

Is there a way to use a for loop to do the overwriting process foreach file that is in a current folder?

Answer Source

Use the Get-ChildItem cmdlet to retrieve the files, iterate over it using the ForEach-Object cmdlet, read the content of the file using Get-Content, overwrite the specific line and finally write the text back to the file using the Set-Content cmdlet:

Get-ChildItem 'yourFolder' -Filter '*.ctl' | ForEach-Object {
    $content = Get-Content $_
    $content[7] = 'rel_nr    constant "{0}"' -f $releasenr
    $content | Set-Content -Path $_.FullName
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download