Shortcut Credentialing to open an app and explorer window - powershell

I'm attempting to launch a powershell script that requests my password for an admin account for credentials. Once it has my credentials it opens a powershell shell, launches a windows explorer window, and an application, all with the admin credentials. Ideally I would also like for the explorer window and shell to open to a specific location but i haven't tried coding that until I get the credentials working correctly.
Currently every time I try the following code I am told that the username and password is incorrect when I know for a fact that it is the correct username and password.
$MyCredentials = Get-Credential -Credential ''
Start-Process powershell.exe -Credential $MyCredentials -ArgumentList "Start-Process powershell.exe -verb runas"
Start-Process explorer.exe -Credential $MyCredentials
Start-Process 'C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\Microsoft.ConfigurationManagement.exe' -Credential $MyCredentials

Related

Powershell - open new console as different user in the same window - runas, netonly, NoNewWindow

I need to open Powershell console (within the same window) as different user with /netonly option.
I would like to avoid typing manually passwords, because I will use this console to run some scripts automatically.
I've tried few ways:
1
runas.exe /netonly /user:myDomain\myTestUser powershell.exe
works properly, except:
Opens new window
Ask me for password (as long as I know it is not possible to combine /netonly and /savecred with runas)
2
$Cred = New-Object System.Management.Automation.PSCredential ("myDomain\myTestUser", (ConvertTo-SecureString "myPassword" -AsPlainText -Force))
Start-Process powershell -Credential $Cred -NoNewWindow
Unfortunately this option doesn't allow /netonly switch
3
I used script from:
https://github.com/FuzzySecurity/PowerShell-Suite/blob/master/Invoke-Runas.ps1
and executed:
Invoke-Runas -User "myTestUser" -Password "myPassword" -Domain "myDomain" -Binary C:\Windows\System32\WindowsPowerShell\v1.0\PowerShell.exe -LogonType 0x2
this works properly...except it opens new window
Is there any workaround / is it possible to combine functionality of /netonly switch from runas and NoNewWindow from Start-Process in Powershell

Elevated PS script in Jenkins

I have been trying to run a script from a Windows Jenkins (slave) server. The script is written in PowerShell and requires elevated privileges (such as if one right-clicked on PS and selected run-as-administrator).
Jenkins launches its scripts the following way:
powershell.exe -NonInteractive -ExecutionPolicy ByPass "& 'C:\Users\JOHAN.DER\AppData\Local\Temp\2\hudson9084956499652818911.ps1'"
My script fails because it requires elevated privileges. How can I spawn a new elevated-privileged PS process (that does not require clicking because Jenkins can't do that) that could run my script?
Cheers!
The snippet below checks if current process is elevated and if not, it spawns a new, privileged process. It is little tricky to get output of the child powershell process, so I'm using transcript command to capture it. Below you can find my pipeline definition step:
powershell """
cd "${env.WORKSPACE}"
If (-NOT ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator"))
{
echo "* Respawning PowerShell child process with elevated privileges"
\$pinfo = New-Object System.Diagnostics.ProcessStartInfo
\$pinfo.FileName = "powershell"
\$pinfo.Arguments = "& '" + \$myinvocation.mycommand.definition + "'"
\$pinfo.Verb = "RunAs"
\$pinfo.RedirectStandardError = \$false
\$pinfo.RedirectStandardOutput = \$false
\$pinfo.UseShellExecute = \$true
\$p = New-Object System.Diagnostics.Process
\$p.StartInfo = \$pinfo
\$p.Start() | Out-Null
\$p.WaitForExit()
echo "* Child process finished"
type "C:/jenkins/transcript-${env.JOB_NAME}-${env.BUILD_NUMBER}.txt"
Remove-Item "C:/jenkins/transcript-${env.JOB_NAME}-${env.BUILD_NUMBER}.txt"
Exit \$p.ExitCode
} Else {
echo "Child process starting with admin privileges"
Start-Transcript -Path "C:/jenkins/transcript-${env.JOB_NAME}-${env.BUILD_NUMBER}.txt"
}
# put rest of your script here, it will get executed
# with elevated privileges.
"""
Even though this is an old thread, I still provide my methods here since I had the same problem, hoping to help anyone who is finding the answer.
First of all, This problem is not relevant to Jenkins, it's Windows's issue, you have to enable build-in Administrator to get an elevated privilege, here is the reference:
Administrator user
It is an unelevated administrator account
that is created by default during the installation of Windows. If an
administrator user tries to do something that requires elevated rights
(ex: run as administrator), Windows will display a UAC prompt for the
administrator user to approve before allowing the action.
Built-in "Administrator"
The hidden built-in elevated
"Administrator account" is a local account that has full
unrestricted access rights to the PC. By default, this "Administrator"
account will not be prompted by UAC.
After enabling build-in Administrator, you have two ways to elevate PS script which is triggered by Jenkins:
1.Login Windows with build-in Administrator:
This is the easiest way to achieve your goal, just log in with build-in Administrator, and everything are elevated, including the PS script triggered by Jenkins. (I am using this method.)
2.Pass credential and run as Administrator:
Add some codes in your PS script
$user = "Administrator"
$passwd = "password"
$securePasswd = ConvertTo-SecureString $passwd -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential $user, $securePasswd
#Use Credential to prevent from being prompted for password
#Use argument -Verb RunAs to get script elevated
Start-Process powershell.exe -Credential $credential -ArgumentList "Start-Process powershell.exe -Verb RunAs -ArgumentList '-File hudson.ps1' -Wait"
Try this :
powershell -Command "Start-Process powershell \"-ExecutionPolicy Bypass -NoExit -Command `\"cd \`\"%scriptFolderPath%`\"; & \`\".\%powershellScriptFileName%\`\"`\"\" -Verb RunAs"

Elevate creditals with powershell via Local System Account

I want to deploy code using powershell via Jenkins Job. This works fine in the powershell ise.
$username = "mydomain\builder"
$password = "notmypassword"
$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList #($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
$Arguments = "-ExecutionPolicy Bypass -File C:\Test.ps1 -NoNewWindow -WorkingDirectory C:\Windows\System32\WindowsPowerShell\v1.0 -NoLogo -NonInteractive"
Start-Process "C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe" -Credential $credentials -ArgumentList $Arguments
But when I run it from Jenkins which use the local system I get the following error message.
Start-Process : This command cannot be run due to the error: Access is denied.
At C:\WINDOWS\TEMP\hudson5557889306949142167.ps1:7 char:1
+ Start-Process powershell.exe -Credential $credentials -ArgumentList $
If change I change the Jenkins service to another account it works. Why won't elevated permission work under the local system account?
note: the only code in test.ps1 is New-Item c:\scripts\new_file.txt
There seems to be a restriction on certain commands when a script is run under LocalSystem. This makes sense in terms of security, given that LocalSystem:
has complete unrestricted access to local resources. This is also the disadvantage of LocalSystem because a LocalSystem service can do things that would bring down the entire system.
Reference: MSDN, The LocalSystem Account
There is a similar question at SuperUser: Can not create process with elevated permissions from LocalSystem account with no answer so far a reference to this answer now.
There is a similar question at TechNet: Runing PowerShell script with the permissions of the LocalSystem user with answers suggesting to run the script via Task Scheduler.
I can think of using runas with /savecred and a /user:... with appropriate permissions whose password never expires. AFAIR you have to invoke runas with /savecred interactively once, enter the credentials and it will take the saved credentials from the next invocation onwards.

How to prompt to run EXE as different user in powershell

How would I go about running an EXE as a different user? How could I prompt for credentials or atleast ask for the password for a local admin to launch an exe through powershell. I'm having a hard time getting the runas command to work.
This was the latest thing I tried:
runas -credential .\me c:\windows\system32\notepad.exe
This works in the powershell terminal:
runas /user:asdf c:\windows\system32\notepad.exe but doesn't ask for credentials in a standalone powershell script.
This is a simple operation.
Start-Process "c:\windows\system32\notepad.exe" -Credential $(Get-Credential)
Using Get-Credential will prompt the user for credentials, You can also store it in a variable.
$Creds = Get-Credential
Start-Process "c:\windows\system32\notepad.exe" -Credential $Creds
Try following
Start-Process notepad.exe -Verb RunAsUser
change directory to .exe directory and run below command
runas /netonly /user:<domain\username> .\<app name>

Invoke-Command and Start-Process Issues

I'm trying to execute the following script:
$Cred = Get-Credential
Invoke-Command -Computername Localhost -Cred $Cred -Scriptblock {Start "Notepad.exe" -Wait}
Well, the notepad comes up no problem as Administrator but it is not visible in the current user's account.
I think it's not possible to see gui in an interactive session with different credential, it live in another user session.
Workaround:
start-process notepad.exe -Credential $Cred
I've run into this problem with PS Remoting and could not find a way to get an app running under one set of credentials to show up on the interactive desktop of a different user. I eventually gave up and used SysInternals utility psexec along with its -i parameter.