Avatar of ITguy565
ITguy565
Flag for United States of America asked on

Powershell Logon Script Elevation assistance

Experts,

I have a powershell script that has to be run via an elevated powershell prompt.

#Generate Random Password
add-type -AssemblyName System.Web
$Password = "UserAccount1" + [System.Web.Security.Membership]::GeneratePassword(24,8)

#Command/Uncomment Below Statement : to see Password Generated in the Log File
write-log "Password for $($ENV:computername)\UserAccount1 is $($password)"

Function Write-Log {

    
    
        [cmdletbinding()]
    
        Param(
        [Parameter(Position=0)]
        [ValidateNotNullOrEmpty()]
        [string]$Message,
         [Parameter(Position=1)]
        [int]$Level=3,
        [Parameter(Position=2)]
        [string]$Path="$env:temp\PowerShellLog.txt"
    
        )
        
        #Pass on the message to Write-Verbose if -Verbose was detected
        Write-Verbose -Message $Message
        
        #only write to the log file if the $LoggingPreference variable is set to Continue
        if ($LoggingPreference -eq "Continue")
        {
        
            #if a $loggingFilePreference variable is found in the scope
            #hierarchy then use that value for the file, otherwise use the default
            #$path
            if ($loggingFilePreference)
            {
                $LogFile=$loggingFilePreference
            }
            else
            {
                $LogFile=$Path
            }
            
            $script = $MyInvocation.ScriptName.tostring()
            
            if (-not $LogLevel)
            {
                    #Write-Output "[$Level] $(Get-Date) $script $Message" | Out-File -FilePath $LogFile -Append
                    Write-Output "[$Level] $(Get-Date) $Message" | Out-File -FilePath $LogFile -Append
            }
            else
            {
                if ($Level -le $LogLevel)
                {
                    #Write-Output "[$Level] $(Get-Date) $script $Message" | Out-File -FilePath $LogFile -Append
                    Write-Output "[$Level] $(Get-Date) $Message" | Out-File -FilePath $LogFile -Append
                }
            }
        }
    
    } #end function

$scriptname = "script1"
$loggingPreference = "Continue"
$loggingFilePreference = "c:\$($ScriptName)_$(get-date -f yyyy_MM).txt"

Function invoke-Create-UserAccount1-User([switch]$remove){
    #Check for User
    $check = Get-WmiObject Win32_UserAccount -Filter "LocalAccount='true' and Name='UserAccount1'"
    # If Exists
    if ($Check){
        write-log "User Check : UserAccount1 Local User Found";
        $check2 = net localgroup administrators |Select-String -Pattern '^UserAccount1';
        if ($check2.count -ge 1){write-log "UserAccount1 Found in Local Group Administrators"};
        
        #Define Remove Switch
        if ($remove.IsPresent){
            write-log "Remove Switch Triggered : Removing UserAccount1 Account"
            net user UserAccount1 /del
            $check = Get-WmiObject Win32_UserAccount -Filter "LocalAccount='true' and Name='UserAccount1'"
            if (!$Check){write-log "UserAccount1 Account Removed"}
            EXIT    
        } 
        EXIT

#if Doesn't Exist
    }else {
        write-log "User Check : UserAccount1 User Not Found";
        
        #Create User
        write-host "Creating UserAccount1 User"
        net user "UserAccount1" $($password) /add /Y
        $check = Get-WmiObject Win32_UserAccount -Filter "LocalAccount='true' and Name='UserAccount1'"
        if ($Check){write-log "UserAccount1 Account Successfully Created"}
        
        #Add User To Group
        net localgroup administrators UserAccount1 /add
        $check2 = net localgroup administrators |Select-String -Pattern '^UserAccount1'
        if ($check2.count -ge 1){write-log "UserAccount1 Found in Local Group Administrators"}
        Exit
    }
}
invoke-Create-UserAccount1-User

Open in new window


This script needs to be deployed via logon script through a GPO. what is the easiest way to launch it with admin rights where it will function properly?
PowershellWindows Server 2016Shell Scripting

Avatar of undefined
Last Comment
McKnife

8/22/2022 - Mon
McKnife

Tell me, what action done in the name of the user (not system-wide but user-specific) would need administrative permissions? If you tell me, maybe I can lead you to a better solution, since trying to run elevated as user will not work out, at least not securely. So what is that script trying to set?
ITguy565

ASKER
  #Create User
        write-host "Creating UserAccount1 User"
        net user "UserAccount1" $($password) /add /Y
        $check = Get-WmiObject Win32_UserAccount -Filter "LocalAccount='true' and Name='UserAccount1'"
        if ($Check){write-log "UserAccount1 Account Successfully Created"}
        
        #Add User To Group
        net localgroup administrators UserAccount1 /add
        $check2 = net localgroup administrators |Select-String -Pattern '^UserAccount1'
        if ($check2.count -ge 1){write-log "UserAccount1 Found in Local Group Administrators"}
        Exit
    }

Open in new window

ITguy565

ASKER
@mcknife,

My script is designed to create a User Account on each of my Domain Joined workstations and set that account to a random password.

You can't create the user and add it to the local admins group if you are under a non-elevated powershell prompt.
Experts Exchange is like having an extremely knowledgeable team sitting and waiting for your call. Couldn't do my job half as well as I do without it!
James Murphy
ASKER CERTIFIED SOLUTION
McKnife

THIS SOLUTION ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
GET A PERSONALIZED SOLUTION
Ask your own question & get feedback from real experts
Find out why thousands trust the EE community with their toughest problems.
McKnife

To illustrate my thinking: with local accounts, you will be limited to local resources. With my concept, you have access to domain resources and have a random password and central management at ease.
Another concept (that I don't like very much) is "Microsoft LAPS".
ITguy565

ASKER
LAPS is what we are moving to which is why we are doing this :(
McKnife

Aha. See if the solution from my article wouldn't look much better than LAPS. I think it does.
⚡ FREE TRIAL OFFER
Try out a week of full access for free.
Find out why thousands trust the EE community with their toughest problems.