Jump to content

Help with invoke-restmethod and '\' char


Johhny

Recommended Posts

Hi,

 

I have a powershell script that we use for creating new accounts in AD and adding the password to PasswordState. It works OK, but I get an error if someone includes a \ in the title.

 

Example code

 

$jsonData = '
{
  "PasswordListID":"278",
  "Title":"'+ $($Title) +'",
  "UserName":"'+$($username)+'",
  "Description":"'+$($purpose)+'",
  "HeartbeatEnabled":true,
  "ValidationScriptID":"7",
  "generatepassword":true,
  "AccountTypeID":"65",
  "ADDomainNetBIOS":"test",
  "HeartbeatSchedule":"'+$($date)+'"
 }'
 
$PasswordstateUrl = 'https://passwordstate.xxx.com/winapi/passwords'
$result = Invoke-Restmethod -Method Post -Uri $PasswordstateUrl -ContentType "application/json" -Body $jsonData -UseDefaultCredentials
 
 
 
With this data I get the error below
{
  "PasswordListID":"278",
  "Title":"test\srvtest",
  "UserName":"srvtest12",
  "Description":"Test script",
  "HeartbeatEnabled":true,
  "ValidationScriptID":"7",
  "generatepassword":true,
  "AccountTypeID":"65",
  "ADDomainNetBIOS":"test",
  "HeartbeatSchedule":"17:04"
}
 
Invoke-Restmethod : [{"errors":[{"message":"Invalid API Call"},{"phrase":"Error = Object reference not set to an instance of an object.}]}]
 
If I remove the \ from the Title then it works
 
{
  "PasswordListID":"278",
  "Title":"test srvtest",
  "UserName":"srvtest12",
  "Description":"Test script",
  "HeartbeatEnabled":true,
  "ValidationScriptID":"7",
  "generatepassword":true,
  "AccountTypeID":"65",
  "ADDomainNetBIOS":"test",
  "HeartbeatSchedule":"17:04"
 }
 
Any ideas how to get around this?  I could just do a string replace and remove the \,  but is it possible to make this work with the \ included?
 
Best regards,
Johhny 
Link to comment
Share on other sites

Hi Johhny

 

You also could go for the following approach. Create a PowerShell object and convert it to JSON. Then you don't have to care about special character and escaping.

 

$Body = @{
            PasswordList = $Name
            Description = $Description
            ApplyPermissionsForUserID = $global:UserToPermit
            CopySettingsFromTemplateID = $global:PasswordstateTemplateID
            LinkToTemplate = "False"
            Permission = "A"
            PrivatePasswordList = "false"
            NestUnderFolderID = $ParentFolderID
            APIKey = $global:PasswordStateSystemWideAPIKey
        }
        $jsonBody = $Body | ConvertTo-Json

 

Best regards,

 

Fabian

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...