如何从 Invoke-WebRequest 获取返回值

时间:2021-02-01 21:18:40

标签: powershell

我想弄清楚如何从 Invoke-WebRequest 获取结果以从 Internet 下载文件。我写了一个函数,但似乎没有得到结果。即使有效,StatusCode 和 StatusDescription 也不会改变:

val writeStream = ds.select("timeBucket")
  .groupBy("timeBucket")
  .count()
  .writeStream
  .foreach(...)      // persist to db
  .options(...)
  .outputMode(OutputMode.Update)
  .trigger("10 seconds")
  .start()

2 个答案:

答案 0 :(得分:0)

在评估 Invoke-WebRequest 返回的对象时获得状态代码

$response = Invoke-WebRequest -URI $url -OutFile $output -ErrorAction Stop
Write-Host $response.StatusCode

$r = Invoke-WebRequest -URI https://stackoverflow.com/questions/20259251/
Write-Host $r.StatusCode

https://davidhamann.de/2019/04/12/powershell-invoke-webrequest-by-example/

Powershell 实现了 OOP(面向对象编程)设计范式和语义,即在编写面向对象的代码时,每个类都必须有一个构造函数new())和一个析构函数,它应该有 get()set() 方法来访问(读取和写入)类的字段(或属性)。在 ps 中这是直接实现的

cmdlet 的返回值通常是对象(在 OOP 的意义上),您可以访问对象的字段以收集数据......

也可以在ps脚本中使用面向对象的设计模式https://dfinke.github.io/powershell,%20design%20patterns/2018/04/13/PowerShell-And-Design-Patterns.html

答案 1 :(得分:0)

如果您想在 $response 变量中包含某些内容,则在使用 -OutFile 时需要包含 -PassThru。

PowerShell 文档中 PassThru 的确切用途。

<块引用>

表示cmdlet返回结果,除了写 他们到一个文件。此参数仅在 OutFile 时有效 命令中也使用了参数。

例如

$response = Invoke-WebRequest -Uri 'www.google.com' 
if ( $response.StatusCode -eq 200 ) 
{ 
   #This bit runs for HTTP success
} 

$response = Invoke-WebRequest -Uri 'www.google.com' -OutFile 'googleHome.html'
if ( $response.StatusCode -eq 200 ) 
{ 
   #This never runs as $response never has a value even though the googleHome.html file gets created
} 

$response = Invoke-WebRequest -Uri 'www.google.com' -OutFile 'googleHome.html' -PassThru
if ( $response.StatusCode -eq 200 ) 
{ 
   #This bit runs for HTTP success and the file gets created
}