Powershell to import users/update users

Document created by Jason Long on Aug 28, 2017
Version 1Show Document
  • View in full screen mode

Just wanted to share some code that i have scratched together for automatically adding new users to Samanage from a CSV (I generate this from Active Directory with another script). I am no script master, and this is still in development (i still need to add in the section to automatically delete users from Samanage when their Active Directory accounts are removed), so i am sure there are plenty of places where this script can be improved upon.  I generate a Few CSV files during this process that i really don't need, but i have found having those available to audit and verify that things are working has been well worth it.  I am also only looking at the users manager (Reports_to field), location, and UPN for updating.   you could easily add in for Title, Department, phone number, etc as needed for updating.  

 

We also began our Samanage journey by using SSO with an on-prem ADFS setup.  We then moved to an Azure ADFS later on.  This meant that logins were no longer based on email addresses, but on UPNs, long story short we found that some mismatched, so I also included logic in here to update users ensuring that their UPN is set for the Samanage Email.  

 

Finally, i could never get JSON tokens to work for authentication in Powershell, so we have decided it is worth the cost to have one local (to Samanage) account that will handle our automation.  We work with Dells and there is a way to get API access to get Dell warranties (you have to sign up and register for Dell Tech Direct), so this account will also end up being used to automate that with Samanage as well and any other automation we come up with in the future.  

 

#script to automate user creation and maintenance with Samanage API

#####DECLARING VARIABLES#####

#sets up the admin account to authenticate with. Must have Admin rights in Samanage
$username = "user@company.com"
$Password = ConvertTo-SecureString "Password" -AsPlainText -Force
$admin = new-object System.Management.Automation.PSCredential ($username, $Password)

#sets up the headers to access the API
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Accept", 'application/vnd.samanage.v1.1+xml')

#imporst the CSV that was generated by exporting AD users
$AD_Users = import-csv ".\ad_Users.csv" -Header 'Email', 'UPN', 'Name', 'Title', 'Phone', 'Mobile Phone', 'Language', 'Site', 'Department', 'Reports_To', 'Role'

#sets up a new_user variable to write a new user CSV and an update_user variable for users who need to be updated and a Delete_User variable for users that are no longer with the company
$new_user = @()
$update_users = @()
$delete_User = @()

#####Declaring Functions#####

Function Get-SamanageUsers
{
#deletes the Samanage csv file and creates a fresh one to ensure we are running against the latest data.
if (test-path ".\samanage_users.csv" -PathType leaf)
{Remove-Item samanage_users.csv -Force
New-Item samanage_users.csv -type file
}
else{
new-Item Samanage_users.csv -ItemType file
}

#sets the page to pull users from (only 100 results may be pulled at a time)
[int]$Page=1
[int]$pages = [math]::Round((Get-Content ad_users.csv | measure-object -Line).lines / 20)
$pages ++
$pages ++

#sets up a loop to get all of the user information from Samanage until it has all of the users
Do{
#Calls the API to pull User data and saves it into an XML file
$Get_user = Invoke-webrequest https://gallup.samanage.com/users.xml?page=$page -Credential $admin -Method GET -Headers $headers -OutFile "samanage_Users.xml"

#imports the XML so that it can be manipulated
[xml]$samage_users = Get-Content "samanage_users.xml"
#Converts the xml to a CSV file
$samage_users.users.user | select-Object @(
@{l="Email";e={$_.email}},
@{l="Name";e={$_.name}},
@{l="ID";e={$_.ID}},
@{l="Phone";e={$_.phone}},
@{l="Site";e={$_.site.name}},
@{l="Reports_To";e={$_.reports_to.name}},
@{l="Reports_To_Email";e={$_.reports_to.email}})|
export-csv "Samanage_users.csv" -NoTypeInformation -Append

$page ++
start-sleep -s 10
}
While ($page -lt ($pages + 2))
}

