I have an RDS environment with an epos application that runs fine under the user that initially installed it but requires any other user to specifically right click the exe and select 'run as administrator' I have a local admin that I would like to use in a script to automate that action and applies the creds for the user.
I have tried the following.
# Construct the credentials object
$username = "svr-rds\xxx"
$password = ConvertTo-SecureString "xxx" -AsPlainText -Force
$cred = New-Object PSCredential -argumentlist $username, $password
Start-Process powershell.exe -Credential $cred -WindowStyle Hidden `
'-noprofile -command "Start-Process C:\Montana\Montana.exe /k -Verb RunAs"'
I have found though that the runas command no matter how you use it opens the application as an empty application frame, if I've researched right, the runas command is not the same as specifically elevating to admin.
is there a solution to this?
Note you stated...
epos application that runs fine under the user that initially
installed it...
Then to install and app, you need to be Admin on the box or use Admin creds when prompted. So, the app is installed as an Admin and global to all users and that app is associated with the user initial user identity only. So, when another user logs on to this what appears to be a shared workstation, that app is never associated with any other user profile. So, one must use the installer identity.
PoSH notwithstanding. RunAs has never meant 'Run Elevated'. It's always meant run with the supplied identity.
Suggestion:
Why not just create a shortcut to the .exe and set it's properties to run as admin?
You can just use that to launch the app with the shortcut settings.
invoke-item 'AppName.lnk'
Example, I run an a regular use all the time, my PoSH host environment is set to restricted. Yet, because I do all things admin in PoSH, I start PoSH as admin and elevated this way:
# Shortcut properties for the ISE
C:\Windows\System32\runas.exe /user:contoso\Administrator "%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy UnRestricted PowerShell_ISE.exe"
# Shortcut properties for the Console Host
C:\Windows\System32\runas.exe /user:contoso\Administrator "%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Unrestricted"
Or just create a shortcut and set the 'Run as administrator' checkbox under the advanced tab of the shortcut properties. if you don't need the extra ExecutionPolicy step as above. Then the whole invoke step.
Related
I want to create a shortcut to all domain users when it is clicked, e.g. notepad++ in admin mode popup without asking users to input password.
i.e.notepad++ in admin mode
Same effect as I told user the admin username and password and ask them right click notepad++ icon then enter username and password.
I tried following but it is not working.
In cmd
"runas /savecred /user:{hostname}\admin "C:\Program Files\Notepad++\notepad++.exe"
It actually only starts notepad++ in normal mode, even I entered admin password.
I tried autoit, but since even running the above not starting notepad++ in admin mode, so it is not working too. I think sanur also not working.
In powershell
Start-Process 'C:\Program Files\Notepad++\notepad++.exe' -Verb runAs
Elevated window pop up and asking to enter admin username and password, the notepad++ started is in admin mode, but I don't want the pop up. And I couldn't find a way pass in the username and password.
In powershell
$username = "admin"
$password = "password"
$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList #($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
powershell Start-Process "C:\Program Files\Notepad++\notepad++.exe" -Credential ($credentials)
It actually only starts notepad++ in normal mode.
Thank you Theo for the comments.
The solution is
Create a shortcut and set it run as admin, eg, C:\temp\Notepad++.lnk
By right-click the normal shortcut --> Advanced --> tick Run as administrator --> OK
Create a .bat to start the shortcut eg, C:\temp\notepad.bat (we need this step because runas cannot start .lnk file)
The .bat file here also written to avoid a cmd window popup when run
#echo off
#start "" "C:\temp\Notepad++.lnk"
Create autoit script to run the .bat by runas, eg. notepad.au3
RunAs ( "{adminAccount}", "{hostname}", "{adminPassword}", 1, "C:\temp\notepad.bat")
Use autoit to turn au3 script to exe
The notepad++ in admin mode will be started without any elevated window pop up to ask you for admin credential.
I want to run one command with saved credentials on powershell, i have the following script
$user = "test"
$passwd = ConvertTo-SecureString -String "ExtremelyStrongPassword" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential -ArgumentList $user, $passwd
Copy-Item -Path "C:\Temp\*" "C:\Program Files\Test\" -Credentials $cred
The user doesn't have administrator permissions, but in the localhost we have an user with administrator permissions to run these process.
The error returned is "Access Denied"
How do i pass these parameters to run a command with elevation?
Never pass plain text credentials in a script. Use the Get-Credential cmdlet to collect and use them. Even doing this, the user will get prompted for a password.
This is what the -RunAs switch of Start-Process is for
Or set your script to auto elevate
Or use the credential switch of a cmdlet
Or use a scheduled task with whatever creds you need, and let the user run it.
Use the Requires statement at the top of your script
Store the need creds in the Windows Credential Store and call them
from there
about_Requires - PowerShell | Microsoft Docs
Short description Prevents a script from running without the required
elements.
#Requires -RunAsAdministrator
Start-Process
Example 5: Start PowerShell as an administrator This example starts
PowerShell by using the Run as administrator option.
Start-Process -FilePath "powershell" -Verb RunAs
Using what you have this way:
Copy-Item -Path 'C:\Temp\*' 'C:\Program Files\Test\' -Credentials (Get-Credential -Credential 'Domain\UserName')
With exception of the scheduled task approach, each will prompt the user for a password, which sounds like what you wanting to avoid. So, consider the following:
Accessing Windows Credentials Manager from PowerShell
This simple PowerShell class can be used for working with Credentials
Manager and Password Vault in Windows: checking if account information
is present in the vault, saving credentials to the vault and reading
stored login and password information from the vault.
https://gallery.technet.microsoft.com/scriptcenter/Accessing-Windows-7210ae91
Using the registry to store credentials:
Save Encrypted Passwords to Registry for PowerShell
How can I do a powershell script to ask for administrator rights to the user? To open modal and accept or enter admin password. Is it possible?
I have written a small snippet, add it to the beginning of your script.
if(!([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] 'Administrator')) {
Start-Process -FilePath PowerShell.exe -Verb Runas -ArgumentList "-File `"$($MyInvocation.MyCommand.Path)`" `"$($MyInvocation.MyCommand.UnboundArguments)`""
Exit
}
}
This will check if the script has elevated privileges, if not will present UAC dialog (If secure desktop is enabled, then modal dialog) to ask for administrator credentials to auto elevate.
Duplicate
You should check if you're not admin and run new process (probably with same args) but with RunAs ( means RequireElevation ) flag. Please note, that if UAC is lowered or disabled, this might not work at all.
start-process powershell –verb runAs (you can pass additional properties like $PSCommandPath)
Notes:
You can not to Elevate current process
You can not (using powershell only) run process elevated even if you have admin credentials stored in variables.
not sure if I'm overcomplicating this, I just want to call another script as local admin and have it run.
The command below opens powershell, and in the new window I get an error and then the window closes too fast for me to be able to see it.
start powershell -verb runas -ArgumentList {Invoke-Expression -Command "C:\Script.ps1"}
If you want to stay native powershell use the start-process cmdlet and you can specify the filepath (process to run) as powershell.exe and the -ArgumentList parameters as conditions for your new session. In my example below i'm setting ExecutionPolicy so you don't have to rely on the system level policy, NoProfile will make your script a bit more resiilent by not loading any customized profile on a system.
$Cred = (Get-Credential)
$ScriptLocation = "C:\Temp\TestScript.ps1"
Start-Process -FilePath "powershell.exe" -ArgumentList "-NoProfile -ExecutionPolicy Bypass -File $ScriptLocation" -Credential $Cred
You can see in the script getting a credential object (which you'll probably want to provide so the script will just run) then specifying the script location and executing.
As vonPryz mentioned, you can always troubleshoot by adding -NoExit to your Argument list so the window stays open after executing the script but keep in mind if that if the script location doesn't exist you'll still see the powershell host appear and close right away.
You can also add -WindowStyle Hidden to your argument list to hide any window from appearing at all.
Turned out to be an execution policy issue. This was a device that was non-standard in our environment and didn't have that GPO pushed.
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"