2015-12-21 58 views
0

使用PowerShell我試圖調用一個webrequest,它讀取第一個請求$defUrl的入口點,然後是每個URL內的後續端點。使用Invoke-WebRequest遍歷REST Api 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

更改此:

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

到這一點:

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

試過以前沒有成功。據我瞭解,每一個人的要求都應該通過。 想我可能需要創建一個新的對象,然後用它來通過循環調用一個新的請求。 – ifeanyi

+0

定義「不成功」。 –

+0

是的,我應該更清楚。 同樣的異常被拋出。 – ifeanyi

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 
}