run another program with credentials - powershell

what I'm trying to do is add a user to the local admin group then launch a program with those credentials. I have the first part working:
$env:COMPUTERNAME
$srvgroup = [ADSI]("WinNT://"+$env:COMPUTERNAME+"/Administrators, Group")
$srvgroup.name
$srvgroup.add("WinNT://userID,user")
$srvgroup.Invoke("Members") | foreach {$_.GetType().InvokeMember("Name", 'GetProperty', $null, $_, $null)}
The second part is what I can't seem to get working correctly.
Start-Process runas.exe -Credential DOMAIN\user -ArgumentList '-noprofile -command & "C:\Program Files (x86)\Misc\SecureClient" -verb runas}'
I don't get an error message but the program does not start. I should get a popup window for the application but nothing happens when I try it this way.
Any ideas?

DOMAIN\user is not a full credential. You need to do something like this:
$passwd = ConvertTo-SecureString "opensesame" -Force -AsPlainText
$cred = new-object pscredential 'Domain\user',$passwd
Start-Process -Credential $cred ...

I ended up doing it like, don't really like it but it works:
start-process "cmd.exe" "/c D:\Scripts\client_connect.cmd"
that .cmd file is:
C:\Windows\System32\runas.exe /savecred /user:domain\username"C:\Program Files (x86)\xxx\xxx\sclient.cmd"

Related

How can i run a specific codeblock in PowerShell as an administrator

I want to set registry keys in a PowerShell script but the script has to be executed as the logged in User and only the part where registry keys are set need to run with administrator privileges.
This is what i got yet, unfortunately it is not working:
#Run ScriptBlock as admin
$username = ".\admin"
$password = ConvertTo-SecureString "adminpassword" -AsPlainText -Force
$credential = [pscredential]::new($username,$password)
Start-Process -WindowStyle Hidden -FilePath "powershell" -Credential $credential - ArgumentList '-noprofile -command &{$ScriptBlock -verb runas}'
Is there a better way to do it? I'm really new into scripting.
Thanks a lot!

Powershell Start-Process -NoNewWindow not working with -Credentials

I am looking to run an exe from powershell using a credential. I want the output to be in the same window. This is how my powershell looks.
Start-Process documentation: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.management/start-process?view=powershell-6
$username = 'user'
$password = 'password'
$credentials = New-Object System.Management.Automation.PSCredential -ArgumentList #($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
$pathNew = "c:\pathtomyexe\text.exe"
Start-Process $pathNew -NoNewWindow -Credential ($credentials) -PassThru -Wait
With -Credential ($credentials) a new window is launched.
When I run Start-Process without -Credential, I get result in the same window as expected.
Start-Process $pathNew -NoNewWindow -PassThru -Wait
What am I doing wrong? Any pointers?
Short answer, you aren't doing anything wrong. You just won't be able to do this.
When you run Start-Process -NoNewWindow without -Credential you say: with the current already authenticated credentials, run the executable, and return the results within the same console window.
When you run Start-Process with -Credential the first question is: how do you verify that the Credentials are valid? You can't just look at the username and assume that you can re-use the existing session (e.g. the password might be wrong). To validate the credentials, Start-Process launches a new process as the username/password provided in the Credential object. It performs an authentication check and get a new authentication ticket.
Since it's a new process, running under a completely new context, with new authentication ticket, it ignores the -NoNewWindow flag as there is no way for the current console to redirect the output of the new process, and launches it as a new window.

powershell execute start-process on remote machine

IDE: PowerShell ISE
I have a script which installs the chrome to a remote machine
#Script : Test01.ps1
Start-Process D:\Chrome\Chrome.exe -wait -verb runas
write-host "Chrome is installed"
and I am executing the above script using :
Invoke-Command -ComputerName MySystem18 -FilePath D:\Test01.ps1 -ArgumentList Process
The above script is working on local system (MySystem03) and remote machine (MySystem18).
But when I am executing this in MySystem18 it is not showing up the acknowledgement or cursor after the installation of chrome, even after successful installation of chrome on MySystem18.
Can you tell me how to fix it.
D:\Chrome\Chrome.exe is a path on your remote computer ? If not, try to share a dir with Chrome.exe named yourdirshared on your mysystem03 and replace by \\mysystem03\yourdirshared\Chrome.exe into your ps1
if always doesnt work, you can try to remove -wait my be...
if always doesnt work, are you try to specify credentil parameter?
$Username = 'username'
$Password = 'yourpassword
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass
Invoke-Command -ComputerName "MySystem18" -Credential $Cred -ScriptBlock {Start-Process D:\Chrome\Chrome.exe -wait -verb runas; write-host "Chrome is installed" }

MSBuild calling Powershell with credentials

