Run code block as different user

Ask your 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.
This topic is 4 years and 8 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked
mgebauer
Posts: 3
Last visit: Mon Oct 16, 2023 12:04 pm

Run code block as different user

Post by mgebauer »

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.     $Credential = Get-Credential ***\**** #User with rights in AD
  3.    
  4.     $GetProcessJob = Start-Job -ScriptBlock {
  5.         param (
  6.             $Domain,
  7.             $PCName,
  8.             $UserOU,
  9.             $UPNSuffix,
  10.             $BuildType,
  11.             $ALPassword)
  12.        
  13.         $root = [ADSI]"LDAP://$($Domain)"
  14.         $searcher = New-Object System.DirectoryServices.DirectorySearcher($root)
  15.         $searcher.Filter = "(&(objectClass=user)(sAMAccountName= A$($PCName)))"
  16.         $User = $searcher.FindOne()
  17.        
  18.         if ($User)
  19.         {
  20.             $found = $true
  21.             [void][System.Windows.Forms.MessageBox]::Show('Problem Creating User, User Already Exists.', 'Creating User Error')
  22.         }
  23.         else
  24.         {
  25.             try
  26.             {
  27.                 $notfound = $true
  28.                 [ADSI]$OU = "LDAP://$($UserOU)"
  29.                 $newUser = $OU.Create("user", "CN=A$($PCName)")
  30.                 $newUser.put("samaccountname", "A$($PCName)")
  31.                
  32.                 $newUser.setinfo()
  33.             }
  34.             catch
  35.             {
  36.                 [void][System.Windows.Forms.MessageBox]::Show('Problem Creating User, normally AD Permissions', 'Creating User Error')
  37.             }
  38.             try
  39.             {
  40.                 $newUser.setpassword($currentMinistry.ALPassword)
  41.                 $newUser.put("description", $BuildType)
  42.                 $newUser.put("userWorkstations", $PCName)
  43.                 $newUser.put("userPrincipalName", "A$($PCName)$($UPNSuffix)")
  44.                 $newUser.put("userAccountControl", 66080)
  45.                 $newUser.setinfo()
  46.             }
  47.             catch
  48.             {
  49.                 [void][System.Windows.Forms.MessageBox]::Show('Problem Modifying new user.')
  50.             }
  51.            
  52.             $done = $true
  53.             [void][System.Windows.Forms.MessageBox]::Show('User Creation Complete', 'Creating User')
  54.         }
  55.     } -Credential $Credential -ArgumentList @($currentMinistry.Domain, $textbox_Build_PCName.Text, "OU=Testing,OU=Desktop ,OU=Resource,DC=****,DC=****", $currentMinistry.UPNSuffix, $combobox_Build_PCBuild.SelectedItem.ToString(),"********")
  56.     #Wait until the job is completed
  57.     Wait-Job $GetProcessJob
  58.     #Get the Job results
  59.     $GetProcessResult = Receive-Job -Job $GetProcessJob
  60.     #Print the Job results
  61.     $GetProcessResult
jvierra
Posts: 15439
Last visit: Tue Nov 21, 2023 6:37 pm
Answers: 30
Has voted: 4 times
Been upvoted: 33 times

Re: Run code block as different user

Post by jvierra »

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.
This topic is 4 years and 8 months old and has exceeded the time allowed for comments. Please begin a new topic or use the search feature to find a similar but newer topic.
Locked