Powershell Invoke-WebRequest [处理请求时发生错误]

Powershell Invoke-WebRequest [Error happened while processing request]

我正在开发一个自动创建 AD 用户的项目,在不同 departments/sections 中为用户创建文件夹,在创建 AD 用户时自动将密码发送到他们的手机和用户公司的启动包邮件。

我在 PowerShell 中执行此操作时遇到问题,这在 Python(我的主要语言)中效果很好。尝试在 powershell 中处理我的请求时出现这个奇怪的错误。

代码:

$url = "hiding_this_for_obvious_reasons" # Request URL

$nummer = Read-Host("Skriv inn mobil nummer: ")
$tekst = Read-Host("Skriv inn melding: ")

#Request Payload information
$JSON = @'
{
            "content": "$tekst",
            "senderNumber": "SSB",
            "targetNumbersAsDelimitedString": "47$nummer",
            "sendDate": null,
            "status": {"id": "5"},
            "numberOfTargetNumbers": null,
            "numberOfInvalidNumbers": ""
}
'@

Invoke-WebRequest -Uri $url -Method Post -Body $JSON -ContentType "application/json"

报错信息如下:

Invoke-WebRequest : Error happened while processing request 
At H:\Scripts\Powershell Scripts\ClearAD\SendSMSPowershell.ps1:19 char:1
+ Invoke-WebRequest -Uri $url -Method Post -Body $JSON -ContentType "ap ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebExce 
   ption
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

您似乎在尝试使用单引号内的变量。展开的变量需要双引号

试试这个:

$JSON = @"
{
            "content": "$tekst",
            "senderNumber": "SSB",
            "targetNumbersAsDelimitedString": "47$nummer",
            "sendDate": null,
            "status": {"id": "5"},
            "numberOfTargetNumbers": null,
            "numberOfInvalidNumbers": ""
}
"@