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}"
Related
Meanwhile I've read and tried so many options and none of them worked for me.
I need to run a command on a remote machine that will install an application.
The setup.exe is an Oracle installer and is able to accept silent parameters.
"\\SVR1\Share\remote application Install\install\Setup.exe" -silent -force -nowait -waitforcompletion PACKAGE_NAME=abcde INSTALL_MODE=Typical ORACLE_HOME=C:\some_dir ORACLE_HOME_NAME=some_dir_Client1 APP_USER=itsmeagain APP_PASSWORD=surexxx
When I paste this command in a cmd it works as expected
When I put this in a ps1 script and run it, it works too:
cmd /c "\\SVR1\Share\remote application Install\install\Setup.exe" -silent -force -nowait -waitforcompletion PACKAGE_NAME=abcde INSTALL_MODE=Typical ORACLE_HOME=C:\some_dir ORACLE_HOME_NAME=some_dir_Client1 APP_USER=itsmeagain APP_PASSWORD=surexxx
However trying to run this 1 line script from a remote computer, it fails with: [Start-Process], InvalidOperationException
$svr="mach1"
$cmdFile="install.ps1"
$RemDir = "\\${svr}\C$\All_files\Scripts\"
$fn = "${RemDir}\${cmdFile}"
$password = ConvertTo-SecureString "${pazwd}" -AsPlainText -Force
# can't change the remote dir without spaces
"cmd /c `"\\SVR1\Share\remote application Install\install\Setup.exe`" -silent -force -nowait -waitforcompletion PACKAGE_NAME=abcde INSTALL_MODE=Typical ORACLE_HOME=C:\some_dir ORACLE_HOME_NAME=some_dir_Client1 APP_USER=itsmeagain APP_PASSWORD=surexxx " | Out-File -FilePath $fn
$cred = New-Object System.Management.Automation.PSCredential($user,$password)
$sb = { Start-Process -FilePath "${LocalDir}\${cmdFile}" }
Invoke-Command -ComputerName $svr -Credential $cred -ScriptBlock $sb
Suggestions? what Am I doing wrong here?
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!
I am writing a script to deploy through group policy. The script deletes a number of registry settings to fix an issue we have on our build of Windows. The script needs to run as an administrator as the keys exist in hives that require admin rights to delete.
Because GP runs powershell scripts as the logged on user, I am looking at creating a wrapper which will read an encrypted password for the local user account and then run the script with it.
My script is able to read the credential, but I am getting errors when running the start-process command. If I try and reference the script it will give the error that the path doesn't exist, even though you can dump the contents using cat .
I then tried reading it into a variable and running powershell with the -command argument. If I do this I get an error.
"Start-Process : This command cannot be run due to the error: The parameter is incorrect"
I understand that I need to enclose the code in braces, but I am not sure how this is done as concatenating them to the string doesn't work.
if($connected) {
$Encrypted = Get-Content <PATH TO PASSWORD FILE>
$pass = ConvertTo-SecureString -String $Encrypted -Key (1..16)
$user = <MY ADMIN ACCOUNT>
$Credential = New-Object System.Management.Automation.PSCredential $user, $pass
echo $(pwd)
echo $(cat <PATH TO SCRIPT>)
$code = $( cat <PATH TO SCRIPT> )
#Invoke-Command -ScriptBlock {$code} -Credential $Credential
#Start-Process powershell.exe <PATH TO SCRIPT> -Credential $Credential
Start-Process powershell.exe -ArgumentList "-command $code" -Credential $Credential
}
I just need a way of executing the code in my second script, but I can't work out how to do this as it's not behaving as expected. Sorry, as I am sure I am missing something obvious.
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"
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.