I'm trying to deploy a windows service using an MSBuild script that runs a Powershell command.
The MSBuild script deploys the files I need and the PowerShell script will uninstall and reinstall the windows service using this command:
Invoke-Command -ComputerName IPAddressHere -FilePath "C:\theScriptFileName.ps1" -credential "TheUserName"
Using an IP address (which I need to because of different domains) I need to use credentials. The problem is that it prompts for a password, which won't work for TeamCity's automation.
I know I can save the credentials into a variable so that the prompt won't show, but I need to get it into a line something like the following that MSBuild can execute:
powershell.exe -NonInteractive -executionpolicy Unrestricted -command "& Invoke-Command -ComputerName IPAddressHere -FilePath 'C:\theScriptFileName.ps1' "
Is there a proper way to do this?
Use the code from Lee Holmes' article on exporting credentials:
function Export-Credential($cred, $path) {
$cred.Password = $cred.Password | ConvertFrom-SecureString
$cred | Export-Clixml $path
}
function Import-Credential($path) {
$cred = Import-Clixml $path
$cred.password = $cred.Password | ConvertTo-SecureString
New-Object System.Management.Automation.PSCredential($cred.username, $cred.password)
}
Save the credentials first in a regular session with the same user on the same machine that will be running the builds. (Well, on each such machine and user profile.) Then, in the build script, Import-Credential from the same path and pass the new $cred to Invoke-Command.
Maybe something like this?
$Creds = $host.ui.PromptForCredential("Need credentials", "Please enter username/password with proper rights on objects to manage.`r`n`r`nExample: AD-Domain\username", $env:userdomain + "\" + $env:username, "")
$IPAddressHere = "192.168.0.1"
powershell.exe -NonInteractive -executionpolicy Unrestricted -command "& {Invoke-Command -ComputerName $IPAddressHere -FilePath 'C:\theScriptFileName.ps1' -credentials $creds}"

Powershell running as a another user with elevated privileges

I have two scripts located in C:\setup: script.ps1 and script1.ps1.
I want to be able to run the script1.ps1 from withing script.ps1 as another user and with elevated privileges but I cannot make it work. The new powershell window opens but closes immediately ...
here is the script:
$cspath = $MyInvocation.MyCommand.Path
$sfolder = Split-Path $cspath
$spath = Join-Path $sfolder "\Script1.ps1"
$sa = "domain\user"
$sap = "userpassword"
$sasp = ConvertTo-SecureString -String $sap -AsPlainText -Force
$sac = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $sa, $sasp
Start-Process $PSHOME\powershell.exe `
-Credential $sac `
-ArgumentList "-Command Start-Process $PSHOME\powershell.exe -ArgumentList `"'$spath'`" -Verb Runas" -Wait
Any help will be appreciated ...
It looks like you might need to adjust your parameters for powershell.exe. Instead of using -ArgumentList, which I don't think is valid, you should use the -File parameter. Also, you will want to use the -ExecutionPolicy Bypass parameter to ensure that the script execution policy is not interfering.
Finally, I would recommend removing the single quotes from around the script path, as the Windows command interpreter does not understand single quotes to surround parameters.
Give this a try:
$ArgumentList = '-Command Start-Process -FilePath $PSHOME\powershell.exe -ArgumentList "-ExecutionPolicy Bypass -File \"{0}\"" -Verb Runas' -f $sPath;
Start-Process $PSHOME\powershell.exe `
-Credential $sac `
-ArgumentList $ArgumentList -Wait
Update
It seems that some quoting rules were at play here as well, since we are embedding one command inside of another. I wrote and tested a fully function script on PowerShell v4.0.
Here are the contents:
# Create test directory and script file
[void](New-Item -Path c:\test -ItemType Directory -Force);
Set-Content -Path c:\test\test1.ps1 -Value 'Add-Content -Path $PSScriptRoot\blah.txt -Value (Get-Date);';
# Get credential and define script path
$Credential = Get-Credential;
$ScriptPath = 'c:\test\test1.ps1';
# Define the command line arguments
$ArgumentList = 'Start-Process -FilePath powershell.exe -ArgumentList \"-ExecutionPolicy Bypass -File "{0}"\" -Verb Runas' -f $ScriptPath;
Start-Process -FilePath powershell.exe `
-Credential $Credential `
-ArgumentList $ArgumentList -Wait -NoNewWindow;
I can confirm that I get a UAC prompt, and the target script successfully executes.
Since you're concerned about the new session window closing, I'm guessing you want command line output.
Start-Process is working as intended. It will run the script passed in through -ArgumentList and exit the session. This means it will not hold to display command line output - the session will terminate immediately after the process completes.
If you want a persistent session, use New-PSSession. Otherwise, you could export the data you're gathering to a file.