Rest api authentication issue -Creating a new ticket using powershell

I am trying to create a ticket in the backend using Powershell using rest API. But the authentication fails. Please help me with this. Below is the code for the same.

$user_name = “myusername”
$password = “password”
$RTURL = “http://servername/REST/1.0/ticket/new

Define the ticket content as a hashtable

$ticketContent = @{
Subject = “Test”
Text = “some text”
Queue = “general”

Create a credential object for authentication

$credential = New-Object System.Management.Automation.PSCredential ($user_name, (ConvertTo-SecureString $password -AsPlainText -Force))

Create a session variable for the authentication session

$session = New-PSSession -Credential $credential

Invoke the REST API to create a new ticket

$response = Invoke-RestMethod -Uri $RTURL -Method Post -Body $ticketContent -WebSession $session

Check the response


The error I received while running the above code is

New-PSSession : [localhost] Connecting to remote server localhost failed with the following error message : The client cannot connect to the destination specified in the request.
Verify that the service on the destination is running and is accepting requests. Consult the logs and documentation for the WS-Management service running on the destination, most
commonly IIS or WinRM. If the destination is the WinRM service, run the following command on the destination to analyze and configure the WinRM service: “winrm quickconfig”. For
more information, see the about_Remote_Troubleshooting Help topic.
At line:16 char:12

  • $session = New-PSSession -Credential $credential
  •        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    • CategoryInfo : OpenError: (System.Manageme…RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
    • FullyQualifiedErrorId : CannotConnect,PSSessionOpenFailed
      RT/5.0.2 401 Credentials required

Also I tried the thing which is there in the rt website, this also has the same issue.

$servername=“Your Servername here”
$q=“search/ticket?query=(Status=‘open’ OR Status=‘new’) AND (Queue=‘GENERAL’ OR Queue=‘FOO’) AND Owner=‘Nobody’”
$uri=“https://” + $servername + “/rt/REST/1.0/” + $q + “&” + $u + “&” + $p
$RT=Invoke-WebRequest -Uri $uri -SessionVariable sess

Are you on RT 5.x? Have you tried creating an “auth token” for the user and using that?