As a follow-up to this question, instead of using a long array in the script I wanted to draw from a text file. So I replaced this:
$URLs = 'http://websiteone.com','http://websitetwo.com','http://websitethree.com'
with this
$URLs = Get-Content ./urlfile.txt
or (functionally the same as far I know) this
$URLs = @(Get-Content ./urlfile.txt)
But I end up with Invoke-RestMethod : The remote server returned an error: (400) Bad Request.
Incorporating the great response form my last question, my foreach loop looks like this:
foreach($URL in $URLs) {
$BODY = @([pscustomobject]@{"client" = @{"clientId" = "company"; "clientVersion" = "1.0"}; "threatInfo" = @{"threatTypes" = "MALWARE","SOCIAL_ENGINEERING","THREAT_TYPE_UNSPECIFIED","UNWANTED_SOFTWARE","POTENTIALLY_HARMFUL_APPLICATION"; "platformTypes" = "ANY_PLATFORM"; "threatEntryTypes" = "URL","EXECUTABLE","THREAT_ENTRY_TYPE_UNSPECIFIED"; "threatEntries" = @{"url" = $URL}}})
$JSONBODY = $BODY | ConvertTo-Json
$Result = Invoke-RestMethod -Method 'POST' -Uri $Uri -Body $JSONBODY -Headers $HEADERS
if ( ([string]::IsNullOrEmpty($Result)) ) {} else {write-host $URL "ALERT: Safe browsing match!"}
}
... but this doesn't work if I create the array with the Get-Content cmdlet. If I run the script either way, then type $URLs, I get the exact same data returned. What am I doing wrong with get-content?
The
Invoke-RestMethodcmdlet is there to make oneRestrequest at a time and can't take an array.You will need to add a
forEachloop to step through your$urlsone at a time, something like this:So to integrate into your sample from the previous question, you should have a
urls.txtfile which looks like this:And then your code would look like this:
This would load up the list of
$urlsfrom your text file, then run a Rest Request on each, storing the result in$result. Finally, it will make a new PowerShell Object with the site name and show you if there are any matches from the Google SafeBrowsing API.You'll need to run the command interactively and see which properties from
$resultare meaningful to you, but you can see all of the expected properties in the Google API Docs.Edit
Found the bug. It turns out when we use
Get-Contentthe object returned back retains some of the document formatting information from the original file! We can see this by inspecting$JSONBODY. We also see that the conversion toJsonfrom[PSCustomObjectis leaving a lot of cruft behind too.To fix this, we should cast
$URLinto a string using theToString()method and also ditch casting to[psCustomObject]too as shown below.