隐藏 Invoke-WebRequest 的进度

如何隐藏 Invoke-WebRequest的进度显示?我做了很多连续的请求,并有我自己的 Write-Progress显示器,我使用,所以我不需要内置的一个弹出下面,每次。

我使用从 Invoke-WebRequest的结果自动创建的 mshtml 结果(IE COM 对象) ,所以我不能切换到 WebClient或类似的东西,除非有人提供如何从 WebClient 请求获取 mshtml 对象的说明。

49627 次浏览

使用 $ProgressPreferences 变量。默认情况下,它应该有一个“ Contine”值,除非您已经在其他地方进行了编辑,这将告诉 Powershell 显示进度条。既然您提到您有自己的自定义进度显示,那么我将在 cmdlet 执行后立即重置它。例如:

$ProgressPreference = 'SilentlyContinue'    # Subsequent calls do not display UI.
Invoke-WebRequest ...
$ProgressPreference = 'Continue'            # Subsequent calls do display UI.
Write-Progress ...

更多关于偏好变量的信息请看 About _ 偏好 _ 变量:

$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.

下面是一个 可重用功能,它可以暂时隐藏任何 脚本块的进度,并在脚本块结束时自动恢复进度首选项,脚本块抛出 即使是例外(脚本终止错误)。

# 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
}
}
}

用法例子:

Invoke-WithoutProgress {
# Here $ProgressPreference is set to 'SilentlyContinue'
Invoke-WebRequest ...
}


# Now $ProgressPreference is restored
Write-Progress ...

备注:

  • New-Module调用存在,所以脚本块传递给 Invoke-WithoutProgress 不能在新的范围内运行(允许它直接修改周围的变量,类似于 ForEach-Object的脚本块)。有关更多信息,请参见 这个答案