qJa*_*ake 50 powershell progress powershell-3.0
如何隐藏进度显示Invoke-WebRequest?我做了很多连续的请求并拥有自己的Write-Progress显示器,所以我不需要每次都在它下面弹出一个内置的显示器.
我使用从Invoke-WebRequest自动结果创建的mshtml结果(IE COM对象),因此我无法切换到WebClient类似的东西,除非有人提供有关如何从WebClient请求获取mshtml对象的说明.
Ant*_*ace 71
使用$ progressPreference变量.默认情况下,它应该具有"继续"值,除非您已在其他位置编辑它,这告诉Powershell显示进度条.由于您提到您有自己的自定义进度显示,因此我会在执行cmdlet后立即重置它.例如:
$progressPreference = 'silentlyContinue' # Subsequent calls do not display UI.
Invoke-WebRequest ...
$progressPreference = 'Continue' # Subsequent calls do display UI.
Write-Progress ...
Run Code Online (Sandbox Code Playgroud)
有关about_preference_variables上的首选项变量的更多信息.这是$ ProgressPreference的条目:
$ProgressPreference
-------------------
Determines how Windows PowerShell responds to progress updates
generated by a script, cmdlet or provider, such as the progress bars
generated by the Write-Progress cmdlet. The Write-Progress cmdlet
creates progress bars that depict the status of a command.
Valid values:
Stop: Does not display the progress bar. Instead,
it displays an error message and stops executing.
Inquire: Does not display the progress bar. Prompts
for permission to continue. If you reply
with Y or A, it displays the progress bar.
Continue: Displays the progress bar and continues with
(Default) execution.
SilentlyContinue: Executes the command, but does not display
the progress bar.
Run Code Online (Sandbox Code Playgroud)
这是一个可重用的函数,可以暂时隐藏任何脚本块的进度,并在脚本块结束时自动恢复进度首选项,即使脚本块抛出异常(脚本终止错误)也是如此。
# Create an in-memory module so $ScriptBlock doesn't run in new scope
$null = New-Module {
function Invoke-WithoutProgress {
[CmdletBinding()]
param (
[Parameter(Mandatory)] [scriptblock] $ScriptBlock
)
# Save current progress preference and hide the progress
$prevProgressPreference = $global:ProgressPreference
$global:ProgressPreference = 'SilentlyContinue'
try {
# Run the script block in the scope of the caller of this module function
. $ScriptBlock
}
finally {
# Restore the original behavior
$global:ProgressPreference = $prevProgressPreference
}
}
}
Run Code Online (Sandbox Code Playgroud)
使用示例:
Invoke-WithoutProgress {
# Here $ProgressPreference is set to 'SilentlyContinue'
Invoke-WebRequest ...
}
# Now $ProgressPreference is restored
Write-Progress ...
Run Code Online (Sandbox Code Playgroud)
笔记:
New-Module调用在那里,因此传递给的脚本块Invoke-WithoutProgress 不会在新范围中运行(允许它直接修改周围的变量,类似于 的ForEach-Object脚本块)。请参阅此答案以获取更多信息。| 归档时间: |
|
| 查看次数: |
19943 次 |
| 最近记录: |