使用Invoke-WebRequest遍历REST Api URL

时间:2015-12-21 10:58:38

标签: powershell httpwebrequest

使用PowerShell我试图调用webrequest来读取第一个请求$defUrl的入口点,然后读取每个URL中的后续端点。

enter image description here

上述内容在$UrlParsed之后返回:

enter image description here

然后我将其添加到第一个图像,以横向后续端点。

foreach ($Url in $UrlsParsed) {
  Invoke-WebRequest -uri $UrlsParsed -Credential $cred
}

添加foreach循环后,我收到以下错误。

enter image description here

我想获得的信息位于该网址的不同深度。

需要了解我可能做错了什么以及如何解决这个问题的建议。

2 个答案:

答案 0 :(得分:0)

改变这个:

foreach ($Url in $UrlsParsed) {
  Invoke-WebRequest -uri $UrlsParsed -Credential $cred
}

进入这个:

foreach ($Url in $UrlsParsed) {
  Invoke-WebRequest -uri $Url -Credential $cred
}

答案 1 :(得分:0)

经过一些帮助和反复试验,得到了我想要的结果。适当的评论代码。

$user = "darthmaul"
$pwd = "#deathStarOrder66" | ConvertTo-SecureString -asPlainText -Force

#This Url exposes all the service endpoint from a top level.
$defUrl = "https://weaponsTest1.galacticempire.co.uk/star-destroyer/api/v2/service_states?limit=1000"
$cred = New-Object System.Management.Automation.PSCredential($user,$pwd)
#connect to the first page that exposes all the URL
$stackStatus = Invoke-RestMethod -Uri $defUrl -Credential $cred

#appends only the service url for an individual service
$parsedUrls = $stackStatus.serviceUrl
#secure requests required else the call fails
$UrlsParsed = $parsedUrls.Replace("http","https")

#for each service found perform an addition call to determine the status of the service via a foreach loop 
foreach ($Url in $UrlsParsed)
{
    #use the individual url
    $sep = Invoke-WebRequest -uri $url -Credential $cred
    #select specific table you want to display and rename as you see fit.
    $svcStatus = $sep | select @{name="Response";Expression ={$_.statuscode}}, @{name="Status";Expression ={$_.statusdescription}} 
    #convert from json so you can select the field you want more easily.
    $svcCall = $sep | ConvertFrom-Json | select displayname, serviceTypeUrl, port, serviceport

    #in order to join those 2 variables together ($svcStatus & $svcCall)
    # add new members to the x.status object by appending svcCall.X to make it look like they are part of the object svcStatus.
    #
    $svcStatus | Add-Member -MemberType NoteProperty -Name displayname -Value $svcCall.displayname
    $svcStatus | Add-Member -MemberType NoteProperty -Name serviceTypeUrl -Value $svcCall.serviceTypeUrl
    $svcStatus | Add-Member -MemberType NoteProperty -Name port -Value $svcCall.port
    $svcStatus | Add-Member -MemberType NoteProperty -Name servicePort -Value $svcCall.servicePort

    #print out to view.
    $svcStatus | fl
}