Powershell Ruan As Administrator

This topic contains 18 replies, has 5 voices, and was last updated by Profile photo of Mr. Jacko Mr. Jacko 2 years, 4 months ago.

  • Author
    Posts
  • #16840
    Profile photo of Mr. Jacko
    Mr. Jacko
    Participant

    Sorry for my bad English.
    I wanted to ask if there is a solution for this problem.
    Run powershell in administrator mode and then run a command that writes to me in a file the characteristics of the host it runs on.
    By executing these commands:
    Start-Process-Verb RunAs PowerShell
    $ computers = Get-WmiObject-Class Win32_ComputerSystem
    $ computer | out-file c: \ filename.txt
    the thing works.
    I tried to put these lines in a file .ps1 and run
    What happens is that I open powershell, run the first line (Start-Process PowerShell-Verb RunAs), which in turn opens a new shell in administrator mode but then the execution of subsequent commands continue in the original shell (the one without administrator rights) and it generates error.
    In practice, I wanted to ask if there is a way to pass the commands in the .ps1 from the shell normal in to with administrative rights.
    Thank you

  • #16841
    Profile photo of Don Jones
    Don Jones
    Keymaster

    Look at the -Command parameter of PowerShell.exe. That's how you launch a new copy of PowerShell and pass in commands.

  • #16842
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator
  • #16843
    Profile photo of Mr. Jacko
    Mr. Jacko
    Participant

    Thank you.
    I can create a script without operator intervention?
    I did not understand, however, how then to pass the following commands:
    $ Computers = Get-WmiObject-Class Win32_ComputerSystem
    $ Computer | out-file c: \ filename.txt
    Sorry for the banality of the questions but I'm a newbie ....

  • #16881
    Profile photo of Alexander Johansson
    Alexander Johansson
    Participant

    Hello!

    The following should do what you want if I understand your question correctly:

    $args = @'
    powershell.exe -Command {
        $computers = Get-WmiObject -Class Win32_ComputerSystem
        $computers | out-file "c:\temp\filename.txt"
    }
    '@
    
    Start-Process -ArgumentList $args -Verb RunAs PowerShell
    • #17073
      Profile photo of Mr. Jacko
      Mr. Jacko
      Participant

      @Alexander Johansson
      I'm sorry, I'm testing your solution but finding a security issue:
      Could not load file C: \ Users \ test \ Desktop \ New Folder \ prova1.ps1. The execution of scripts is disabled on your system. For more information,
      see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170.
      + CategoryInfo: Security error: (:) [], ParentContainsErrorRecordException
      + FullyQualifiedErrorId: unauthorizedaccess

      I tried to use the -ExecutionPolicy Unrestricted but I always get the same error:

      $args = @'
      powershell.exe [b]-ExecutionPolicy Unrestricted [/b]-Command {
      $computers = Get-WmiObject -Class Win32_ComputerSystem
      $computers | out-file "c:\youfilename.txt"
      $EmailFrom = "notifications@somedomain.com"
      $EmailTo = "mail@gmail.com"
      $Subject = "Notification from XYZ"
      $Body = "this is a notification from XYZ Notifications.."
      $SMTPServer = "smtp.gmail.com"
      $SMTPClient = New-Object Net.Mail.SmtpClient($SmtpServer, 587)
      $SMTPClient.EnableSsl = $true
      $SMTPClient.Credentials = New-Object System.Net.NetworkCredential("login", "password");
      $SMTPClient.Send($EmailFrom, $EmailTo, $Subject, $Body)
      $emailMessage = New-Object System.Net.Mail.MailMessage
      $emailMessage.From = $EmailFrom
      $emailMessage.To.Add($EmailTo)
      $emailMessage.Subject = $Subject
      $emailMessage.Body = $Body
      $emailMessage.Attachments.Add("C:\youfilename.txt")
      $SMTPClient.Send($emailMessage)
      }
      '@

      Start-Process -ArgumentList $args -Verb RunAs PowerShell

  • #17089
    Profile photo of Sam Boutros
    Sam Boutros
    Participant

    This line should give you what you need:
    Get-WmiObject -Class Win32_ComputerSystem | select * | Out-File ($env:COMPUTERNAME + ".txt")

    To make this runs as administrator, on this or any machine, whether they're on the same domain or not, you can use something like:

        $DomainAccount = "domain\user-with-eoungh-permissions-for-task"
        $Targets = @("PC1","PC2","PC3") # or get Target computer list from AD, or network scan, or...
        #
        if (!(Test-Path -Path ".\DomainCred.txt")) {
            Write-Output "Error: missing encrypted pwd file .\DomainCred.txt, enter the pwd to be encrypted and saved to .\DomainCred.txt for future script use:" 
            Read-Host 'Enter the pwd to be encrypted and saved to .\DomainCred.txt for future script use:' -AsSecureString | ConvertFrom-SecureString | Out-File .\DomainCred.txt
        }
        $Pwd = Get-Content .\DomainCred.txt | ConvertTo-SecureString
        $DomainCred = New-Object System.Management.Automation.PSCredential($DomainAccount,$Pwd)
        foreach ($Computer in $Targets) {
            $PC = Invoke-Command -ComputerName $Computer -Credential $DomainCred -ScriptBlock { 
                $data = Get-WmiObject -Class Win32_ComputerSystem | select *
                return $data
            } 
            $PC | Out-File ($Computer + ".txt")
        }
    
  • #17091
    Profile photo of Mr. Jacko
    Mr. Jacko
    Participant

    Thanks!
    your script starts to be too complicated for my skills (beginning now ...).
    what is proposed @Alexander Johansson and built by me by sending email, works if only I could overcome the problem of "The execution of scripts is disabled on your system" without tripping the operator with manual controls as "run as administrator"
    would not be possible to modify the script, as follows so as to overcome the problem?

  • #17103
    Profile photo of Alexander Johansson
    Alexander Johansson
    Participant

    Hello!

    I prefer to answer here so that everyone can see the answers 🙂

    Try to open the powershell console and use the "Set-ExecutionPolicy" cmdlet inside of the console instead of inside the script file, like this:

    Set-ExecutionPolicy 'Unrestricted'

    You can't change the execution policy inside of a script, you need to do it from the console or by the help of a GPO.

    Best Regards Alexander

    • #17104
      Profile photo of Mr. Jacko
      Mr. Jacko
      Participant

      So it seems to work, but my goal is to put everything in a script, complementing what I had suggested in your first post .
      Execution requires a response (Y / N).
      I tried ECHO Y | Set-ExecutionPolicy 'Unrestricted' but does not work ...
      Thank you for the swift and accurate response

  • #17105
    Profile photo of Alexander Johansson
    Alexander Johansson
    Participant

    Hi again!

    If you change the execution policy from the console the setting will be permanent.

    /Alexander

  • #17106
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    If you want Set-ExecutionPolicy to work without prompting, add the -Force switch as well. (However, as has been noted, you can't rely on doing this from inside a script, since the execution policy would already have to be set up to allow scripts to run before that line was executed anyway.)

    piping (echo "Y") to a command is an old Command Prompt trick which sometimes worked, but is never appropriate when working with PowerShell cmdlets or functions.

    • #17108
      Profile photo of Mr. Jacko
      Mr. Jacko
      Participant

      unfortunately the problem is that I should perform the execution of the policy manually on many PCs, located in different places.
      for this I tried to automate the process .....
      also to perform Set-ExecutionPolicy 'Unrestricted' -Force I need to give starting powershell console as administrator on each location ....
      sorry for my questions!

  • #17107
    Profile photo of Alexander Johansson
    Alexander Johansson
    Participant

    Yes I'm sorry that I wasn't so straight forward in my answer, you can change the execution policy from within a script but not if the execution policy is set to restricted.

    /Alexander

  • #17109
    Profile photo of Dave Wyatt
    Dave Wyatt
    Moderator

    If you're in an Active Directory environment, you can use Group Policy to change PowerShell's execution policy. Also, individual users can set it for themselves without admin rights; you just need to add the "-Scope CurrentUser" parameter to the Set-ExecutionPolicy call. For example:

    Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy RemoteSigned -Force
    

    You can also choose an execution policy for the current PowerShell session only, by using a scope of "Process", or by using the -ExecutionPolicy parameter when launching powershell.exe:

    PowerShell.exe -ExecutionPolicy Bypass -File c:\some\script.ps1
    
  • #17110
    Profile photo of Alexander Johansson
    Alexander Johansson
    Participant

    If you are in an Active Directory environment you should set the exectuion policy by a Group Policy, the policy is located as seen in the picture below.

    [img]http://b2b.cbsimg.net/blogs/oct-2010-wstips-1-through-3-tip3-figb.jpg[/img]

    /Alexander

    • #17111
      Profile photo of Mr. Jacko
      Mr. Jacko
      Participant

      Are all in AD.
      Only one group of users is in workgroup.
      On these I get the following error (just because I not run the command manually as administrator):
      Set-ExecutionPolicy: Access is denied to the key 'HKEY_LOCAL_MACHINE \ SOFTWARE \ Microsoft \ PowerShell \ 1 \ ShellIds \ Microsoft.PowerShell 'registry.
      To change the default execution policy scope (LocalMachine)
      start Windows PowerShell with the "Run as administrator". for
      change the execution policy for the current user, run
      "Set-ExecutionPolicy-Scope CurrentUser".
      In C: \ Users \ Walter \ Desktop \ test_mail.ps1: 1 car: 1
      + Set-ExecutionPolicy 'Unrestricted'-Force
      + ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~ ~
      + CategoryInfo: PermissionDenied: (:) [Set-ExecutionPolicy], A
      uthorizedAccessException
      + FullyQualifiedErrorId: System.UnauthorizedAccessException, Microsoft.Pow
      erShell.Commands.SetExecutionPolicyCommand

      my ultimate goal is just to run powerrshell script as administrator without start manually Windows PowerShell with the "Run as administrator"

  • #17112
    Profile photo of Sam Boutros
    Sam Boutros
    Participant

    You can use this script to set Execution Policy on all the computers in the $Targets list to "unrestricted"

        $DomainAccount = "domain\user-with-enough-permissions-for-task"
        $Targets = @("PC1","PC2","PC3") # or get Target computer list from AD, or network scan, or . . .
        #
        if (!(Test-Path -Path ".\DomainCred.txt")) {
            Write-Output "Error: missing encrypted pwd file .\DomainCred.txt, enter the pwd to be encrypted and saved to .\DomainCred.txt for future script use:" 
            Read-Host 'Enter the pwd to be encrypted and saved to .\DomainCred.txt for future script use:' -AsSecureString | ConvertFrom-SecureString | Out-File .\DomainCred.txt
        }
        $Pwd = Get-Content .\DomainCred.txt | ConvertTo-SecureString
        $DomainCred = New-Object System.Management.Automation.PSCredential($DomainAccount,$Pwd)
        foreach ($Computer in $Targets) {
            Invoke-Command -ComputerName $Computer -Credential $DomainCred -ScriptBlock { 
                Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Force} 
            Write-Output "Setting Execution Poliy on $Computer to 'Unrestricted' . . . done"
        }
    

    All you have to do is:
    1. Copy the script and paste it in Powershell_ise (running in elevated permissions)
    2. Edit the first 2 lines to put in an account with sufficient permissions for the task, and edit the Target list in line 2

    That's it, click the run button.

    How does this work on computers with "restricted" execution policy you ask?
    Because this is not running as a script. This is running as a script-block, which is not subject to script execution policy..
    This will even work if run from a computer that's not joined or part of the Target domain, that's why it includes code to ask for and use separate domain credentials.

    Hope that helps..

    • #17113
      Profile photo of Mr. Jacko
      Mr. Jacko
      Participant

      I'll try.
      It seems a little complicated for my skills ......
      Thanks

You must be logged in to reply to this topic.