PowerShell RestAPI Create Users from CSV file

Added by Valentino Adam 2 months ago

Hello,

I'm trying to automate creating users with powershell script.
With GET command i'm successfully listing users, but with POST i got weird error:

Invoke-RestMethod : Email is invalidLogin is invalid
At line:10 char:1
+ Invoke-RestMethod -Method $method -Headers $headers $url -ContentType ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

This is my code:

import-csv -Path c:\new_users.csv -UseCulture | ForEach-Object {
$headers = @{'X-Redmine-API-Key'='api-key'}
$method = 'Post'
$type = 'application/json'
$body = '{"user": {"login": "$_.cn", "firstname": "$_.FirstName", "lastname": "$_.LastName", "mail": "$_.mail", "auth_source_id": "1"}}'
$url = 'http://redmine:3000/users.xml'

Invoke-RestMethod -Method $method -Headers $headers $url -ContentType $type -Body $body }

And this is my CSV file:

FirstName;LastName;PrivateEmail;AMAccountName;mail;password;displayName;cn
Test01;User01;test01.user01@private.mail;test01.user01;test01.user01@test.local;password;Test01 User01;test01.user01
Test02;User02;test02.user02@private.mail;test02.user02;test02.user02@test.local;password;Test02 User02;test02.user02

I really need help :)
Thanks