Posted On March 29, 2019

PowerShell: Elevating Credential

kimconnect 0 comments
blog.KimConnect.com >> Codes , Windows >> PowerShell: Elevating Credential
$jumpbox="127.0.0.1"

<#
# Static Credentials (unsecured)
$username = (Get-ADDomain).name+"\ADMINISTRATOR"
$password = "PASSWORD"
#>

# Dynamic Credential method 1
$who = whoami
	if ($who.substring($who.length-2, 2) -eq "-a"){$username=$who;}
    else {$username=$who+"-a";}
#$password = Read-Host -Prompt "Input the password for account $username" -AsSecureString
$password=convertto-securestring "PASSWORD" -AsPlainText -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $username,$password
$elevate = New-PSSession -ComputerName $jumpbox -Credential $cred

<#
# Dynamic Credential method 2
$username = (Get-ADDomain).name+(Read-Host -Prompt 'Input the Admin Username: ')
$securedValue = Read-Host -AsSecureString -Prompt "Input the password for account $username"
$password = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto([System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($securedValue))
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username,$pass
$elevate = New-PSSession -ComputerName $jumpbox -Credential $cred
#>

# Run a script in the context of another user within the current host (no remote execution)
$script="C:\Users\kim\Desktop\test.ps1"
$Args = 'Start-Process -FilePath powershell.exe -ArgumentList \"-ExecutionPolicy Bypass -File "{0}"\" -Verb Runas' -f $script;
start-process powershell.exe -Wait -Credential $cred -NoNewWindow -ArgumentList $Args;

# Remote execution via WinRM
Invoke-Command -Session $elevate -ScriptBlock {
"Running as "+ (whoami)
$proxy="http://proxy:port"
$proxyUri=new-object System.Uri($proxy)
[System.Net.WebRequest]::DefaultWebProxy=new-object System.Net.WebProxy ($proxyUri, $true)
[System.Net.WebRequest]::DefaultWebProxy.Credentials=[System.Net.CredentialCache]::DefaultCredentials

    }

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post

Basic JavaScript: Constructing Strings with Variables

// Examplevar ourName = "freeCodeCamp";var ourStr = "Hello, our name is " + ourName +…

How to move the Active Directory (AD) Global Catalog (GC) to another domain controller (DC)

You don't actually move the GC between servers. Instead, you simply enable the GC on…

Python: Module vs Package vs Library vs Framework

Module is a file which contains various Python functions and global variables. It is simply…