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

请求合并两个PowerShell Active Directory脚本输出至同一文件

合并两个PowerShell脚本输出到同一文件的解决方案

这里有两种可行的方案帮你把两个AD相关脚本的输出合并到同一个文件里,根据你对输出格式的需求选择就行:

方案1:分块写入(带标题区分,适合可读性优先)

这个方案会把两部分内容用标题分隔开,分别写入同一个文本文件,既保留各自的输出格式,又清晰区分内容:

# 定义最终输出文件路径
$OutputPath = 'C:\Users\akouyoumjian\Desktop\CombinedADReport.txt'

# 第一部分:写入启用AD用户的最后登录信息
"=== 启用状态AD用户最后登录时间报告 ===" | Out-File -Path $OutputPath -Encoding utf8
Get-ADUser -Filter {Enabled -eq $true} -Properties LastLogonTimeStamp | 
    Select-Object Name, @{Name="LastLogonTimestamp"; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp).ToString('yyyy-MM-dd_hh:mm:ss')}} |
    Out-File -Path $OutputPath -Encoding utf8 -Append

# 第二部分:写入启用状态Windows 7计算机的操作系统信息
"`n=== 启用状态Windows 7计算机操作系统报告 ===" | Out-File -Path $OutputPath -Encoding utf8 -Append
Get-ADComputer -Filter {(OperatingSystem -like "Windows 7") -and (Enabled -eq $true)} -Properties OperatingSystem | 
    Sort-Object Name | 
    Select-Object -Unique OperatingSystem |
    Out-File -Path $OutputPath -Encoding utf8 -Append

说明:

  • 用Out-File -Append实现内容追加,确保两部分都写入同一文件
  • 添加了标题行和换行符,让不同模块的输出一目了然
  • 选择utf8编码避免乱码问题

方案2:统一CSV格式(适合后续数据处理)

如果需要输出为结构化的CSV文件方便后续分析,可以给两部分数据添加标识列,让整个CSV的结构统一:

# 定义最终输出CSV路径
$OutputPath = 'C:\Users\akouyoumjian\Desktop\CombinedADReport.csv'

# 处理AD用户数据:添加类型标识列
$userRecords = Get-ADUser -Filter {Enabled -eq $true} -Properties LastLogonTimeStamp | 
    Select-Object `
        @{Name="RecordType"; Expression={"Enabled AD User"}},
        Name,
        @{Name="Details"; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp).ToString('yyyy-MM-dd_hh:mm:ss')}}

# 处理Windows 7计算机数据:添加类型标识列
$computerRecords = Get-ADComputer -Filter {(OperatingSystem -like "Windows 7") -and (Enabled -eq $true)} -Properties OperatingSystem | 
    Sort-Object Name | 
    Select-Object -Unique `
        @{Name="RecordType"; Expression={"Enabled Windows 7 Computer"}},
        @{Name="Name"; Expression={$_.Name}}, # 保留计算机名称
        @{Name="Details"; Expression={$_.OperatingSystem}}

# 合并两组数据并导出到CSV
$userRecords + $computerRecords | Export-Csv -Path $OutputPath -NoTypeInformation -Encoding utf8

说明:

  • 给每条记录添加RecordType列,明确区分是用户还是计算机数据
  • Details列统一存储用户的登录时间或计算机的操作系统版本
  • 保留了计算机名称字段,让数据更完整

注意事项

  • 确保你的PowerShell环境已经加载了AD模块(可通过Import-Module ActiveDirectory手动加载)
  • 运行脚本时需要有足够的AD查询权限
  • 输出路径需确保有写入权限,若路径不存在可提前用New-Item -ItemType Directory -Path "路径目录"创建

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 07:52:37