You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用PowerShell脚本替换nginx.conf中指定的三行内容

使用PowerShell脚本替换nginx.conf中指定的多行内容

需求说明

需要替换nginx.conf里的三行log_format配置:

  • 原目标内容:
log_format  main  '$remote_addr - $remote_user [$time_local] "&$request" '
                   '$status $body_bytes_sent "&$http_referer" '
                   '&"$http_user_agent" "&$http_x_forwarded_for"';
  • 替换为:
log_format  main  '$remote_addr - $remote_user $time_iso8601 [$request_time] "&$request" '
                     '$status $body_bytes_sent "&$http_referer" '
                     '&"$http_user_agent" "&$http_x_forwarded_for"';

原脚本的问题

原脚本用脚本块{}定义$Find和$Replace是错误的,脚本块无法被当作字符串处理,会直接导致匹配失败;另外未指定文件编码,可能引发配置文件乱码。

修正后的脚本

$Nginx_home = "I:\nginx\nginx-1.22.1"
$filePath = "$Nginx_home\conf\nginx.conf"

# 备份原配置文件
$now = (Get-Date).ToString("MM-dd-yyyy_HH_mm_ss")
Copy-Item -Path $filePath -Destination "$Nginx_home\conf\nginx_$now.conf" -PassThru

# 用Here-String定义要查找的多行内容,完整保留原始格式
$Find = @"
log_format  main  '$remote_addr - $remote_user [$time_local] "&$request" '
                   '$status $body_bytes_sent "&$http_referer" '
                   '&"$http_user_agent" "&$http_x_forwarded_for"';
"@

# 定义替换后的多行内容
$Replace = @"
log_format  main  '$remote_addr - $remote_user $time_iso8601 [$request_time] "&$request" '
                     '$status $body_bytes_sent "&$http_referer" '
                     '&"$http_user_agent" "&$http_x_forwarded_for"';
"@

# 读取文件并执行替换,指定UTF8编码避免乱码
(Get-Content $filePath -Raw -Encoding UTF8) -replace [regex]::Escape($Find), $Replace | 
    Set-Content $filePath -Encoding UTF8

核心注意事项

  • 用Here-String保存多行文本:Here-String能完整保留文本的换行、空格格式,确保和nginx.conf里的内容完全匹配,不会因格式差异导致匹配失败。
  • 正则转义特殊字符:[regex]::Escape()会把查找内容里的正则特殊字符(比如[]、$)转义成普通字符,避免被正则引擎误解析。
  • 指定文件编码:nginx.conf通常采用UTF8编码,读取和写入时指定-Encoding UTF8,防止出现乱码问题。
  • 先备份再修改:操作前自动备份原文件,避免意外操作导致配置丢失。

内容的提问来源于stack exchange,提问作者anand8398

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 16:40:26