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

如何让PowerShell脚本将HTML报告保存至运行脚本的U盘路径?

解决PowerShell脚本U盘路径保存HTML报告的问题

你可以通过PowerShell的自动变量或获取执行文件路径的方式,动态定位脚本/可执行文件所在的U盘目录,实现报告的正确保存,具体方法如下:

针对未打包的.ps1脚本

直接使用$PSScriptRoot自动变量,它会返回当前脚本所在的完整目录路径,不管U盘盘符如何变化都能准确定位:

$Report = ConvertTo-HTML -Body "$ComputerName $OSinfo $ProcessInfo $BiosInfo $DiscInfo $ServicesInfo" -Head $header -Title "Computer Information Report" -PostContent ""

# 获取脚本所在的U盘目录
$scriptDir = $PSScriptRoot
# 拼接报告保存路径
$reportPath = Join-Path -Path $scriptDir -ChildPath "Test.html"
# 输出到目标路径
$Report | Out-File $reportPath

Join-Path命令会自动处理路径分隔符,比手动拼接字符串更可靠,避免出现路径格式错误。

针对打包后的可执行文件(EXE)

如果脚本被打包成EXE运行,$PSScriptRoot可能指向临时目录,这时候可以通过$MyInvocation.MyCommand.Source获取EXE文件的完整路径,再提取所在目录:

$Report = ConvertTo-HTML -Body "$ComputerName $OSinfo $ProcessInfo $BiosInfo $DiscInfo $ServicesInfo" -Head $header -Title "Computer Information Report" -PostContent ""

# 获取EXE文件的完整路径
$exePath = $MyInvocation.MyCommand.Source
# 提取EXE所在的U盘目录
$scriptDir = Split-Path -Path $exePath -Parent
# 拼接报告保存路径
$reportPath = Join-Path -Path $scriptDir -ChildPath "Test.html"
# 输出到目标路径
$Report | Out-File $reportPath

这样修改后,不管U盘插在哪个电脑上,报告都会自动保存到脚本/EXE所在的U盘目录下。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 04:05:24