looking for help with setting response for the powershell script

Copper Contributor


I am SQL DBA, don't know much about powershell. I created one powershell script to push data to a website, using invoke-restmethod. My script works fine, but I don't know how can I set up some response from script. For eg- if script works well, I want it to send some response like 'success' & if it fails, it says 'failed' or tell me why it failed. Is there a way to do that ?

script sample:

$Uri = 'https://someURL'
$Body = @{
u_interface = 'DBA'
u_month_year = '202401'
u_login_name = 'USERNAME'
u_account_status = 'USERNAME(User),USERNAME(MemberOf)'
} | ConvertTo-Json

$Headers= @{"Accept"="application/json"

$svc_pwd=ConvertTo-SecureString "password" -AsPlainText -Force
$svc_cred = New-Object Management.Automation.Pscredential ( 'userforURL', $user_pwd)
$Result = Invoke-RestMethod -Uri $Uri -headers $Headers -Method Post -Body $Body -Credential $user_pwd

2 Replies



Hi, Mudit.


We can't answer this, as every web service/API/site is different. This, therefore, isn't about PowerShell but rather your specific web service.


Some web services will leverage the traditional status-code header, where a return status code in the 400 and above categories will cause Invoke-RestMethod (and Invoke-WebRequest) to throw an exception.


To intelligently handle such an exception, you'd need to include the -ErrorAction:Stop parameter in the Invoke-RestMethod call, and use the try/catch structure to handle the thrown exception.



However, some web services may opt to unconditionally return a valid web request (i.e. status-code in the 200 and 300 ranges) and include any errors in the response body (commonly seen in JSON service implementations).


Yet others might use non-standard headers.


Even when a request is "successful" (i.e. the status-code is in the 200 and 300 ranges), you might find that your web services expects you to behave in a certain manner based on the code returned. This is a much subtler scenario where you will need to use Invoke-WebRequest instead of Invoke-RestMethod, since the latter doesn't provide the response header to work from (while the former does).


To get your answer, you'll need to read the documentation for and/or play around with the web service you're talking to (assuming you can without impacting production) and deliberately trigger erroneous scenarios so you can learn how to adapt to it's specific requirements.





Thank you very much. This explains a lot and is very helpful.