Elevate permissions within script

This topic contains 8 replies, has 2 voices, and was last updated by Profile photo of Mark Hammonds Mark Hammonds 10 months, 2 weeks ago.

  • Author
    Posts
  • #34009
    Profile photo of Mark Hammonds
    Mark Hammonds
    Participant

    so I have a startup script where I need to run the script as a user to collect environment variables halfway through the script I need to run a command as admin. here is the catch the execution policy is set to restricted to invoke command will not work. any suggestions?

    here is the example

    #requires -Version 3
    Set-StrictMode -Version Latest
    Set-Location $Env:userprofile
    $Report = @()
    $Reg = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders'
    $Folder_Redirect = Get-Item $Reg | Select-Object -ExpandProperty property |
    ForEach-Object { New-Object psobject -Property @{"property"=$_; "Value" = (Get-ItemProperty -Path $Reg -Name $_).$_ }}
    $Folder_Redirect = ($Folder_Redirect | ?{$_.Value -like "\\cam\fldrrdr\*"})[-0] 
    $UsrNfo = ($Folder_Redirect.Value.Split("\")[-3] + "\" + $Folder_Redirect.Value.Split("\")[-2])
    #########################################################Security Info################################################
    $adminname = "hammmondsm_admin"
    $PSW = "76492d1116743f0423413b16050a5345MgB8AHMAbwBwAC8AcAAzAHMATQBaAG8AagByAC8ATQBqAGgAagBIAC8ATwArAGcAPQA9AHwANgA3ADAAYwBmADEAMgAxAGQAMgBlADcABlaBLaBLareallylongstring =" | convertto-securestring -key (1..16) 
    $cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $adminname,$PSW
    #########################################################Security Info################################################
    
    #########################################Script Block to move files from offline folder###############################
    Invoke-Command -ComputerName localhost -Credential $cred -PipelineVariable $UsrNfo -ScriptBlock{
                #Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Services\CSC' -Name FormatDatabase -Value 1 #This will Wipe the offline files folder
                #Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\Csc\Parameters'  -Name FormatDatabase -Value 1  #This will Wipe the offline files folder
                Robocopy "C:\WINDOWS\CSC\v2.0.6\namespace\CAM\fldrrdr\$($UsrNfo)” “C:\users\$($UsrNfo)” /E /COPY:DATOU /ZB /R:0 /LOG+:C:\$($UsrNfo.Split("\")[-1])\robolog.txt /TEE 
    }
    #########################################Script Block to move files from offline folder###############################
    
    #######################################Sets all the Registry keys for local user profile##############################
            Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Communicator'  -Name FtReceiveFolder -Value "%USERPROFILE%\Documents\My Recieved Files"
            Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Internet Explorer\Main\WindowsSearch'  -Name 'User Favorites Path' -Value %USERPROFILE%\Favorites
            Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Internet Explorer\Suggested Sites'  -Name 'SlicePath' -Value '%USERPROFILE%\Favorites\Links\Suggested Sites.url'
            Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders' -Name Desktop -Value %USERPROFILE%\Desktop
            Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders' -Name Favorites -Value %USERPROFILE%\Favorites
            Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders' -Name Personal -Value %USERPROFILE%\Document
            Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders' -Name Desktop -Value %USERPROFILE%\Desktop
            Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders' -Name Favorites -Value %USERPROFILE%\Favorites
            Set-ItemProperty -Path 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders' -Name Personal -Value %USERPROFILE%\Documents
            $WshShell = New-Object -comObject WScript.Shell
            $Shortcut = $WshShell. CreateShortcut("$env:USERPROFILE\Links\desktop.lnk")
            $Shortcut.TargetPath =  "$env:USERPROFILE\Desktop"
            $Shortcut.Save()
    #######################################Sets all the Registry keys for local user profile##############################
    
  • #34010
    Profile photo of Mark Hammonds
    Mark Hammonds
    Participant

    wait cant I use Invoke-Command to launch a command prompt with elevated credentials wont that circumvent the execution policy

  • #34011
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    Does the user running the script have admin rights already, or are you talking about trying to use alternate credentials here?

  • #34012
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    Nevermind, I see the credentials in your script. Is hammmondsm_admin a local account or a domain account?

  • #34013
    Profile photo of Mark Hammonds
    Mark Hammonds
    Participant

    domain

  • #34014
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    Should be okay, then. The only problem I see is in how you're trying to pass local variables to Invoke-Command. -PipelineVariable doesn't work that way. Instead, try this:

    Invoke-Command -ComputerName localhost -Credential $cred -ScriptBlock{
                #Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Services\CSC' -Name FormatDatabase -Value 1 #This will Wipe the offline files folder
                #Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\Csc\Parameters'  -Name FormatDatabase -Value 1  #This will Wipe the offline files folder
                Robocopy "C:\WINDOWS\CSC\v2.0.6\namespace\CAM\fldrrdr\$($using:UsrNfo)” “C:\users\$($using:UsrNfo)” /E /COPY:DATOU /ZB /R:0 /LOG+:C:\$(($using:UsrNfo).Split("\")[-1])\robolog.txt /TEE 
    }
    
    

    I should point out that your admin username and password may as well be in plain text. They're encrypted, but the key is right there in the script, and anyone who has that script can read the password. If you hadn't modified it for this post with that "areallylongstring" bit, you'd have already posted your password to the whole internet. 🙂

    There is no way to put a password like that into your script in such a way that it's secure (unless you're okay with anyone who is able to run the script also being able to retrieve the plain-text password). In PowerShell, the ideal solution is to set up a custom PSRemoting endpoint which runs as an administrator account, but the authentication / authorization to that endpoint comes from the users themselves. With that approach, you get two big advantages: no hard-coded credentials (users are authenticated as themselves), and you can limit _what_ is done with the admin credentials by locking down the endpoint (NoLanguage mode, only one function exposed that does what you need it to do, etc.)

  • #34019
    Profile photo of Mark Hammonds
    Mark Hammonds
    Participant

    ok I got the execution working how ever I run into this problem

    Invoke-Command -ComputerName $env:COMPUTERNAME -Credential Get-Credential -ArgumentList $UsrNfo,$userID -ScriptBlock{
                #Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Services\CSC' -Name FormatDatabase -Value 1 #This will Wipe the offline files folder
                #Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\Csc\Parameters'  -Name FormatDatabase -Value 1  #This will Wipe the offline files folder
                Robocopy "C:\WINDOWS\CSC\v2.0.6\namespace\CAM\fldrrdr\$($args[0])” “C:\users\$($args[0])” /E /COPY:DATOU /ZB /R:0 /LOG+:C:\Users\$($args[1])\robolog.txt /TEE 
    }
    

    it does kick off robocopy how ever it is running into an old robocopy issue run as user vs run as admin. this happens when you right click on cmd prompt and select run as other user vs run as admin.

    ERROR : You do not have the Backup and Restore Files user rights.
    *****  You need these to perform Backup copies (/B or /ZB).
    
    ERROR : Robocopy ran out of memory, exiting.
    ERROR : Invalid Parameter #%d : "%s"
    
    ERROR : Invalid Job File, Line #%d :"%s"
    
    
      Started : %hs
    
       Source %c 
    
         Dest %c 
           Simple Usage :: ROBOCOPY source destination /MIR
    
                 source :: Source Directory (drive:\path or \\server\share\path).
            destination :: Destination Dir  (drive:\path or \\server\share\path).
                   /MIR :: Mirror a complete directory tree.
    
        For more usage information run ROBOCOPY /?
    
                                                              
    ****  /MIR can DELETE files as well as copy them !
    

    Tried this

    $vara = "C:\WINDOWS\CSC\v2.0.6\namespace\CAM\fldrrdr\$($UsrNfo)","C:\users\$($UsrNfo)",'/E','/COPY:DATOU','/ZB','/R:0','/LOG+:C:\Users\108736\robolog.txt /TEE'
    Start-Process -FilePath C:\Windows\System32\Robocopy.exe -NoNewWindow -Credential Get-Credential -ArgumentList $vara 
    

    and this is what I got

    -------------------------------------------------------------------------------
       ROBOCOPY     ::     Robust File Copy for Windows                              
    -------------------------------------------------------------------------------
    
      Started : Mon Jan 18 10:21:41 2016
    
       Source : C:\WINDOWS\CSC\v2.0.6\namespace\CAM\fldrrdr\HTN\108736\
         Dest : C:\users\HTN\108736\
    
        Files : *.*
    	    
      Options : *.* /TEE /S /E /COPY:DATOU /ZB /R:0 /W:30 
    
    ------------------------------------------------------------------------------
    
    ERROR : You do not have the Manage Auditing user right.
    *****  You need this to copy auditing information (/COPY:U or /COPYALL).
    
           Simple Usage :: ROBOCOPY source destination /MIR
    
                 source :: Source Directory (drive:\path or \\server\share\path).
            destination :: Destination Dir  (drive:\path or \\server\share\path).
                   /MIR :: Mirror a complete directory tree.
    
        For more usage information run ROBOCOPY /?
    
                                                              
    ****  /MIR can DELETE files as well as copy them !
    
  • #34021
    Profile photo of Mark Hammonds
    Mark Hammonds
    Participant

    and if I run any of the robocopy command lines in a Administrator ISE they work fine

  • #34029
    Profile photo of Mark Hammonds
    Mark Hammonds
    Participant

    Rewrote the whole script to be run as administrator. Works now 😀

    #requires -Version 3
    Set-StrictMode -Version Latest
    
    ####################################################Fully Automated Code##############################################
    $keys = Get-ChildItem HKU: | Select Name | ?{$_.Name.Length -gt 46 -and $_.Name.Length -lt 60}
    Foreach($key in $keys){
        $key = $key.Name.Split("\")[-1]
        $Reg = "HKU:\$($key)\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders"
        $Folder_Redirect = Get-Item $Reg | Select-Object -ExpandProperty property |
        ForEach-Object { New-Object psobject -Property @{"property"=$_; "Value" = (Get-ItemProperty -Path $Reg -Name $_).$_ }}
            Try {
                $Folder_Redirect = ($Folder_Redirect | ?{$_.Value -like "\\cam\fldrrdr\*"})[0] 
                $UsrNfo = ($Folder_Redirect.Value.Split("\")[-3] + "\" + $Folder_Redirect.Value.Split("\")[-2])
                $userID = $UsrNfo.Split("\")[-1]
                $SID = $key
                Robocopy "C:\WINDOWS\CSC\v2.0.6\namespace\CAM\fldrrdr\$($UsrNfo)” “C:\users\$($UsrNfo)” /E /COPY:DATOU /ZB /R:0 /LOG+:C:\Users\$($userID)\robolog.txt /TEE
                #Set-ItemProperty -Path 'HKLM:\System\CurrentControlSet\Services\CSC' -Name FormatDatabase -Value 1 #This will Wipe the offline files folder
                #Set-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\Csc\Parameters'  -Name FormatDatabase -Value 1  #This will Wipe the offline files folder
                Set-ItemProperty -Path "HKU:\$($SID)\Software\Microsoft\Communicator"  -Name FtReceiveFolder -Value "%USERPROFILE%\Documents\My Recieved Files"
                Set-ItemProperty -Path "HKU:\$($SID)\Software\Microsoft\Internet Explorer\Main\WindowsSearch"  -Name 'User Favorites Path' -Value %USERPROFILE%\Favorites
                Set-ItemProperty -Path "HKU:\$($SID)\Software\Microsoft\Internet Explorer\Suggested Sites"  -Name 'SlicePath' -Value '%USERPROFILE%\Favorites\Links\Suggested Sites.url'
                Set-ItemProperty -Path "HKU:\$($SID)\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" -Name Desktop -Value %USERPROFILE%\Desktop
                Set-ItemProperty -Path "HKU:\$($SID)\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" -Name Favorites -Value %USERPROFILE%\Favorites
                Set-ItemProperty -Path "HKU:\$($SID)\Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders" -Name Personal -Value %USERPROFILE%\Document
                Set-ItemProperty -Path "HKU:\$($SID)\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" -Name Desktop -Value %USERPROFILE%\Desktop
                Set-ItemProperty -Path "HKU:\$($SID)\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" -Name Favorites -Value %USERPROFILE%\Favorites
                Set-ItemProperty -Path "HKU:\$($SID)\Software\Microsoft\Windows\CurrentVersion\Explorer\User Shell Folders" -Name Personal -Value %USERPROFILE%\Documents
                $WshShell = New-Object -comObject WScript.Shell
                $Shortcut = $WshShell. CreateShortcut("C:\$userID\Links\desktop.lnk")
                $Shortcut.TargetPath =  "C:\$userID\Desktop"
                $Shortcut.Save()
            }
            Catch{}
    }
    ####################################################Fully Automated Code##############################################
    

You must be logged in to reply to this topic.