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

求助:如何在PowerShell脚本中添加主机名并与弹窗结果一同输出至文件

解决PowerShell弹窗结果与主机名同时输出的问题

要实现同时输出用户选择结果和计算机主机名,只需两步:获取主机名,再将其与弹窗结果组合输出。

核心操作说明

  • 获取主机名:直接读取系统环境变量$env:COMPUTERNAME,这是最快捷的方式,无需额外命令
  • 组合输出内容:可选择普通文本拼接或结构化格式输出,按需选择

方式一:普通文本格式输出

修改后的脚本如下:

Add-Type -AssemblyName PresentationCore,PresentationFramework

$msgBody = "Your computer will restart soon 

Do you want to restart now ?"

$msgTitle = "Confirm Reboot"
$msgButton = 'YesNoCancel'
$msgImage = 'Question'
$Result = [System.Windows.MessageBox]::Show($msgBody,$msgTitle,$msgButton,$msgImage)

# 获取计算机主机名
$computerName = $env:COMPUTERNAME
# 拼接输出内容
$outputContent = "Hostname: $computerName, User Choice: $Result"
# 输出到共享文件(可加-Encoding utf8解决乱码问题,-Append实现追加记录)
$outputContent | Out-File \\share\xxxxx -Append -Encoding utf8

方式二:结构化CSV格式输出(推荐,便于后续批量处理)

如果需要后续对数据进行统计或分析,输出为CSV格式更合适:

Add-Type -AssemblyName PresentationCore,PresentationFramework

$msgBody = "Your computer will restart soon 

Do you want to restart now ?"

$msgTitle = "Confirm Reboot"
$msgButton = 'YesNoCancel'
$msgImage = 'Question'
$Result = [System.Windows.MessageBox]::Show($msgBody,$msgTitle,$msgButton,$msgImage)

# 获取主机名并生成自定义对象(可选添加时间戳记录操作时间)
$outputObj = [PSCustomObject]@{
    Hostname = $env:COMPUTERNAME
    UserChoice = $Result
    Timestamp = Get-Date
}

# 输出到CSV文件(-Append追加记录,-NoTypeInformation避免多余表头)
$outputObj | Export-Csv \\share\xxxxx.csv -Append -NoTypeInformation -Encoding utf8

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 16:37:47