Add the below line after the word "server {" in nginx.conf file.
location /nginx-status {
stub_status on;
allow all;
}
Using the script below adds a new line next to the word "server {" wherever that word occurs.
$Nginx_home = "I:Anandnginx-1.22.1"
$filePath = "$Nginx_homeconfnginx.conf"
$textToAdd1 = {
location /nginx-status {
stub_status on;
allow all;
}
}
$content = Get-Content $filePath
# Replace the specific word with the word followed by a new line character
$content = $content -replace "server {", "server {`n$textToAdd1"
# Write the updated contents back to the text file
Set-Content $filePath $content
The nginx.conf file contains more than one word "server {". But I need to find the word first and add the below lines to the next line.
location /nginx-status {
stub_status on;
allow all;
}
2
Answers
Use the
ForEach-Object
to inspect each line as it passes through the pipeline, add the extra content after the line you’re looking for:I would use
switch
for this and keep track if you have already inserted the new text in order to only do that once: