使用Invoke-WebRequest上传文件

时间:2020-03-21 13:47:51

标签: powershell powershell-core

使用PowerShell 7,我成功使用Invoke-RestMethod上传了一个文件:

$Uri = '...(my url)...'
$File = '...(path to my file)...'
$Form = @{
    f = Get-Item -Path $File
}
$Result = Invoke-RestMethod -Uri $Uri -Method Post -Form $Form -StatusCodeVariable 'HttpStatus'

我想对Invoke-WebRequest做同样的事情;我更喜欢Invoke-WebRequest,因为它的返回值具有内部状态和内容字段的便捷结构,因此我可以摆脱$ HttpStatus变量,而只需使用'$ Result.Content |将结果转换为JSON。 ConvertFrom-Json'。

在Invoke-WebRequest cmdlet的文档中有一个上载示例:https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/invoke-webrequest?view=powershell-7,示例6。但是它使用Invoke-RestMethod cmdlet。这不是文档中的错字吗?是否可以像Invoke-RestMethod示例中那样简单地使用Invoke-WebRequest?

1 个答案:

答案 0 :(得分:0)

我成功用Invoke-WebRequest替换了代码中的cmdlet:

$Result = Invoke-WebRequest -Uri $Uri -Method Post -Form $Form -SkipHttpErrorCheck
$httpStatus = $Result.StatusCode
if ($httpStatus -eq 200)
{
    $j = $Result.Content | ConvertFrom-Json
    . . . .
}

FoxDeploy,您的评论很有帮助。谢谢。