POSTing data to ServiceNow via Powershell using Invoke-WebRequest - powershell

I am trying to POST information into a table in ServiceNow via a Powershell script. When I run it I get an error
Invoke-WebRequest : The remote server returned an error: (500) Internal Server Error.
Can someone help me figure out how to solve this? Thank you all in advance.
$userName = 'helpMe'
$password = 'iAmStuck' | ConvertTo-SecureString -asPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($userName, $password)
$uri = 'stuff'
$postParams = "test"
#[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
Invoke-WebRequest -Uri $uri -Method Post -Body $postParams -Credential $cred

ServiceNow has a REST API explorer with various code examples to start working with.
Below is an example that I threw together that posts to the incident table with an admin account. Two important factors here, the user must have roles (here for info https://docs.servicenow.com/bundle/istanbul-servicenow-platform/page/integrate/inbound-rest/reference/r_RESTAPIRoles.html) to use the API and must have access to the table you are trying to post to. Also, note that the body of the post needs to be RAW JSON and all the correct header data is supplied in the URL. If successful ServiceNow will return JSON data about the post.
# Eg. User name="admin", Password="admin" for this code sample.
$user = "admin"
$pass = "noPassword"
# Build auth header
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user, $pass)))
# Set proper headers
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add('Authorization',('Basic {0}' -f $base64AuthInfo))
$headers.Add('Accept','application/json')
$headers.Add('Content-Type','application/json')
# Specify endpoint uri
$uri = "https://xxxxx.service-now.com/api/now/table/incident"
# Specify HTTP method
$method = "post"
# Specify request body
{request.body ? "$body = \"" :""}}{\"active\":\"true\",\"number\":\"123\",\"short_description\":\"test\"}"
# Send HTTP request
$response = Invoke-WebRequest -Headers $headers -Method $method -Uri $uri -Body $body
# Print response
$response.RawContent

Even though you posted code, you posted nothing relevant to the problem. Whatever ServiceNow is might have an API for reference on what it's expecting. Often when interacting with web-based APIs, there is a structure that is required for the API to be able to understand the data you're supplying in $postParams. Sometimes it can just be key->value pairs in the case of a flat HTTP POST but often times for RESTful APIs you'll need to structure a JSON header as defined by the API documentation.
If you do a search for "servicenow powershell interaction" it looks like there's a GitHub project for interacting with ServiceNow via PowerShell and also a PDF that specifcally covers this topic.

Related

need to add authentication header to azure devops api request

I'm trying to get information on my latest builds by sending a GET request to the Azure DevOps REST Api. I'm using Azure DevOps Server 2020 with the Patch 1 update. I need to add an authorization header to the request. The header I added is not working.
I'm doing the request in Powershell. Here's my code:
$PAT = 'personal access token'
$ENCODED = [Convert]::ToBase64String([Text.Encoding]::Unicode.GetBytes($PAT))
$headers = #{
Authorization="Basic $ENCODED"
}
Invoke-RestMethod -Uri [azure devops server url]/[project name]/_apis/build/latest/Build?api-version=5.0 -Method Get -Headers $headers
When I run the code I get the error: Invoke Method: The format of value [PAT] is invalid
UPDATE:
I updated the header syntax. Now the reponse I get:
Invoke-RestMethod:
TF400813: Resource not available for anonymous access. Client authentication required. - Azure DevOps Server
I also tried passing my Azure DevOps username and password in the header like this:
$headers = #{
Authorization="Basic [domain\username]:[password]"
}
and I got this in response:
Invoke-RestMethod: Response status code does not indicate success: 401 (Unauthorized).
Do I have to enable some setting in Azure DevOps?
I usually reference to this demo to run REST API in PowerShell, it can work fine:
$uri = "request URI"
$pat = "personal access token"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f "", $pat)))
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", ("Basic {0}" -f $base64AuthInfo))
$headers.Add("Content-Type", "application/json")
. . .
$body = "{
. . .
}"
Invoke-RestMethod -Uri $uri -Headers $headers -Body $body -Method POST
In your case, the issue seems is caused by the encoding. Try using ASCII or UTF8, instead of Unicode.
To view more details, you can see "Use personal access tokens".

Create folder in user mailbox with Graph API

