从文本文件的多个 URL 调用 RestMethod

Invoke-RestMethod from multiple URLs from text file

需要通过文本文件中的几个链接使用带有 Invoke-RestMethod 的 PowerShell 脚本获得帮助:

我没有但适用于单个站点的内容:

$username = 'username'
$password = 'password'
$accept = 'application/xml'
$uri = 'https://example.com/ping/id/31'
$headers = @{
    "Accept"=$accept
}
$secpwd = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($username, $secpwd)
Invoke-RestMethod -Method Post -Uri $uri -Headers $headers -Credential $credential

但是需要对多个链接执行此操作。 有什么建议可以实现吗?

假设您想对每个 URL 使用相同的用户名和密码等,请尝试这样的操作:

$username = 'username'
$password = 'password'
$accept = 'application/xml'
$headers = @{
    "Accept"=$accept
}
$secpwd = ConvertTo-SecureString $password -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($username, $secpwd)
Get-Content .\file_with_one_url_per_line | ForEach-Object { Invoke-RestMethod -Method Post -Uri $_ -Headers $headers -Credential $credential }

ForEach-Object cmdlet 将执行您为文件中的每一行提供的代码块中的任何内容,将 $_ 替换为该行。