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

PowerShell脚本无法在日志文件名中添加用户名,请求技术指导

PowerShell日志文件名拼接问题解决办法

原脚本在添加用户名到日志文件名时出现语法错误,核心问题是字符串拼接的语法不符合PowerShell规则,以下是修正后的可行方案:

方案一:提前提取变量(可读性更高)

while ($true) {
    # 先获取TCP连接信息,避免重复执行命令
    $tcpConn = Get-NetTCPConnection -RemoteAddress 10.86.178.10
    if (-not [String]::IsNullOrEmpty($tcpConn.OwningProcess)) {
        # 提取当前登录用户名(仅保留域名后的部分)
        $username = (Get-CimInstance CIM_ComputerSystem).Username.Split("\")[1]
        # 拼接符合要求的日志路径
        $logPath = "\\fuobomdt01.ap.win.int.kn\Wechat\10.200.0.34\$env:computername`_$username.log"
        # 将进程信息追加到日志并退出循环
        Get-Process -Id $tcpConn.OwningProcess >> $logPath
        break
    }
}

方案二:直接在路径中使用表达式插值

while ($true) {
    $tcpConn = Get-NetTCPConnection -RemoteAddress 10.86.178.10
    if (-not [String]::IsNullOrEmpty($tcpConn.OwningProcess)) {
        # 用$()包裹需要计算的表达式,PowerShell会先解析表达式再拼接字符串
        Get-Process -Id $tcpConn.OwningProcess >> "\\fuobomdt01.ap.win.int.kn\Wechat\10.200.0.34\$env:computername`_$((Get-CimInstance CIM_ComputerSystem).Username.Split("\")[1]).log"
        break
    }
}

错误原因说明

原修改后的脚本中,$env:computername"_"((gcim cim_computersystem).username).split("\\")[1].log 的写法不符合PowerShell字符串语法:

  • 直接用双引号拼接字符串和表达式会导致解析混乱
  • 嵌套的表达式需要用$()包裹,让PowerShell优先计算表达式结果再参与字符串拼接

另外,将Get-NetTCPConnection的结果存入变量,避免了重复执行同一命令,提升了脚本效率。

内容的提问来源于stack exchange,提问作者饿到自然醒

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 15:54:56