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.
Post Reply
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.

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

$GetProcessJob = Start-Job -ScriptBlock {
param (
$Domain,
$PCName,
$UserOU,
$UPNSuffix,
$BuildType,
$ALPassword)

$root = [ADSI]"LDAP://$($Domain)"
$searcher = New-Object System.DirectoryServices.DirectorySearcher($root)
$searcher.Filter = "(&(objectClass=user)(sAMAccountName= A$($PCName)))"
$User = $searcher.FindOne()

if ($User)
{
$found = $true
[void][System.Windows.Forms.MessageBox]::Show('Problem Creating User, User Already Exists.', 'Creating User Error')
}
else
{
try
{
$notfound = $true
[ADSI]$OU = "LDAP://$($UserOU)"
$newUser = $OU.Create("user", "CN=A$($PCName)")
$newUser.put("samaccountname", "A$($PCName)")

$newUser.setinfo()
}
catch
{
[void][System.Windows.Forms.MessageBox]::Show('Problem Creating User, normally AD Permissions', 'Creating User Error')
}
try
{
$newUser.setpassword($currentMinistry.ALPassword)
$newUser.put("description", $BuildType)
$newUser.put("userWorkstations", $PCName)
$newUser.put("userPrincipalName", "A$($PCName)$($UPNSuffix)")
$newUser.put("userAccountControl", 66080)
$newUser.setinfo()
}
catch
{
[void][System.Windows.Forms.MessageBox]::Show('Problem Modifying new user.')
}

$done = $true
[void][System.Windows.Forms.MessageBox]::Show('User Creation Complete', 'Creating User')
}
} -Credential $Credential -ArgumentList @($currentMinistry.Domain, $textbox_Build_PCName.Text, "OU=Testing,OU=Desktop ,OU=Resource,DC=****,DC=****", $currentMinistry.UPNSuffix, $combobox_Build_PCBuild.SelectedItem.ToString(),"********")
#Wait until the job is completed
Wait-Job $GetProcessJob
#Get the Job results
$GetProcessResult = Receive-Job -Job $GetProcessJob
#Print the Job results
$GetProcessResult

User avatar
jvierra
Posts: 13615
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.

Post Reply