求助:如何在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
相关产品推荐
相关产品推荐

