Skip to content

Instantly share code, notes, and snippets.

@cmcdevitt
Created January 16, 2015 19:14
Show Gist options
  • Select an option

  • Save cmcdevitt/7704051485b08a67be70 to your computer and use it in GitHub Desktop.

Select an option

Save cmcdevitt/7704051485b08a67be70 to your computer and use it in GitHub Desktop.
ServiceNow Orchestration Invoke-Command Add User to Local Group
#Note: Rember the commands are executed LOCALY on the MID server
#Note: The MID server has the same rights as the Service Account Running it.
#Note: The Service Accounts rights can be used to execute commands on remote hosts, if configured to do so
#Note: You may need to use different accounts to do what you need:
#Note: To execute on a remote windows host with a different account:
#Note: You need to rely on a PowerShell Commands which support -ComputerName & -Credential
#Note: Or you need to rap you script in the PowerShell Invoke-Command
#Test-WSMan -ComputerName $computer; #This works used to test remote connection
#Invoke-Command -ComputerName $computer -credential $cred -ScriptBlock {net localgroup administrators}; #This works
#Invoke-Command -ComputerName $computer -credential $cred -ScriptBlock {[Environment]::UserName;}; #This works
#get-wmiobject Win32_BIOS -computer $computer -credential $cred; #This works
#[Environment]::UserName; #This works (It's run locally on the MID Server and returns 'SYSTEM' as expected for me)
#These 3 lines work togetehr to return a list of users from a group
$workstation = [ADSI]("WinNT://" + $computer + ",computer");
$AdminGroup = $workstation.psbase.children.find("Administrators");
($AdminGroup.psbase.invoke("Members") | %{$_.GetType().InvokeMember("Adspath", 'GetProperty', $null, $_, $null)}) -replace ('WinNT://DOMAIN/' + $computer + '/'), '' -replace ('WinNT://DOMAIN/', 'DOMAIN\') -replace ('WinNT://', '');
#Example of Invoke-Command
$userName = '123456';
$groupName = 'Administrators';
#Note: $computer is automaticaly created from the HostName field by Orchestration
#Note: You NEED to pass parameters to a ScriptBlock
Invoke-Command -ComputerName $computer -credential $cred -ArgumentList $computer,$userName,$groupName -ScriptBlock {
param($hostName,$userName,$groupName) $OFS=',';
$domainName = $env:userdomain; #Probably Should pass this
$objUser = [ADSI]"WinNT://$domainName/$userName,user";
$objGroup = [ADSI]"WinNT://$hostName/$groupName,group";
#$objGroup.add($objUser.Path); #Add User
#$objGroup.remove($objUser.Path); #Remove User
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment