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 *