How to run commands on a secondary window from script

António 1 Reputation point
2022-01-10T16:11:37.767+00:00

I'm taking the first steps on the PowerShell learning and for that reason my apologizes if what I'm going to ask is pretty basic.

I'm trying to run some commands on a remote computer with elevated privileges; for that I have a script_1 that inside as an onliner that calls a script_2 with the credentials (I admit that this may not be the best way to do it, but for commodity purposes for now I will this way).

But if I try to put any command in script_1, those do not run on the window with elevated privileges. I have no clue if doing this is possible and if possible how can that be done. I have searched here and on google but haven't found anything similar.

I really would appreciate some advice on how to manage this.

Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

2 answers

Sort by: Most helpful
  1. MotoX80 36,291 Reputation points
    2022-01-10T19:44:53.167+00:00

    I'm trying to run some commands on a remote computer with elevated privileges;

    You do that with Invoke-Command. This example shows how to test if the account you are using has Administrator access.

    $sb = {
        $admin = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")
        "Running on {0}" -f $env:COMPUTERNAME
        "Your name is {0}" -f  $env:USERNAME 
        "Admin level is {0}" -f  $admin
    }
    
    $User = ".\admin"
    $PWord = ConvertTo-SecureString -String "admin" -AsPlainText -Force
    $Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $User, $PWord
    
    Invoke-Command -ComputerName test10 -ScriptBlock $sb -Credential $Credential 
    
    0 comments No comments

  2. António 1 Reputation point
    2022-01-10T21:08:06.22+00:00

    Hi

    Thank you for your reply.

    I manage to open a powershell window with privileges after running the script, it happens that if I run any command it runs on the window without privileges


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.