want to use the Graph API to create a folder in a user's mailbox that exists in Exchange Online.
As a result of the investigation, if I use "https://graph.microsoft.com/v1.0/users/testuser01#domain.com/mailFolders", I feel that it is possible, but an error is displayed and I cannot create it.
Currently, "Exchange> Mail.ReadWrite, MailboxSettings.ReadWrite" is assigned to the execution user (admin).
However, it says "Access is denied. Check credentials and try again." Is the permission wrong?
Or is the specified URL incorrect?
Sorry to trouble you, but thank you for your response.
【Append】
$body = #{
grant_type="client_credentials"
resource=$resource
client_id=$ClientID
client_secret=$ClientSecret
}
`#Get Token
$oauth = Invoke-RestMethod -Method Post -Uri $loginURL/$TenantName/oauth2/token -Body $body
API Permissions
You are using the client credential flow to get the token to call Microsoft Graph - Create MailFolder, so you need to add the Application permission Mail.ReadWrite of Micrsoft Graph to your AD App.
1.Add the Application permission Mail.ReadWrite like below.
2.Click the Grant admin consent for xxx button, and make sure the $resource in your request is https://graph.microsoft.com.
Update:
Here is a powershell sample to call Create MailFolder API to create MailFolder.
$uri = "https://graph.microsoft.com/v1.0/users/joyw#xxxxx.onmicrosoft.com/mailFolders"
$headers = #{
'Content-Type' = 'application/json'
'Authorization' = 'Bearer <access-token-here>'
}
$body = ConvertTo-Json #{
"displayName" = "testfolder1"
}
Invoke-RestMethod -Method Post -Uri $uri -Headers $headers -Body $body
Check the result in the Graph Explorer with List mailFolders:

REST API: adapt a cURL POST to Powershell 5 (upload files)

I have this cURL command that I must adapt to Powershell in order to upload different files. In order to do that, I have mandatory fields that I need use in the request.
I've tried like a dozen of different scripts, nothing works.
Can someone help me out with this?
It should be plain simple, but I am missing something.
cURL command:
curl -H "Authorization: Bearer xxx"
-F "parentDirectoryId=1"
-F "name=AutoUpload"
-F "contents=#C:\temp\test.pdf"
https://url/v1/api/files?
This is going to depend on which version of Powershell you are using. If you have Powershell 6 you can use the simple method below which uses the form parameter. If you use another version you can use the more complicated example #4 which is outlined on the Microsoft Docs:
$Uri = 'https://url/v1/api/files?'
$Form = #{
parentDirectoryId= '1'
name = 'AutoUpload'
contents= Get-Item -Path 'C:\temp\test.pdf'
}
$token = ConvertTo-SecureString "xxx" -AsPlainText -Force
$Result = Invoke-RestMethod -Uri $Uri -Method Post -Form $Form -Authentication Bearer -Token $token
This example uses the new Authentication and Form parameters in Invoke-RestMethod. Depending on your Authentication type, you will need either a Token or Credentials parameter with additional information. The Form parameter simplifies what was previously a complicated process for adjusting the body or URI per request.

How to authenticate without sending my username and password for HTTP requests?

Currently, following is how I am sending request from PS to update a parameter:
$pair="$("username"):$("password")"
$encodedCreds=[System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$basicAuthValue="Basic $encodedCreds"
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Authorization", $basicAuthValue)
$headers.Add("Content-Type", 'text/plain')
$headers.Add("Origin", 'https://teamcity.server.io')
Invoke-RestMethod -Method Put -Uri $url -Headers $headers -Body $updated_version
But I do not want my username and password mentioned like this anymore.
What other ways do I have to authenticate myself for HTTP requests made within from TeamCity Build Step through PS?
Had to use the basic auth but instead of using my own credentials used a super user created by the dev ops that is available to everyone in the company.

PowerShell Invoke-Webrequest not compatible with site?

I've seen many examples of Invoke-Webrequest and I've already had some success with it myself, however, one site where I was trying to automate my login just hasn't worked no matter what I try. Here is the code:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 # This is required so that HTTPS requests won't fail with Invoke-WebRequest
$r = Invoke-WebRequest -Uri https://order.swisschalet.com -SessionVariable sc
$r.forms[0].fields['form-login-header-email'] = "MyEmail"
$r.forms[0].fields['form-login-header-password'] = 'MyPassword'
$a = Invoke-WebRequest -Uri ("https://order.swisschalet.com" + $r.forms[0].Action) -WebSession $sc -Method POST -Body $r.forms[0]
I have tried using Fiddler 4 to analyze what is going on but it has only confused me even more. When I manually go to the website Fiddler shows 'email' and 'password' fields that were posted rather than what originally came back in the forms which is 'form-login-header-email' and 'form-login-header-password'. However, even if I try to create these new fields and POST them it still doesn't work. Fiddler shows that going to the website manually also creates some kind of synchronization token called 'org.codehaus.groovy.grails.SYNCHRONIZER_TOKEN'.
I am beginning to wonder if Invoke-WebRequest is simply incompatible with this site as I can never get the expected response where I can find my name in the $a.parsedHTML.DocumentElement.InnerText. Instead, when I view this I simply get the full page back telling me that my session has already expired.
I started to try this with the IE Com Object as well but this also did not seem to work. Am I missing something or is it just the way this site has been made? I've been struggling with this (really just to learn) for a couple of days now.
Thanks for any help!
If you send what it sends, to the place it sends it, you get logged in:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 # This is required so that HTTPS requests won't fail with Invoke-WebRequest
$r = Invoke-WebRequest -Uri https://order.swisschalet.com -SessionVariable sc
$form = #{
delegate='login'
id='null'
mode='save'
target='#form-login'
email='email#example.com'
password='password'
}
$a = Invoke-WebRequest -Uri "https://order.swisschalet.com/order/auth/index" -WebSession $sc -Method POST -Body $form
and it says
<span class="welcome-back">Welcome, <span class="username">TestingSome StuffForStackOverflo</span>
in the $a.RawContent result. So I guess it's not incompatible.