I want to be able to load SharePoint Online pages with Invoke-Webrequest from Powershell.
Can someone please show me how to successfully navigate past the login screen?
Here is how I get list items from SPO. You need to have "Microsoft.SharePoint.Client.SharePointOnlineCredentials" dll.
Then use the below function that I have modified for SPO.
Advantage: This will even work with older PowerShell versions. If you want to target only higher level of PowerShell then also this code will work. Optionally you can use Invoke-Webrequest instead of System.Net.HttpWebRequest and System.Net.HttpWebResponse.
function Get-ListItems {
[CmdletBinding()]
PARAM (
[Parameter(Mandatory=$true)]
[String] $URL
)
#$URL = Fix-Url $URL
$xml = Request-Rest -URL $URL
return $xml
}
function Request-Rest{
[CmdletBinding()]
PARAM (
[Parameter(Mandatory=$true)]
[String] $URL,
[Parameter(Mandatory=$false)]
[Microsoft.SharePoint.Client.SharePointOnlineCredentials] $credentials,
[Parameter(Mandatory=$false)]
[String] $UserAgent = "PowerShell API Client",
[Parameter(Mandatory=$false)]
[Switch] $JSON,
[Parameter(Mandatory=$false)]
[Switch] $Raw
)
#Create a URI instance since the HttpWebRequest.Create Method will escape the URL by default.
$URI = New-Object System.Uri($URL,$true)
#Create a request object using the URI
$request = [System.Net.HttpWebRequest]::Create($URI)
#Build up a nice User Agent
$request.UserAgent = $(
"{0} (PowerShell {1}; .NET CLR {2}; {3})" -f $UserAgent, $(if($Host.Version){$Host.Version}else{"1.0"}),
[Environment]::Version,
[Environment]::OSVersion.ToString().Replace("Microsoft Windows ", "Win")
)
if ($credentials -eq $null)
{
$request.UseDefaultCredentials = $true
}
else
{
$request.Credentials = $credentials
}
if ($PSBoundParameters.ContainsKey('JSON'))
{
$request.Accept = "application/json"
}
$request.Headers.Add("X-FORMS_BASED_AUTH_ACCEPTED", "f")
#$request.Accept = "application/json;odata=verbose"
try
{
[System.Net.HttpWebResponse] $response = [System.Net.HttpWebResponse] $request.GetResponse()
}
catch
{
Throw "Exception occurred in $($MyInvocation.MyCommand): `n$($_.Exception.Message)"
}
$reader = [IO.StreamReader] $response.GetResponseStream()
if (($PSBoundParameters.ContainsKey('JSON')) -or ($PSBoundParameters.ContainsKey('Raw')))
{
$output = $reader.ReadToEnd()
}
else
{
[xml]$output = $reader.ReadToEnd()
}
$reader.Close()
Write-Output $output
$response.Close()
}
Though I do not know the direct way to pass the credentials along with Invoke-WebRequest itself, one workaround I found is, capture the cookie values by manual authenticating the SharePoint page and use those for subsequent requests. You can use fiddler or some other similar tool to grab the cookies. The two cookie names were 'FedAuth' and 'rtFa'
$session = New-Object Microsoft.PowerShell.Commands.WebRequestSession
$cookieCollection = New-Object System.Net.CookieCollection
$cookie1 = New-Object System.Net.Cookie
$cookie1.Domain = "<your domain>.sharepoint.com"
$cookie1.Name = "FedAuth"
$cookie1.Value = "<cookie value here>"
$cookieCollection.Add($cookie1)
$cookie2 = New-Object System.Net.Cookie
$cookie2.Domain = "<your domain>.sharepoint.com"
$cookie2.Name = "rtFa"
$cookie2.Value = "<cookie value here>"
$cookieCollection.Add($cookie2)
$session.Cookies.Add($cookieCollection)
$uri = "https:<your site collection here>/_layouts/15/SharePointDesignerSettings.aspx"
$response = Invoke-WebRequest -Uri $uri -WebSession $session -Method Default
$form = $response.Forms[0]
You can use $form to examine the Html elements. If you want to submit the changes made to form use the below line
$response = Invoke-WebRequest -Uri $uri -WebSession $session -Method POST -Body $form
Note: There is an issue with Invoke-WebRequest with respect to field submission.. basically it uses 'id' of input element instead of 'name' in form fields collection.. the below url has the code to convert field Id to Name
https://d-fens.ch/2013/05/11/invoke-webrequest-uses-id-attribute-of-input-element-as-field-name-in-form-fields-collection/
If you are looking for the final content of a page, Invoke-WebRequest will not do what you need. Much of the content of a SharePoint page is loaded asynchronously using JavaScript. Invoke-WebRequest will only return the initial HTML content from the page.
What kind of content are you looking for from the page? Most everything about SharePoint can be accessed using RESTful queries (Invoke-RESTMethod and the SharePoint REST API) or from the PowerShell SharePoint PNP and SharePoint Online cmdlet libraries.
Related
I am writing a PowerShell script which reads through emails in an o365 email box.
It has to connect to the inbox, read through emails and make a decision based on the subject line, and then open those emails with a specific subject line and download any attachments the email might contain to a folder.
It [then] has to move the processed mail message to a mailbox sub-folder.
I have done this in the past using Exchange web services, and basic authentication to connect, but basic authentication is no longer available, and so I am having to re-do the script using modern authentication techniques.
I have been given an application id and secret from my Azure AD admin's with permissions for the relevant mailbox.
I've been googling away, and have managed to get some way using Microsoft Graph - using this section of Powershell:
$ClientID = "my-client-id"
$DirectoryID = "my-directory-id"
$ClientSecret = "my-client-secret"
$Credential = ConvertTo-GraphCredential -ClientID $ClientID -ClientSecret $ClientSecret -DirectoryID $DirectoryID
$mailbox = Get-EXOMailbox -UserPrincipalName myemailaccount#mycompany.com
This successfully gets me a mailbox object, but from here I am at a loss as to how to go about retrieving emails from it for processing.
The Microsoft doco and Google isn't helping me much at present on how extract emails from the mailbox having obtained the object.
Any thoughts/suggestions or pointers to relevant tutorials?
I managed to figure out how to access emails just usiing application id and secret without
using any non-standard libraries. You'll need to install the Graph and powershell utilities,
but they're free from Microsoft, so I call them standard. Then import them into my powershell
script thus:
Import-Module Microsoft.Graph.Mail
Import-Module Microsoft.PowerShell.Utility
After that, use these methods to access your o365 email system using the microsoft graph
REST API.
# This AuthenticateWithSecret is a slightly modified version of the method
# described by https://adamtheautomator.com/powershell-graph-api/
function Get-AccessToken
{
param(
[string] $AppId,
[string] $TenantName,
[string] $AppSecret)
$Scope = "https://graph.microsoft.com/.default"
$Url = "https://login.microsoftonline.com/$TenantName/oauth2/v2.0/token"
# Add System.Web for urlencode
Add-Type -AssemblyName System.Web
# Create body
$Body = #{
client_id = $AppId
client_secret = $AppSecret
scope = $Scope
grant_type = 'client_credentials'
}
# Splat the parameters for Invoke-Restmethod for cleaner code
$PostSplat = #{
ContentType = 'application/x-www-form-urlencoded'
Method = 'POST'
# Create string by joining bodylist with '&'
Body = $Body
Uri = $Url
}
# Request the token!
$Request = Invoke-RestMethod #PostSplat
return $Request
}
# This method builds a header object that can be passed
# in with each request to the Graph REST API, for authentication
# purposes
function Get-Header
{
param($theRequest)
$tokenType = $theRequest.token_type
$accessToken = $theRequest.access_token
# Create header
$theHeader = #{
Authorization = "$($tokenType) $($accessToken)"
}
return $theHeader
}
# This method gets an object containing the email folders from
# a mailbox specified by its UserPrincipalName - which is typically
# the email address of the user concerned. By default it will return
# the first 200 folders it finds, but you can specify however many
# that you wish to return using the $numberOfFoldersToGet parameter.
function Get-Folders
{
param(
$Credential,
[string] $UserPrincipalName,
[int]$numberOfFoldersToGet=200)
$Header = Get-Header -theRequest $Credential
$restUrl = "https://graph.microsoft.com/v1.0/users/$UserPrincipalName/mailFolders/?`$top=$numberOfFoldersToGet"
$folderResult = Invoke-RestMethod -Uri $restUrl -Headers $Header -Method Get -ContentType "application/json"
return $folderResult
}
# This is a little helper function to get the specific folder object
# from an array of folder objects. You specify the folder that you
# want in the array based o its displayName using the $folderNameToFind
# parameter.
function Get-FolderFromListOfFolders
{
param($listOfFolders,
$folderNameToFind)
$specificFolder = ""
# Yeah, yeah, I know - we're doing this the brute-force way - just
# looping through all the folders until we find the one we want.
# Unless you have an insane number of folders, this shouldn't take
# *that* long, but this loop could be re-written to use a nicer search
# if it's really that big a problem.
foreach($fdr in $allFolders)
{
$thisFolderName = $fdr.displayName
if($thisFolderName -eq $folderNameToFind)
{
$specificFolder = $fdr
break
}
}
return $specificFolder
}
# This function allows you to retrieve an object describing a specific
# mail folder in an o365 Outlook, which you can specify by name. It allows
# you to access any folder by name - not just the common ones.
function Get-SpecificFolder
{
param(
$Credential,
[string] $UserPrincipalName,
[string] $folderName)
$allTheFolders = Get-Folders -Credential $Credential -UserPrincipalName $UserPrincipalName
$allFolders = $allTheFolders.value
$specificFolder = Get-FolderFromListOfFolders -listOfFolders $allFolders -folderNameToFind $folderName
$folderId = $specificFolder.id
$Header = Get-Header -theRequest $Credential
$theRestQuery = "https://graph.microsoft.com/v1.0/users/$UserPrincipalName/mailFolders/$folderId"
$folderResult = Invoke-RestMethod -Uri $theRestQuery -Headers $Header -Method Get -ContentType "application/json"
return $folderResult
}
# This function returns an object containing all the emails in a given
# Mail folder in Outlook in o365
function GetEmails
{
param(
$Credential,
[string] $UserPrincipalName,
[string] $folderId)
$Header = Get-Header -theRequest $Credential
$restUrl = "https://graph.microsoft.com/v1.0/users/$UserPrincipalName/mailFolders/$folderId/messages"
$emailResult = Invoke-RestMethod -Uri $restUrl -Headers $Header -Method Get -ContentType "application/json"
return $emailResult
}
You can use these methods in this way. First, you need to specify these variables
$ClientID = "My-azure-ad-client-id"
$DirectoryID = "My-directory-id"
$ClientSecret = "My-client-secret"
$MailboxName = "the-email-address-of-the-o365-mailbox-i-want-to-access"
$MailboxFolderName = "the-folder-name-of-the-mailfolder-containing-emails"
Then, you can get a credential object thus:
$Credential = Get-AccessToken -AppId $ClientID -TenantName $DirectoryID -AppSecret $ClientSecret
Then get your email folder object thus
$myfolder = Get-SpecificFolder -Credential $Credential -UserPrincipalName $MailboxName -folderName $MailboxFolderName
Then, get the id of your folder - this allows you to access any folder - even non-standard ones by name.
$folderId = $myfolder.id
Now, get the email objects from the folder
$emails = GetEmails -Credential $Credential -UserPrincipalName $MailboxName -folderId $folderId
Then get the actual array of emails
$theEmails = $emails.value
Now loop through your array of emails and do stuff with it.
foreach($email in $theEmails)
{
Write-Output $email.subject
}
I've been having a hell of a time trying to access the Microsoft Graph using PowerShell.
First I tried using the authorization flow and Invoke-WebRequest and Invoke-RestMethod neither of which I could get to work.
Then I found this blog that showed how to do it using PowerShell and a couple of the Azure modules. Below is the code I'm using (ripped right from that blog) but every time I get to the Invoke-RestMethod (in the do-while loop) instead of getting the result of the query I get a 403 Forbidden error:
Invoke-RestMethod : The remote server returned an error: (403) Forbidden.
Function GetAuthToken {
Param (
[Parameter()]
$TenantName
)
Import-Module Azure
$clientId = "1950a258-227b-4e31-a9cf-717495945fc2"
$resourceAppIdURI = "https://graph.microsoft.com"
$authority = "https://login.microsoftonline.com/$TenantName"
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
$Credential = Get-Credential
$AADCredentialUser = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserCredential" -ArgumentList $credential.UserName, $credential.Password
$authResult = $authContext.AcquireToken($resourceAppIdURI, $clientId, $AADCredentialUser)
Write-Output $authResult
}
Function GetAllObjectOfType {
param
(
[Parameter(Mandatory = $true)]
$Tenant,
[Parameter(Mandatory = $true)]
$Type,
[Parameter(Mandatory = $false)]
$BatchSize = 100,
[Parameter(Mandatory = $false)]
$Version = 'Beta'
)
#------Get the authorization token------#
$token = GetAuthToken -TenantName $tenant
#------Building Rest Api header with authorization token------#
$authHeader = #{
'Content-Type' = 'application/json'
'Authorization' = $token.CreateAuthorizationHeader()
}
#------Initial URI Construction------#
#$uritest = "https://graph.microsoft.com/v1.0/users/user#contoso.com/mailFolders/Inbox/childFolders"
$uritest = "https://graph.microsoft.com/v1.0/me/mailFolders/Inbox"
#Join-Path -Path ''
$ObjCapture = #()
do {
$users = Invoke-RestMethod -Uri $uritest -Headers $authHeader -Method Get
$FoundUsers = ($Users.value).count
write-host "URI" $uri " | Found:" $FoundUsers
#------Batched URI Construction------#
$uri = $users.'#odata.nextlink'
$ObjCapture = $ObjCapture + $users.value
}until ($uri -eq $null)
$ObjCapture
}
I can run this same query (/v1.0/me/mailFolders/Inbox) from the Graph Explorer and it runs perfectly fine with no errors.
The GetAuthToken seems to be working as I do get a token back with an expiry, refresh token, etc and the $token.CreateAuthorizationHeader() also returns the correct Authorization = Bearer token
I've never done anything with the Microsoft Graph before so I'm sure there is something I'm doing wrong but I cannot for the life of me figure out what.
You cannot reuse the clientid from that blog post. You need to obtain your own clientid by registering your application. See Register your app with the Azure AD v2.0 endpoint for details on how to register your app.
This seems like it was answered in a follow-up blog post from the same source.
When an App is created, by default it has rights to access only the data of
the user that had signed in with the account though the “Sign in and read user
profile” delegated permissions. If you try to execute a script that uses this
AppID/ClientID to query Azure AD to get a list of all users in the directory,
you would receive an error stating (403) Forbidden because it didn’t have
adequate permissions to do that activity.
Putting this here in case any other wandering devs come across the post like I did. Here's the powershell function I'm using to get the access token from our tenant. ClientId and Secret are created in the Azure App Registrations, like others have mentioned.
$clientId = $args[0]
$secret = $args[1]
$redeemURI = "https://login.microsoftonline.com/{tenantGuid}/oauth2/v2.0/token"
$body = "client_id=$clientId&scope=https%3A%2F%2Fgraph.microsoft.com%2F.default&client_secret=$secret&grant_type=client_credentials"
$response = Invoke-RestMethod -Method Post -Uri $redeemURI -Body $body -ContentType "application/x-www-form-urlencoded"
return $response.access_token
Usage:
$token = ./GetAccessToken.ps1 "{clientId}" "{secret}"
I think it needs AD Azure Premium 2 licences
enter link description here
I am trying to create build configurations via the restapi and powershell and keep getting the following error:
Exception calling "GetResponse" with "0" argument(s): "The remote server returned an error: (405) Method Not Allowed."
It seems that I can use GET fine, the issue appears to be with the PUT command
Code Snippet
$url = http://%teamcityServer%:8111/app/rest/buildTypes/id:%projectname%"
$req = [System.Net.WebRequest]::Create($url)
$req.ContentType = "text/plain"
$req.UseDefaultCredentials = $true
$req.Credentials = Get-Credential("username")
$req.Method ="PUT"
$req.ContentLength = 0
$req.Accept = "*/*"
$resp = $req.GetResponse()
$results = [xml]$resp.ReadToEnd()
Output from the Team City log
2015-09-10 09:14:30,582] WARN [io-8111-exec-70] - est.jersey.ExceptionMapperUtil - Error has occurred during request processing (405). Error: javax.ws.rs.WebApplicationException. Not supported request. Please check URL, HTTP method and transfered data are correct. metadata: [Allow:[HEAD,DELETE,GET,OPTIONS],] Request: PUT '/app/rest/buildTypes/id:%project%'
Team City Version is 9.1.1 so I believe this is possible.
I'm fairly new to the restapi so any input is appreciated.
Its possible but you need to post xml data to create builds/projects. For example if you need to create a project you can POST XML something like
<newProjectDescription name='New Project Name' id='newProjectId' copyAllAssociatedSettings='true'><parentProject locator='id:project1'/><sourceProject locator='id:project2'/></newProjectDescription>
to http://teamcity:8111/httpAuth/app/rest/projects.
Check more info on Teamcity REST documentation.
You didn't mention your powershell version, but if you are using 3.0 or later you can call Invoke-WebRequest cmdlet and your code should look something like:
Invoke-WebRequest -Uri $uri -Credential $cred -Method Post -Body $body -ContentType "Application/xml"
For PowerShell 2.0 You can write your own Web-Request method like:
function Web-Request{
param(
[Parameter(Mandatory=$true)]
[string]
$Uri,
[Parameter(Mandatory=$false)]
[string]
$Username = $null,
[Parameter(Mandatory=$false)]
[string]
$Password = $null,
[Parameter(Mandatory=$true)]
[string]
$ContentType,
[Parameter(Mandatory=$true)]
[string]
$Method,
[Parameter(Mandatory=$false)]
[string]
$PostString
)
$webRequest = [System.Net.WebRequest]::Create($Uri)
$webRequest.ContentType = $ContentType
$webRequest.Method = $Method
$webRequest.Accept = "*/*"
if ($Username)
{
$webRequest.Credentials = new-object system.net.networkcredential($Username, $Password)
}
try
{
switch -regex ($Method)
{
"PUT|POST" # PUT and POST behaves similar ways except that POST is only used for creation while PUT for creation/modification
{
if ($PostString -ne "")
{
$PostStringBytes = [System.Text.Encoding]::UTF8.GetBytes($PostString)
$webrequest.ContentLength = $PostStringBytes.Length
$requestStream = $webRequest.GetRequestStream()
$requestStream.Write($PostStringBytes, 0,$PostStringBytes.length)
}
else
{
$requestStream = $webRequest.GetRequestStream()
}
}
"DELETE"
{
$requestStream = $webRequest.GetRequestStream()
}
default
{
# GET requests usually don't have bodies, default will behave like a GET
}
}
if ($requestStream -ne $null)
{
$requestStream.Close()
}
[System.Net.WebResponse] $resp = $webRequest.GetResponse();
$rs = $resp.GetResponseStream();
[System.IO.StreamReader] $sr = New-Object System.IO.StreamReader -argumentList $rs;
[string] $results = $sr.ReadToEnd();
}
catch
{
$results = "Error : $_.Exception.Message"
}
finally
{
if ($sr -ne $null) { $sr.Close(); }
if ($resp -ne $null) { $resp.Close(); }
$resp = $null;
$webRequest = $null;
$sr = $null;
$requestStream = $null;
}
return $results
}
An adaptation of Vadim's answers to Upload file to SharePoint 2010 using PowerShell and the OData API and SharePoint 2010 REST API JQUery Insert, Update, Delete.
Attempting to upload a new version of an attachment:
Function Update-Attachments() {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$True,Position=1)]
[string]$WebUrl,
[Parameter(Mandatory=$True,Position=2)]
[string]$ListName,
[Parameter(Mandatory=$True,Position=3)]
[int]$ItemId,
# pipeline support
[Parameter(Mandatory=$True,Position=4,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
# associate FileInfo object's FullName property to be bound to parameter
[Alias('FullName')]
[string[]]$Paths
)
BEGIN {}
PROCESS {
#
$endpointUri = New-Object System.Uri("$WebUrl/_vti_bin/listdata.svc/$ListName($ItemId)/Attachments")
Foreach ($Path In $Paths) {
Write-Verbose "Path: $Path"
$fileName = (Split-Path $Path -Leaf)
$fileContent = ([IO.File]::ReadAllBytes($Path))
$headers = #{
"X-HTTP-Method" = "MERGE";
"If-Match" = "*"
}
try {
# reset each pass to ensure that prior response isn't reused
$response=$null
$response = Invoke-WebRequest -Uri $endpointUri -Method POST -UseDefaultCredentials -Body $fileContent -Headers $headers -ContentType "*/*"
}
# Invoke-WebRequest throws System.Net.WebException
catch [System.Net.WebException] {
throw $_
}
finally {
# returns Microsoft.PowerShell.Commands.HtmlWebResponseObject
$response
}
} # Foreach
} # PROCESS
END {}
}
Using the command throws (405) Method Not Allowed:
Update-Attachments -WebUrl "http://contoso.intranet.com/" -ListName "Tasks" -ItemId 1 -Paths "C:\Users\user\Documents\SharePointUserGuide.docx"
I've tried variations on the endpoint:
$endpointUri = New-Object System.Uri("$WebUrl/_vti_bin/listdata.svc/$ListName/Attachments/$ItemId/$fileName")
$endpointUri = New-Object System.Uri("$WebUrl/_vti_bin/listdata.svc/Attachments(EntitySet='$ListName',ItemId=$ItemId,Name='$fileName')")
and switching between PUT and MERGE.
What am I missing?
Can you check whether this SharePoint 2013 reference works with the 2010 API?
url: http://site url/_api/web/lists/getbytitle('list title')/items(item id)/AttachmentFiles('file name')/$value
method: POST
body: "Contents of file."
headers:
Authorization: "Bearer " + accessToken
"X-HTTP-Method":"PUT"
X-RequestDigest: form digest value
content-length:length of post body
https://msdn.microsoft.com/en-us/library/office/dn292553.aspx?f=255&MSPPError=-2147217396
What I am currently doing:
Invoke-WebRequest -Uri https://coolWebsite.com/ext/ext -ContentType application/json -Method POST -Body $someJSONFile
I am looking for a way to POST this same .json file in Powershell without using Invoke-WebRequest, if it is possible. This new method would preferably allow me to get the server output content and parse through it in powershell.
Maybe by calling an outside cURL method? I really am not sure and all my internet research has proved fruitless.
How can I achieve this above result without Invoke-WebRequest?
You can try this :
# RestRequest.ps1
Add-Type -AssemblyName System.ServiceModel.Web, System.Runtime.Serialization, System.Web.Extensions
$utf8 = [System.Text.Encoding]::UTF8
function Request-Rest
{
[CmdletBinding()]
PARAM (
[Parameter(Mandatory=$true)]
[String] $URL,
[Parameter(Mandatory=$false)]
[System.Net.NetworkCredential] $credentials,
[Parameter(Mandatory=$true)]
[String] $JSON)
# Remove NewLine from json
$JSON = $JSON -replace "$([Environment]::NewLine) *",""
# Create a URL instance since the HttpWebRequest.Create Method will escape the URL by default.
# $URL = Fix-Url $Url
$URI = New-Object System.Uri($URL,$true)
try
{
# Create a request object using the URI
$request = [System.Net.HttpWebRequest]::Create($URI)
# Build up a nice User Agent
$UserAgent = "My user Agent"
$request.UserAgent = $("{0} (PowerShell {1}; .NET CLR {2}; {3})" -f $UserAgent, $(if($Host.Version){$Host.Version}else{"1.0"}),
[Environment]::Version,
[Environment]::OSVersion.ToString().Replace("Microsoft Windows ", "Win"))
$request.Credentials = $credentials
$request.KeepAlive = $true
$request.Pipelined = $true
$request.AllowAutoRedirect = $false
$request.Method = "POST"
$request.ContentType = "application/json"
$request.Accept = "application/json"
$utf8Bytes = [System.Text.Encoding]::UTF8.GetBytes($JSON)
$request.ContentLength = $utf8Bytes.Length
$postStream = $request.GetRequestStream()
$postStream.Write($utf8Bytes, 0, $utf8Bytes.Length)
#Write-String -stream $postStream -string $JSON
$postStream.Dispose()
try
{
#[System.Net.HttpWebResponse] $response = [System.Net.HttpWebResponse] $request.GetResponse()
$response = $request.GetResponse()
}
catch
{
$response = $Error[0].Exception.InnerException.Response;
Throw "Exception occurred in $($MyInvocation.MyCommand): `n$($_.Exception.Message)"
}
$reader = [IO.StreamReader] $response.GetResponseStream()
$output = $reader.ReadToEnd()
$reader.Close()
$response.Close()
Write-Output $output
}
catch
{
$output = #"
{
"error":1,
"error_desc":"Error : Problème d'accès au serveur $($_.Exception.Message)"
}
"#
Write-Output $output
}
}
Edited 19-10-2015
Here is an example usage :
#$urlBase = "http://192.168.1.1:8080/"
#######################################################################
# Login #
#######################################################################
$wsLogin = "production/login"
Function login
{
[CmdletBinding()]
PARAM
(
[ValidateNotNullOrEmpty()]
[String] $login,
[String] $passwd
)
Write-Verbose $wsLogin
#$jsonIn = [PSCustomObject]#{"login"=$login;"passwd"=$passwd} | ConvertTo-Json
$jsonIn = #"
{
"login":"$login",
"passwd":"$passwd"
}
"#
Write-Verbose $jsonIn
$jsonOut = Request-Rest -URL "$urlBase$wsLogin" -JSON $jsonIn -credentials $null
Write-Verbose $jsonOut
#return $jsonOut | ConvertFrom-Json
return $jsonOut
}
It is easy to convert that code to cURL
curl -v --insecure -X POST -H "Content-Type: application/json" --data-binary someJSONFile.js https://coolWebsite.com/ext/ext/