I'm trying to push some data into ElasticSearch via PowerShell. I'm converting the data into JSON, then trying both Invoke-WebRequest and Invoke-RestMethod, but always get errors on malformed data or content-type not supported. I haven't created the index as I believe it will create it for me.
Anyone able to assist on what I'm missing/doing wrong?
Example code:
$data = #()
$CustomObject = [pscustomobject]#{
SqlInstance = "myserver1"
Database = "mydb"
Schema = "versioning"
Name = "DataVersionHistory"
IndexSpaceUsed = 0
DataSpaceUsed = 0
RowCount = 0
};
$data += $CustomObject;
$CustomObject = [pscustomobject]#{
SqlInstance = "myserver1"
Database = "mydb"
Schema = "versioning"
Name = "VersionHistory"
IndexSpaceUsed = 10
DataSpaceUsed = 25
RowCount = 3000
};
$data += $CustomObject;
$myJson = ConvertTo-Json -InputObject $data ;
Invoke-RestMethod -Uri http://localhost:9200/myindex/mytype/_bulk?pretty `
-Method POST -Body $myJson -ContentType "application/json"
Bulk request is not actual json. You should use following notation:
curl -XPOST 'localhost:9200/_bulk?pretty' -H 'Content-Type: application/json' -d'
{ "index" : { "_index" : "test", "_type" : "type1", "_id" : "1" } }
{ "field1" : "value1" }
{ "delete" : { "_index" : "test", "_type" : "type1", "_id" : "2" } }
{ "create" : { "_index" : "test", "_type" : "type1", "_id" : "3" } }
{ "field1" : "value3" }
{ "update" : {"_id" : "1", "_type" : "type1", "_index" : "test"} }
{ "doc" : {"field2" : "value2"} }
'
$data = #()
$CustomObject = [pscustomobject]#{
SqlInstance = "myserver1"
Database = "mydb"
Schema = "versioning"
Name = "DataVersionHistory"
IndexSpaceUsed = 0
DataSpaceUsed = 0
RowCount = 0
};
$data += $CustomObject;
$CustomObject = [pscustomobject]#{
SqlInstance = "myserver1"
Database = "mydb"
Schema = "versioning"
Name = "VersionHistory"
IndexSpaceUsed = 10
DataSpaceUsed = 25
RowCount = 3000
};
$data += $CustomObject
At this point you have a collection of objects contained in the array $data.
NOTE: for the bulk API the final line of the json data must end with a newline character \n. So I am using a here-string to append the newline char \n to each json element.
also notice that i removed pretty print. this is to play nice with the bulk api.
doc_as_upsert ensures that if the doc exists leave it alone, if not add as new.
$json_col = #()
$data |
ForEach-Object {
#convert object to json
$json_element = #{doc = $_; doc_as_upsert = $true}
| ConvertTo-Json -Depth 1 -Compress
#construt here string with literal \n
$json_col += #"
$json_element\n
"#
}
Invoke-RestMethod -Method Post -Uri "http://localhost:9200/myindex/mytype/_bulk?" -Body $json_col -ErrorAction Stop
Related
I converted two json files with the Get-LeafProperty from this post
Powershell Selecting NoteProperty Type Objects From Object
This maked it easy to merge 2 json file which include different general.apps[] at least it was easy to merge the psobject created by the Get-LeafProperty.
Now I want to go back from the merged psobjects to the origninal json format.
I have a psobject like this which I like to convert to json.
`
[path] : [value]
general.apps[0].name : admin
general.apps[0].storageAccount.sku.name : Standard_LRS
general.apps[0].storageAccount.sku.tier : Standard
general.apps[0].hostingPlan.sku.name : Y1
general.apps[0].hostingPlan.sku.tier : Dynamic
general.apps[0].appconfig.AzureWebJobsDisableHomepage : True
general.apps[0].appconfig.AzureWebJobsStorage__accountName : ${Prefix}${tier}admin
general.apps[0].appconfig.CosmosDbConnectionStringOrManagedIdentity : AccountEndpoint=https://${Prefix}${tier}cosmosdb.documents.azure.com:443
general.apps[0].appconfig.cpo-blackbox-authorization-token :
general.apps[0].appconfig.DatabaseCacheRefreshMinutes :
general.apps[0].appconfig.HttpCallMaxSeconds :
general.apps[0].appconfig.EvgCpoOcpiUrl : https://${Prefix}${tier}${staging}cpoocpi.azurewebsites.net/api/
general.apps[0].appconfig.EvgCtrlWpsUrl : https://${Prefix}${tier}${staging}ctrlwps.azurewebsites.net/api/
general.apps[0].appconfig.EvgPingUrl : https://${Prefix}${tier}${staging}ping.azurewebsites.net/api/
general.apps[0].appconfig.Logging___DebugAsInformation :
general.apps[0].appconfig.Logging___TraceAsInformation :
general.apps[0].appconfig.NegotiatePostfix : /webpubsub/v100/negotiate
general.apps[0].appconfig.OcpiAuthenticationFailureDelayBaseMilliseconds :
general.apps[0].appconfig.OcpiEvgCountryCode :
general.apps[0].appconfig.OcpiLocationSuppressEvents : True
general.apps[0].appconfig.OcpiEvgPartyId :
general.apps[0].appconfig.OcpiSessionTokenMaxAgeSeconds :
general.apps[0].appconfig.OCPIv211___GetPagingLimit :
general.apps[0].appconfig.OCPPv16_OCPIv211___Cdr___Disconnected___TimerCheckConnection :
general.apps[0].appconfig.OCPPv16_OCPIv211___Cdr___Pump___TimerCheckConnection :
general.apps[0].appconfig.OCPPv16_OCPIv211___Cdr___Pump___TimerResponse :
general.apps[0].appconfig.OCPPv16_OCPIv211___LocationEvse___Disconnected___TimerCheckConnection :
general.apps[0].appconfig.OCPPv16_OCPIv211___LocationEvse___Pump___TimerCheckConnection :
general.apps[0].appconfig.OCPPv16_OCPIv211___LocationEvse___Pump___TimerResponse :
general.apps[0].appconfig.OCPPv16_OCPIv211___SessionRecovery___TimerDelayRecoveryRepeatSec :
general.apps[0].appconfig.OCPPv16_OCPIv211___SessionRecovery___TimerDelayRecoveryShotSec :
general.apps[0].appconfig.OCPPv16_OCPIv211___Statemachine___Default___TimerExitSec :
general.apps[0].appconfig.OCPPv16_OCPIv211___Statemachine___Default___TimerRecoverySec :
general.apps[0].appconfig.OCPPv16_OCPIv211___Statemachine___StartSessionState___TimerExitSec :
general.apps[0].appconfig.OCPPv16_OCPIv211___Statemachine___StartSessionRecoveryState___TimerExitSec :
general.apps[0].appconfig.OCPPv16_OCPIv211___Statemachine___WaitPatchSessionState___TimerExitSec :
general.apps[0].appconfig.OCPPv16_OCPIv211___Statemachine___WaitPatchSessionState___TimerRecoverySec :
general.apps[0].appconfig.PingUrls :
general.apps[0].appconfig.SCALE_CONTROLLER_LOGGING_ENABLED :
general.apps[0].appconfig.ServiceBusConnectionString__fullyQualifiedNamespace :
general.apps[0].appconfig.ServiceBusQueueList : cpoocpi:ctrlwps
general.apps[0].appconfig.ServiceBusName :
general.apps[0].appconfig.StatemachineCheckAgeCronSchedule :
general.apps[0].appconfig.StatemachineCheckAgeMinAgeDays :
general.apps[0].appconfig.StatemachineEngineDatabase :
general.apps[0].appconfig.StatemachineEngineContainerData :
general.apps[0].appconfig.StatemachineEngineContainerOperations :
general.apps[0].appconfig.StatemachineEngineContainerOperationsLeases :
general.apps[0].appconfig.StatemachineEngineQueueTimers :
general.apps[0].appconfig.StatemachineEngineServiceBusQueueOperations :
general.apps[0].appconfig.TimerKeepAliveCronSchedule : 0 * * * * *
general.apps[0].appconfig.TimerOcpiSessionTokenCleanupCronSchedule :
general.apps[0].appconfig.TimerOcpiV211GetCdrsCronSchedule :
general.apps[0].appconfig.TimerOcpiV211GetLocationsCronSchedule :
general.apps[0].appconfig.TimerTriggerCronSchedule :
general.apps[0].appconfig.WebPubSubEndpoint :
general.apps[0].appconfig.WebPubSubIdentityObjectId :
general.apps[0].appconfig.WebPubSubConnectionString :
general.apps[0].appconfig.WebPubSubHub :
general.apps[0].appconfig.WebPubSubHubLogging :
general.apps[0].appconfig.WsHostname : ${Prefix}${tier}admin.azurewebsites.net
general.apps[1].name : blackboxtestapi
general.apps[1].storageAccount.sku.name : Standard_LRS
general.apps[1].storageAccount.sku.tier : Standard
general.apps[1].hostingPlan.sku.name : Y1
general.apps[1].hostingPlan.sku.tier : Dynamic
general.apps[1].appconfig.AzureWebJobsDisableHomepage : True
general.apps[1].appconfig.AzureWebJobsStorage__accountName : ${Prefix}${tier}blackboxtestapi
general.apps[1].appconfig.CosmosDbConnectionStringOrManagedIdentity :
general.apps[1].appconfig.cpo-blackbox-authorization-token :
general.apps[1].appconfig.DatabaseCacheRefreshMinutes :
general.apps[1].appconfig.HttpCallMaxSeconds :
general.apps[1].appconfig.EvgCpoOcpiUrl :
general.apps[1].appconfig.EvgCtrlWpsUrl :
general.apps[1].appconfig.EvgPingUrl :
general.apps[1].appconfig.Logging___DebugAsInformation :
general.apps[1].appconfig.Logging___TraceAsInformation :
general.apps[1].appconfig.NegotiatePostfix :
general.apps[1].appconfig.OcpiAuthenticationFailureDelayBaseMilliseconds :
general.apps[1].appconfig.OcpiEvgCountryCode :
general.apps[1].appconfig.OcpiEvgPartyId :
general.apps[1].appconfig.OcpiLocationSuppressEvents : True
general.apps[1].appconfig.OcpiSessionTokenMaxAgeSeconds :
general.apps[1].appconfig.OCPIv211___GetPagingLimit :
general.apps[1].appconfig.OCPPv16_OCPIv211___Cdr___Disconnected___TimerCheckConnection :
general.apps[1].appconfig.OCPPv16_OCPIv211___Cdr___Pump___TimerCheckConnection :
general.apps[1].appconfig.OCPPv16_OCPIv211___Cdr___Pump___TimerResponse :
general.apps[1].appconfig.OCPPv16_OCPIv211___LocationEvse___Disconnected___TimerCheckConnection :
general.apps[1].appconfig.OCPPv16_OCPIv211___LocationEvse___Pump___TimerCheckConnection :
general.apps[1].appconfig.OCPPv16_OCPIv211___LocationEvse___Pump___TimerResponse :
general.apps[1].appconfig.OCPPv16_OCPIv211___SessionRecovery___TimerDelayRecoveryRepeatSec :
general.apps[1].appconfig.OCPPv16_OCPIv211___SessionRecovery___TimerDelayRecoveryShotSec :
general.apps[1].appconfig.OCPPv16_OCPIv211___Statemachine___Default___TimerExitSec :
general.apps[1].appconfig.OCPPv16_OCPIv211___Statemachine___Default___TimerRecoverySec :
general.apps[1].appconfig.OCPPv16_OCPIv211___Statemachine___StartSessionState___TimerExitSec :
general.apps[1].appconfig.OCPPv16_OCPIv211___Statemachine___StartSessionRecoveryState___TimerExitSec :
general.apps[1].appconfig.OCPPv16_OCPIv211___Statemachine___WaitPatchSessionState___TimerExitSec :
general.apps[1].appconfig.OCPPv16_OCPIv211___Statemachine___WaitPatchSessionState___TimerRecoverySec :
general.apps[1].appconfig.PingUrls :
general.apps[1].appconfig.SCALE_CONTROLLER_LOGGING_ENABLED :
general.apps[1].appconfig.ServiceBusConnectionString__fullyQualifiedNamespace :
general.apps[1].appconfig.ServiceBusQueueList :
general.apps[1].appconfig.ServiceBusName :
general.apps[1].appconfig.StatemachineCheckAgeCronSchedule :
general.apps[1].appconfig.StatemachineCheckAgeMinAgeDays :
general.apps[1].appconfig.StatemachineEngineDatabase :
general.apps[1].appconfig.StatemachineEngineContainerData :
general.apps[1].appconfig.StatemachineEngineContainerOperations :
general.apps[1].appconfig.StatemachineEngineContainerOperationsLeases :
general.apps[1].appconfig.StatemachineEngineQueueTimers :
general.apps[1].appconfig.StatemachineEngineServiceBusQueueOperations :
general.apps[1].appconfig.TimerKeepAliveCronSchedule : 0 * * * * *
general.apps[1].appconfig.TimerOcpiSessionTokenCleanupCronSchedule :
general.apps[1].appconfig.TimerOcpiV211GetLocationsCronSchedule :
general.apps[1].appconfig.TimerOcpiV211GetCdrsCronSchedule :
general.apps[1].appconfig.TimerTriggerCronSchedule :
general.apps[1].appconfig.WebPubSubConnectionString :
general.apps[1].appconfig.WebPubSubEndpoint :
general.apps[1].appconfig.WebPubSubIdentityObjectId :
general.apps[1].appconfig.WebPubSubHub : blackboxtest
general.apps[1].appconfig.WebPubSubHubLogging : logging
`
I want to convert this object to json.
ConvertTo-Json gives me this =>
`
{
"general.apps[0].name": "admin",
"general.apps[0].storageAccount.sku.name": "Standard_LRS",
"general.apps[0].storageAccount.sku.tier": "Standard",
"general.apps[0].hostingPlan.sku.name": "Y1",
"general.apps[0].hostingPlan.sku.tier": "Dynamic",
<snip>
`
But I want to get something like this.
`
{
"general": {
"apps":[
{
"name": "admin",
"storageAccount":
{
"sku": {
"name": "Standard_LRS",
"tier": "Standard"
},
"queues": []
},
"hostingPlan":{
"sku": {
"name": "Y1",
"tier": "Dynamic"
}
},
"insight": {},
"appconfig": {
"AzureWebJobsDisableHomepage": true,
"AzureWebJobsStorage__accountName": "${Prefix}${tier}admin",
<snip>
`
I can run a loop over the Path variable and split it on '.' and try to create path again.
I wonder if there is no easier solution.
I solved it differently.
Instead of merging via the Get-Leafeproperty, I use as script that merges the json directly.
The next function merges complex json just fine.
function Merge-Json( $source, $extend ){
if( $source -is [PSCustomObject] -and $extend -is [PSCustomObject] ){
# Ordered hashtable for collecting properties
$merged = [ordered] #{}
# Copy $source properties or overwrite by $extend properties recursively
foreach( $Property in $source.PSObject.Properties ){
if( $null -eq $extend.$($Property.Name) ){
$merged[ $Property.Name ] = $Property.Value
}
else {
$merged[ $Property.Name ] = Merge-Json $Property.Value $extend.$($Property.Name)
}
}
# Add $extend properties
foreach( $Property in $extend.PSObject.Properties ){
if( $null -eq $source.$($Property.Name) ) {
$merged[ $Property.Name ] = $Property.Value
}
}
# Convert hashtable into PSCustomObject and output
[PSCustomObject] $merged
}
elseif( $source -is [Collections.IList] -and $extend -is [Collections.IList] ){
$maxCount = [Math]::Max( $source.Count, $extend.Count )
[array] $merged = for( $i = 0; $i -lt $maxCount; ++$i ){
if( $i -ge $source.Count ) {
# extend array is bigger than source array
$extend[ $i ]
}
elseif( $i -ge $extend.Count ) {
# source array is bigger than extend array
$source[ $i ]
}
else {
# Merge the elements recursively
Merge-Json $source[$i] $extend[$i]
}
}
# Output merged array, using comma operator to prevent enumeration
, $merged
}
else{
# Output extend object (scalar or different types)
$extend
}
}
I want to convert the data in the following script to JSON, can anyone let me know how to include [] in the JSON using powershell.
My script:
$URL = " http://localhost:4200/api/testinglabproject/test-run"
$projectShortName = "NES"
$testPlanName = "TestManager"
$deviceName = "testt"
$nodeManagerResourceName = "nm-4c2f1575-00fd-4363-b88a-2fb3cf587223"
$hostname = "DSTW8Y2.bla.is.abc.com"
$resourceName = "hs-515a8129-1aa0-4a14-847b-210022fe9cd7"
$hardwareSolutionType = "testt"
$emailId = "abc#gmail.com"
$data = #{
projectShortName=$projectShortName
testPlanName=$testPlanName
hardwareSolution=#{
hardwareSolutionItemList =
#{deviceName = $deviceName
nodeManagerResourceName =$nodeManagerResourceName
hostname = $hostname}
hardwareSolutionMetadataList = "[]"
resourceName = $resourceName
hardwareSolutionType = $hardwareSolutionType
}
emailId = $emailId
}
$jsondata = $data | ConvertTo-Json -Depth 3
Write-Host $jsondata
The resulting JSON should be like this:
{
"projectShortName": <projectShortName>,
"testPlanName": <planName>,
"hardwareSolution": {
"hardwareSolutionItemList": [{"deviceName": <deviceName>,
"nodeManagerResourceName": <NodeManagerResourceName>,
"hostname": <hostName>}],
"hardwareSolutionMetadataList": [],
"resourceName": <HardwareSolutionResourceName>,
"hardwareSolutionType": <hwstName>
},
"emailId": <emailID>
}
I stripped all those superfluous variables and replaced the string "[]" with an actual PowerShell array #() for the hardwareSolutionMetadataList key:
$data = #{
testPlanName = "TestManager"
projectShortName = "NES"
hardwareSolution = #{
hardwareSolutionItemList = #{
deviceName = "testt"
nodeManagerResourceName = "nm-4c2f1575-00fd-4363-b88a-2fb3cf587223"
hostname = "DSTW8Y2.bla.is.abc.com"
}
hardwareSolutionMetadataList = #()
resourceName = "hs-515a8129-1aa0-4a14-847b-210022fe9cd7"
hardwareSolutionType = "testt"
}
emailId = "abc#gmail.com"
}
$jsondata = $data | ConvertTo-Json -Depth 3
Write-Host $jsondata
PowerShell's idea of JSON formatting is a bit odd, but structurally it's OK.
{
"hardwareSolution": {
"hardwareSolutionItemList": {
"deviceName": "testt",
"hostname": "DSTW8Y2.bla.is.abc.com",
"nodeManagerResourceName": "nm-4c2f1575-00fd-4363-b88a-2fb3cf587223"
},
"resourceName": "hs-515a8129-1aa0-4a14-847b-210022fe9cd7",
"hardwareSolutionMetadataList": [
],
"hardwareSolutionType": "testt"
},
"testPlanName": "TestManager",
"emailId": "abc#gmail.com",
"projectShortName": "NES"
}
You can use the -Compress parameter to remove the whitespace for uploading the JSON somewhere.
{"hardwareSolution":{"hardwareSolutionItemList":{"deviceName":"testt","hostname":"DSTW8Y2.bla.is.abc.com","nodeManagerResourceName":"nm-4c2f1575-00fd-4363-b88a-2fb3cf587223"},"resourceName":"hs-515a8129-1aa0-4a14-847b-210022fe9cd7","hardwareSolutionMetadataList":[],"hardwareSolutionType":"testt"},"testPlanName":"TestManager","emailId":"abc#gmail.com","projectShortName":"NES"}
Am developing Laravel RESTful API for saving array of Json object into DB using php associative array and this is the error am getting.;
"message": "Illegal string offset 'product_id'",
"exception": "ErrorException",
...
This is the array of JSON object am trying to save in Mysql DB
"userId": "1",
"userName": "Dan",
"userEmail": "dan#gmail.com"
"product": [
{
"product_id": "31",
"product_name": "Orange",
"product_price": "USD 0.5"
}
]
}
This is the php function for save Json object into DB.
$userId = $request -> input('userId');
$userName = $request ->input('userName');
$userEmail = $request ->input('userEmail');
$data = array(
"userId"=>$userId,
"userName"=>$userName,
"userEmail"=>$userEmail
);
$user = User::create($data);
if($order){
//Storing the received JSON in $json.
$json = file_get_contents('php://input');
// Decode the received JSON and store into $obj
$obj = json_decode($json,true);
foreach($obj as $product){
$product_id = $product['product_id'];
$product_name = $product['product_name'];
$product_price = $product['product_price'];
$product = array(
"product_id" => $product_id,
"product_name" => $product_name,
"product_price" => $product_price
);
DB::table('products')->insert($product);
}
if($product){
// On query success it will print below message.
$MSG = 'Data Successfully Submitted.' ;
// Converting the message into JSON format.
$json = json_encode($MSG);
// Echo the message.
echo $json ;
}
else{
echo 'Try Again';
}
Guys where am I making mistake. Thank you in advance!
I am parsing JSON data which is in .json file. Here I have 2 formats of JSON data files.
I could parse first JSON file - file is shown below:
file1.json
{
"sequence" : [ {
"type" : "type_value",
"attribute" : {
"att1" : "att1_val",
"att2" : "att2_val",
"att3" : "att3_val",
"att_id" : "1"
}
} ],
"current" : 0,
"next" : 1
}
Here is my script:
#/usr/lib/perl
use strict;
use warnings;
use Data::Dumper;
use JSON;
my $filename = $ARGV[0]; #Pass json file as an argument
print "FILE:$filename\n";
my $json_text = do {
open(my $json_fh, "<:encoding(UTF-8)", $filename)
or die("Can't open \$filename\": $!\n");
local $/;
<$json_fh>
};
my $json = JSON->new;
my $data = $json->decode($json_text);
my $aref = $data->{sequence};
my %Hash;
for my $element (#$aref) {
my $a = $element->{attribute};
next if(!$a);
my $aNo = $a->{att_id};
$Hash{$aNo}{'att1'} = $a->{att1};
$Hash{$aNo}{'att2'} = $a->{att2};
$Hash{$aNo}{'att3'} = $a->{att3};
}
print Dumper \%Hash;
Everything is getting stored in %Hash and when I print Dumper of the %Hash I am getting following result.
$VAR1 = {
'1' => {
'att1' => 'att1_val',
'att2' => 'att2_val',
'att3' => 'att3_val'
}
};
But when I parse second set of JSON file, I am getting empty hash by using the above script.
Output:
$VAR1 = {};
Here is the JSON file -
file2.json
{
"sequence" : [ {
"type" : "loop",
"quantity" : 8,
"currentIteration" : 0,
"sequence" : [ {
"type" : "type_value",
"attribute" : {
"att1" : "att1_val",
"att2" : "att2_val",
"att3" : "att3_val",
"att_id" : "1"
}
} ]
} ]
}
We can see two sequence in above JSON data file, which is causing the problem.
Can somebody tell me what I am missing in the script inorder to parse file2.json.
One possibility might be to check the type field to differentiate between the two file formats:
# [...]
for my $element (#$aref) {
if ( $element->{type} eq "loop" ) {
my $aref2 = $element->{sequence};
for my $element2 ( #$aref2 ) {
get_attrs( $element2, \%Hash );
}
}
else {
get_attrs( $element, \%Hash );
}
}
sub get_attrs {
my ( $element, $hash ) = #_;
my $a = $element->{attribute};
return if(!$a);
my $aNo = $a->{att_id};
$hash->{$aNo}{'att1'} = $a->{att1};
$hash->{$aNo}{'att2'} = $a->{att2};
$hash->{$aNo}{'att3'} = $a->{att3};
}
Please see the following code if it fits your requirements
#!/usr/bin/env perl
#
# vim: ai:sw=4:ts=4
#
use strict;
use warnings;
use feature 'say';
use Data::Dumper;
use JSON;
my $debug = 0; # debug flag
my $filename = shift; # Pass json file as an argument
say "FILE: $filename";
open(my $json_fh, "<:encoding(UTF-8)", $filename)
or die("Can't open \$filename\": $!\n");
my $json_data = do { local $/; <$json_fh> };
close $json_fh;
my $json = JSON->new;
my $data = $json->decode($json_data);
say Dumper($data) if $debug;
my $data_ref;
my %Hash;
$data_ref = $data->{sequence}[0]{attribute}
if $filename eq 'file1.json';
$data_ref = $data->{sequence}[0]{sequence}[0]{attribute}
if $filename eq 'file2.json';
say Dumper($data_ref) if $debug;
my #fields = qw/att1 att2 att3/;
my $aNo = $data_ref->{att_id};
my %data_hash;
#data_hash{#fields} = $data_ref->{#fields};
$Hash{$aNo} = \%data_hash;
say Dumper(\%Hash);
I am hitting this url
https://webadmin.td90.centile-dev.com/restletrouter/v1/service/Login
Then i am getting the session and passing into the url below
https://myistra.td90.centile-dev.com/restleroute/v1/3rdParty/AdmtiveDomain.
Problem
Output
Invoke-WebRequest : Unauthorized
The request requires user authentication
You can get technical details here.
Please continue your visit at our home page.
At C:\Users\administrator\Documents\CDR.ps1:20 char:213
+ ... 'Session' | Invoke-WebRequest -Uri ("https://myistra.td90.centile-
dev ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation:
(System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
thirdParty_SESSIONID=969514241160310577; _ac958=http://10.20.100.190:8078
Here is my code
$user = "SuperGabriel"
$pass = "SuperGabriel#2019"
$pair = "$($user):$($pass)"
$encodedCreds =
$basicAuthValue = "Basic $encodedCreds"
$PartOneHeaders = #{
"Authorization" = $basicAuthValue
"X-Application" = "3rdParty"
}
#test
$Headers =#{
"X-Application" = "3rdParty"
"Cookie"= "thirdParty_SESSIONID=7353595784495763113;"
}
$PartOneWebRequest = Invoke-WebRequest -Uri https://webadmin.td90.centile-
dev.com/restletrouter/v1/service/Login -Headers $PartOneHeaders -
ContentType "application/json" -Method POST -SessionVariable 'Session' |
Invoke-WebRequest -Uri ("https://myistra.td90.centile-
dev.com/restleroute/v1/3rdParty/AdmtiveDomain" ) -Headers $Headers -
Method Get
I have echoed everything out to make sure i am getting the right information and passing it into the right places.
I have tested the call in postman and it works.
Expected results
[
{
"restUri": "v1/3rdParty/AdmtiveDomain/0.",
"alias": "TopLevelAdmtiveDomain",
"rootModel": "AdmtiveDomain",
"domainName": "Top-Level",
"admtiveDomainID": "0."
},
{
"restUri": "v1/3rdParty/AdmtiveDomain/0.106.",
"alias": "AdmtiveDomainSpecific",
"rootModel": "AdmtiveDomain",
"domainName": "acd-00",
"domainType": "Enterprise",
"admtiveDomainID": "0.106."
}
]
[System.Uri]$Uri = "https://webadmin.td90.centile-dev.com/restletrouter/v1/service/Login" # Add the Uri
[System.Uri]$Uri_Get = "https://webadmin.td90.centile-dev.com/restletrouter/v1/3rdParty/AdmtiveDomain"
$ContentType = "application/json" # Add the content type
$Method = 'POST' # Add the method type
$user = "SuperGabriel"
$pass = "SuperGabriel#2019"
$pair = "$($user):$($pass)"
$encodedCreds = [System.Convert]::ToBase64String([System.Text.Encoding]::ASCII.GetBytes($pair))
$basicAuthValue = "Basic $encodedCreds"
$Headers = #{
# Add name and value of headers
"Authorization" = $basicAuthValue
"Cookie" = "thirdParty_SESSIONID=6335513255659796064"
"X-Application" = "3rdParty"
}
$Headers_Get = #{
# Add name and value of headers
"Cookie" = "thirdParty_SESSIONID=4436753218874838616; thirdParty_SESSIONID=6335513255659796064;"
"X-Application" = "3rdParty"
"Host" = "webadmin.td90.centile-dev.com"
"Content-Type"= "$ContentType"
}
$Headers_Get2 = #{
# Add name and value of headers
"Cookie" = "thirdParty_SESSIONID=1312545750448673312"
"X-Application" = "3rdParty"
"Host" = "webadmin.td90.centile-dev.com"
"Content-Type"= "$ContentType"
}
# Splat the parameters
$props = #{
Uri = $Uri
Headers = $Headers
ContentType = $ContentType
Method = $Method
}
$props_Get = #{
Uri = $Uri_Get
Headers = $Headers_Get
ContentType = $ContentType
Method = "GET"
}
try
{
$Result= Invoke-RestMethod #props -SessionVariable sess -OutFile C:\output.json
echo $Result
$Result1= Invoke-RestMethod #props_Get -OutFile C:\"$DateStr".json -WebSession $sess
echo $Result1
}
catch [System.Net.WebException]
{
$res = $_.Exception.Response
echo $res
}
Will work as per your request.
Cheers..