SCCM - Remove-CMUserAffinityFromDevice in c# (no PowerShell)
Hello all
I have the task to write a program that allows me to set a primer user or delete a primer user in SCCM.
The adding (CreateRelationship) works very well, the deleting unfortunately not. What code I have I will write below.
PowerShell is out of question, because 1. the whole thing must be startable from a client system and 2. remote PowerShell is not allowed in the network :-(
So the PowerShell "Remove-CMUserAffinityFromDevice" and "Remove-CMDeviceAffinityFromUser" cmdlets do not work.
I found something under „GitHub - NickolajA/PowerShell => https://github.com/NickolajA/PowerShell“ there is the "Remove-PrimaryDeviceRelationship.ps1" however I can't port the script to C#.
I hope for your help and thank you already now
Greeting Brauschi
using Microsoft.ConfigurationManagement.ManagementProvider;
using Microsoft.ConfigurationManagement.ManagementProvider.WqlQueryEngine;
public void RemoveFromDevice(WqlConnectionManager connection, string DeviceId, string Unique_User_Name0)
{
try
{
// ?!?!?!?!??!?!?!??!?!?!
}
catch (Exception ex)
{
var TempInfo = ex.Message;
}
}
public void AddToDevice(WqlConnectionManager connection, string DeviceId, string Unique_User_Name0)
{
try
{
Dictionary<string, object> Param = new Dictionary<string, object>();
Param.Add("MachineResourceId", DeviceId);
Param.Add("UserAccountName", Unique_User_Name0);
Param.Add("SourceId", "2"); //Administrative change
Param.Add("TypeId", "1");
IResultObject IRO = connection.ExecuteMethod("SMS_UserMachineRelationship", "CreateRelationship", Param);
}
catch (Exception ex)
{
var TempInfo = ex.Message;
}
}
public WqlConnectionManager Connect()
{
try
{
string serverName = SCCMServer;
string userName = DomainName + "\\" + SccmAdminUser;
string userPassword = "Passw0rd1!";
SmsNamedValuesDictionary namedValues = new SmsNamedValuesDictionary();
WqlConnectionManager connection = new WqlConnectionManager(namedValues);
if (System.Net.Dns.GetHostName().ToUpper() == serverName.ToUpper())
{
connection.Connect(serverName);
}
else
{
connection.Connect(serverName, userName, userPassword);
}
return connection;
}
catch (SmsException ex)
{
return null;
}
catch (UnauthorizedAccessException ex)
{
throw;
}
}
Excerpt from:
Script name: Remove-PrimaryDeviceRelationship.ps1
Author: Nickolaj Andersen
Contact: @NickolajA
DateCreated: 2015-04-20
foreach ($Device in $DeviceName) {
$UserMachineRelations = Get-WmiObject -Namespace "root\SMS\site_$($SiteCode)" -Class SMS_UserMachineRelationship -ComputerName $SiteServer -Filter "ResourceName like '$($Device)'"
if ($UserMachineRelations -ne $null) {
if ($PSCmdlet.ShouldProcess($UserMachineRelations.__PATH, "Remove")) {
Remove-WmiObject -InputObject $UserMachineRelations
}
}
}
Thanks at this point also to Nickolaj Andersen