Function NewUsers
{
foreach ($user in $new_user)
{
#checks for the New_user.xml file, deletes it if it exists, then creates a blank version
if (test-path (".\new_User.xml") -PathType Leaf)
{Remove-Item new_user.xml
new-item new_user.xml -ItemType file
}
Else {new-item new_user.xml -ItemType file}

#Fills out the XML code for the user to be created
$XML = "<user><email>" + $user.Email.trim() + "</email><disabled>false</disabled><name>" + $user.Name.trim() + "</name><phone>" + $user.Phone + "</phone><role><name>Requester</name></role></user>"

#Writes the XML to the New_User.xml file
$xml | Out-File "new_user.xml" -Append

#imports the new_user.xml file as an xml variable
[xml]$upload = Get-Content "new_user.xml"

#resets the Header information for using the API
$headers = $Null
$headers = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
$headers.Add("Accept", 'application/xml')

#Calls the Rest API to create the new user
Invoke-RestMethod https://api.samanage.com/users.xml -Credential $admin -Method Post -Headers $headers -ContentType 'text/xml' -Body $upload
}
}

Function UpdateUser
{
foreach ($user in $update_users)
{
#checks for the update_user.xml file, deletes it if it exists, then creates a blank version
if (test-path (".\update_user.xml") -PathType Leaf)
{
Remove-Item update_user.xml
New-Item update_user.xml -ItemType File
}
else {New-Item update_user.xml -ItemType File}

#fills out the XML code for updating a user
$XML = "<user><email>" + $user.upn + "</email><site>" + $user.site + "</site><reports_to><email>"
foreach($associate in $samage_user_list)
{
if ($associate.name -eq $user.reports_to)
{
$XML += $associate.email.trim()
}
}
$xml += "</email></reports_to></user>"

#writes the XML to the update_user.xml file
$xml | Out-File "update_user.xml" -Append

#imports the update_user.xml file to an XML variable
[xml]$upload = Get-Content "update_user.xml"

#gets the ID for the user to be updated
foreach ($associate in $samage_user_list)
{
if ($user.email -eq $associate.email)
{
$ID = $associate.ID.Trim()
}
}

#sets the URL that will be used
$URI = "https://api.samanage.com/users/" + $ID + ".xml"

#Calls the Rest API to update the user
Invoke-RestMethod $URI -Credential $admin -Method PUT -Headers $headers -ContentType 'text/xml' -Body $upload
}
}

Function Delete_User
{

}

#####BEGIN SCRIPT#####

#Runs the Get-SamanageUsers function to generate a CSV of all users in Samanage
Get-SamanageUsers

#imports the Samanage users csv file
$samage_user_list = import-csv ".\samanage_users.csv" -Header 'Email', 'Name', 'ID', 'Phone', 'Site', 'Reports_To', 'Reports_To_Email'

#cycles through each email checking if it is a new user If it is a new user, then adds the user to the new user list
foreach ($Email in $AD_Users)
{
if ($samage_user_list.Email -contains $email.Email)
{}
else
{
if ($samage_user_list.Email -contains $email.UPN)
{}
else
{
$new_user += $email
}
}
}
$new_user | Export-Csv "new_user.csv" -NoTypeInformation

#Runs the NewUsers function to add the new Users to Samanage
NewUsers

#runs the Get-SamanageUSers function to get a fresh list of the Samanage users
Get-SamanageUsers

#imports the Samanage users csv file
$samage_user_list = import-csv ".\samanage_users.csv" -Header 'Email', 'Name', 'ID', 'Phone', 'Site', 'Reports_To', 'Reports_To_Email'

#cycles through each email checking if the user account has been updated
foreach ($email in $AD_users)
{
if ($samage_user_list.Email -contains $Email.Email)
{
$match = $samage_user_list | where {$_.Site -eq $email.Site}
if ($match)
{
$match2 = $samage_user_list | where {$_.Reports_To -eq $email.Reports_to}
if ($match2)
{
$match3 = $samage_user_list | where {$_.email -eq $email.upn}
if ($match3)
{}
Else
{
$update_users += $Email
}
}
Else
{
$update_users += $Email
}
}
else
{
$update_users += $Email
}
}
}
#exports the update user variable to a CSV
$update_users | Export-Csv "updateuser.csv" -NoTypeInformation

#Calls the UpdateUser function to update the Site and Go-To of users to keep current
UpdateUser

 

 

 

Hope this helps others with some automation!

2 people found this helpful

Attachments

    Outcomes