Run code block as different user

Ask your Windows PowerShell-related questions, including questions on cmdlet development!
Forum rules
Do not post any licensing information in this forum.

Any code longer than three lines should be added as code using the 'Select Code' dropdown menu or attached as a file.
Locked
mgebauer
Posts: 3
Joined: Tue Jun 04, 2019 5:33 pm

Run code block as different user

Post by mgebauer » Tue Jul 09, 2019 12:04 pm

I am just not getting this error. Not sure if it's Powershell Studio or just the code itself.

I am trying to create a user in AD with a different user's credentials in one of many domains. The RSAT tools are more than likely not going to be available on the PC this will run on, so the nice built in commands aren't an option, which is why I turned to ADSI.

When running straight as someone with rights that works great. On a VM I am logged in as someone without rights in AD, and this works great.

When I run it in Powershell Studio I get
ERROR: [localhost] An error occurred while starting the background process. Error reported: The directory name is invalid.
ERROR: + CategoryInfo : OpenError: (localhost:String) [], PSRemotingTransportException
ERROR: + FullyQualifiedErrorId : -2147467259,PSSessionStateBroken


Here is the trouble spot.
  1. Write-Log "Creating an autologon user named $($textbox_Build_PCName.Text).$($currentMinistry.Domain) in $($combobox_Build_MinistryList.Text)"
  2.  
  3.     $Credential = Get-Credential ***\**** #User with rights in AD
  4.  
  5.    
  6.  
  7.     $GetProcessJob = Start-Job -ScriptBlock {
  8.  
  9.         param (
  10.  
  11.             $Domain,
  12.  
  13.             $PCName,
  14.  
  15.             $UserOU,
  16.  
  17.             $UPNSuffix,
  18.  
  19.             $BuildType,
  20.  
  21.             $ALPassword)
  22.  
  23.        
  24.  
  25.         $root = [ADSI]"LDAP://$($Domain)"
  26.  
  27.         $searcher = New-Object System.DirectoryServices.DirectorySearcher($root)
  28.  
  29.         $searcher.Filter = "(&(objectClass=user)(sAMAccountName= A$($PCName)))"
  30.  
  31.         $User = $searcher.FindOne()
  32.  
  33.        
  34.  
  35.         if ($User)
  36.  
  37.         {
  38.  
  39.             $found = $true
  40.  
  41.             [void][System.Windows.Forms.MessageBox]::Show('Problem Creating User, User Already Exists.', 'Creating User Error')
  42.  
  43.         }
  44.  
  45.         else
  46.  
  47.         {
  48.  
  49.             try
  50.  
  51.             {
  52.  
  53.                 $notfound = $true
  54.  
  55.                 [ADSI]$OU = "LDAP://$($UserOU)"
  56.  
  57.                 $newUser = $OU.Create("user", "CN=A$($PCName)")
  58.  
  59.                 $newUser.put("samaccountname", "A$($PCName)")
  60.  
  61.                
  62.  
  63.                 $newUser.setinfo()
  64.  
  65.             }
  66.  
  67.             catch
  68.  
  69.             {
  70.  
  71.                 [void][System.Windows.Forms.MessageBox]::Show('Problem Creating User, normally AD Permissions', 'Creating User Error')
  72.  
  73.             }
  74.  
  75.             try
  76.  
  77.             {
  78.  
  79.                 $newUser.setpassword($currentMinistry.ALPassword)
  80.  
  81.                 $newUser.put("description", $BuildType)
  82.  
  83.                 $newUser.put("userWorkstations", $PCName)
  84.  
  85.                 $newUser.put("userPrincipalName", "A$($PCName)$($UPNSuffix)")
  86.  
  87.                 $newUser.put("userAccountControl", 66080)
  88.  
  89.                 $newUser.setinfo()
  90.  
  91.             }
  92.  
  93.             catch
  94.  
  95.             {
  96.  
  97.                 [void][System.Windows.Forms.MessageBox]::Show('Problem Modifying new user.')
  98.  
  99.             }
  100.  
  101.            
  102.  
  103.             $done = $true
  104.  
  105.             [void][System.Windows.Forms.MessageBox]::Show('User Creation Complete', 'Creating User')
  106.  
  107.         }
  108.  
  109.     } -Credential $Credential -ArgumentList @($currentMinistry.Domain, $textbox_Build_PCName.Text, "OU=Testing,OU=Desktop ,OU=Resource,DC=****,DC=****", $currentMinistry.UPNSuffix, $combobox_Build_PCBuild.SelectedItem.ToString(),"********")
  110.  
  111.     #Wait until the job is completed
  112.  
  113.     Wait-Job $GetProcessJob
  114.  
  115.     #Get the Job results
  116.  
  117.     $GetProcessResult = Receive-Job -Job $GetProcessJob
  118.  
  119.     #Print the Job results
  120.  
  121.     $GetProcessResult

jvierra
Posts: 13932
Joined: Tue May 22, 2007 9:57 am
Contact:

Re: Run code block as different user

Post by jvierra » Tue Jul 09, 2019 1:11 pm

You can't use MessageBox in a job script.

This would be the correct way to do this:

Code: Select all

Write-Log "Creating an autologon user named $($textbox_Build_PCName.Text).$($currentMinistry.Domain) in $($combobox_Build_MinistryList.Text)"
$Credential = Get-Credential ***\**** #User with rights in AD
$sb = {
    param (
        $Domain,
        $PCName,
        $UserOU,
        $UPNSuffix,
        $BuildType,
        $ALPassword
    )
    
    try {
        $samaccountname = "A$PCName"
        $searcher = [adsisearcher]"(sAMAccountName=$samaccountname)"
        $searcher.SearchRoot = "LDAP://$($Domain)" # doamin must be DN format
        if($searcher.FindOne()){
            Throw "User already exists in AD $samaccountname"
        } else {
            $OU = [ADSI]"LDAP://$($UserOU)"
            $newUser = $OU.Create('user', "CN=$samaccountname")
            $newUser.put('samaccountname', "$samaccountname")
            $newUser.put('description', $BuildType)
            $newUser.put('userWorkstations', $PCName)
            $newUser.put('userPrincipalName', "$samaccountname$$UPNSuffix")
            $newUser.put('userAccountControl', 66080)
            $newUser.setinfo()
            $newUser.setpassword($ALPassword)
        }
    }
    catch {
        Throw $_
    }
}

$argList = @(
    $currentMinistry.Domain,
    $textbox_Build_PCName.Text,
    "OU=Testing,OU=Desktop ,OU=Resource,DC=****,DC=****",
    $currentMinistry.UPNSuffix,
    $combobox_Build_PCBuild.SelectedItem.ToString(),
    '********'
)

Start-Job -ScriptBlock $sb -Credential $Credential -ArgumentList $argList |
    Wait-Job $job | Receive-Job 
I also think you need to be careful with the arglist contents. You had some mistakes.

Locked