如何解决任务计划程序截断PowerShell输出至80字符的问题?
解决任务计划程序PowerShell输出80列截断问题
不管用什么格式设置或输出方法,都绕不开任务计划程序默认将PowerShell输出截断为80列的限制。我试过以下几种方法都没解决:
- 执行带
Out-String -Width 120的命令:Get-CimInstance -computerName $glfServers -Class Win32_OperatingSystem | Sort-Object csName | Format-Table -Property $csName, $serverStatus, $totalVisibleMemorySize, $freePhysicalMemory, $memoryUsage, $freeSpaceInPagingFiles, $lastBootTime | Out-String -Width 120 | Out-File 'C:\Scripts\OutputFiles\ServerMemory\PyhsMem.txt' - 用
Tee-Object同时输出到控制台和文件,发现任务计划程序的输出和直接执行不一致 - 尝试
Format-Table -Autosize、直接用Out-File等常规格式方法
经过多日搜索,找到有效的解决方案:
方案1:在脚本中设置控制台缓冲区宽度
在脚本开头添加以下代码,强制设置缓冲区宽度,避免截断:
# 设置缓冲区宽度为200(可根据需求调整) $Host.UI.RawUI.BufferSize = New-Object Management.Automation.Host.Size(200, 5000)
然后再执行输出命令,配合指定宽度的Out-File:
Get-CimInstance -computerName $glfServers -Class Win32_OperatingSystem | Sort-Object csName | Format-Table -Property $csName, $serverStatus, $totalVisibleMemorySize, $freePhysicalMemory, $memoryUsage, $freeSpaceInPagingFiles, $lastBootTime | Out-File 'C:\Scripts\OutputFiles\ServerMemory\PyhsMem.txt' -Width 200
方案2:修改任务计划程序的执行参数
在任务计划程序的「行动」设置中,将PowerShell的执行命令改为:
powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "& {C:\Scripts\你的脚本路径.ps1}" -WindowStyle Hidden
通过-Command调用脚本而非直接指定路径,能让脚本内的缓冲区设置生效,绕过任务计划程序的默认80列限制。
内容的提问来源于stack exchange,提问作者DougR
相关产品推荐
相关产品推荐

