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

如何用PowerShell将服务账户修改前后的用户名存入CSV(修改后获取异常)

问题分析与修正脚本

原脚本无法获取修改后账户信息的核心原因:

  1. 修改服务账户后未重新查询最新的服务对象,仍使用修改前的$service变量,导致$AfterChangeAccount始终是旧值
  2. 远程会话(Invoke-Command)内的变量无法直接在本地会话中访问
  3. CSV导出逻辑存在语法错误且未使用追加模式,会覆盖之前的结果

以下是修正后的完整脚本:

$complist = Get-Content "c:\scripts\computers.txt"
# 提前定义输出路径,修正语法错误
$outputPath = "c:\Temp\ServiceList_-$(Get-Date -Format 'MM-dd-yyyy').csv"

foreach($computer in $complist){
    Write-Host "Checking on $computer" -ForegroundColor yellow
    Write-Host ""

    $pingtest = Test-Connection -ComputerName $computer -Quiet -Count 1 -ErrorAction SilentlyContinue

    if($pingtest){
        Write-Host "$computer is online" -ForegroundColor Green
        
        # 从远程会话返回修改前后的完整服务信息
        $serviceInfo = Invoke-Command -ComputerName $computer {
            # 获取修改前的服务状态与账户
            $serviceBefore = Get-WmiObject win32_service -Filter "name='ontapavc'"
            $BeforeChangeAccount = $serviceBefore.StartName

            Write-Host ""   
            Write-Host "Logon Credentials for " -ForegroundColor cyan -NoNewline
            Write-Host $serviceBefore.DisplayName -NoNewline
            Write-Host " prior to Script Change: " -ForegroundColor cyan -NoNewline
            Write-Host $BeforeChangeAccount
            
            # 修改服务启动账户
            Write-Host "" 
            Write-Host "Setting default logon Credentials" -ForegroundColor yellow
            sc.exe CONFIG "ontapavc" obj= Home\Tester password= "Testing"  
            
            # 设置服务恢复选项
            Write-Host ""
            Write-Host "Setting Recovery Options" -ForegroundColor yellow
            sc.exe failure "ontapavc" reset= 60000 actions= restart/60000/restart/60000/reboot/60000
            
            # 停止并重启服务
            Write-Host ""
            Write-Host "Stopping service " -ForegroundColor yellow -NoNewline
            Write-Host $serviceBefore.Name 
            Stop-Service -Name "ontapavc" -PassThru 
            
            Write-Host "" 
            Write-Host "Restarting service " -ForegroundColor yellow -NoNewline
            Write-Host $serviceBefore.Name
            Start-Service -Name "ontapavc" -PassThru  
            
            # 重新查询服务,获取修改后的账户信息
            $serviceAfter = Get-WmiObject win32_service -Filter "name='ontapavc'"
            $AfterChangeAccount = $serviceAfter.StartName

            # 返回结构化数据到本地会话
            [PSCustomObject]@{
                Time = (Get-Date -Format s)
                PSComputerName = $env:COMPUTERNAME
                Name = $serviceAfter.Name
                DisplayName = $serviceAfter.DisplayName
                ServiceName = $serviceAfter.Name
                Status = $serviceAfter.State
                UsernamePriorToChange = $BeforeChangeAccount
                UsernameAfterChange = $AfterChangeAccount
            }
        }

        # 本地输出修改后的账户信息
        Write-Host ""
        Write-Host "Logon Credentials for " -ForegroundColor cyan -NoNewline
        Write-Host $serviceInfo.DisplayName -NoNewline
        Write-Host " after Change:" -ForegroundColor cyan -NoNewline
        Write-Host $serviceInfo.UsernameAfterChange

        # 追加写入CSV,避免覆盖历史数据
        $serviceInfo | Export-Csv -Path $outputPath -NoTypeInformation -Append
    }
    else{
        Write-Host "$computer is not reachable" -ForegroundColor red
        Write-Host ""
    }
}

关键修改说明

  • 重新查询服务对象:修改账户后,必须再次调用Get-WmiObject获取最新的服务实例,才能读取到更新后的启动账户
  • 远程会话数据传递:通过返回自定义PSCustomObject,将远程会话中的修改前后账户信息传递回本地,解决跨会话变量不可访问的问题
  • CSV导出优化:使用-Append参数实现追加写入,避免每次循环覆盖之前的结果;同时修正了路径中的语法错误
  • 简化服务操作:直接使用Stop-Service/Start-Service的-Name参数,无需额外过滤服务对象,提升脚本效率

内容的提问来源于stack exchange,提问作者Interested In PowerShell

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 14:55:22