PowerShell Script fails to execute batch file on Remote server - powershell

I have a PowerShell script which works fine on windows server 2016 azure VM but fails to execute the same script from my build agent which is also window server 2016 OS azure VM.
No errors get logged in PowerShell due to which i am not able to figure out what is the reasons?
Is there any Prerequisites that i need to validate or install on the server for executing this script?
Below is the script which execute batch file present on another another VM.
$Username = 'ABC'
$Password = 'XYZ'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass
try {
Invoke-Command -ComputerName "ServerName" -credential $cred -ErrorAction Stop -ScriptBlock {Invoke-Expression -Command:"cmd.exe /c 'C:\CI\Demo_CI.bat'"
Write-Host "done"
}
} catch {
Write-Host "error"
}

I believe what you are facing here is a Credential delegation issue, You can try enabling CredSSP in your build agent and the target "ServerName". To know more about credssp , see here, therwise you will have to use psexec in CI.

Related

Running powershell script fails on windows server salve

I have the below code which runs from Jenkins on windows server 2019 slave:
$Username = $args[0]
$Password = $args[1]
$Env = $args[2]
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass
echo "******** Start SQL Deploy ********"
Start-Process -FilePath msbuild -ArgumentList '"Database Services\Database Services.sqlproj"','/t:deploy', '/p:Configuration=Release', '/p:TargetConnectionString=$Env', '/p:BlockOnPossibleDataLoss=True', '/p:TargetDatabase="test_fsdb"','-fl','-flp:logfile=msbuild.log' -wait -LoadUserProfile -credential $cred
Get-Content msbuild.log
echo "******** End SQL Deploy ********"
The parameters comes form Jenkinsfile. I'm using applicative user.
The error is:
Start-Process : This command cannot be run due to the error: The service cannot be started, either because it is
disabled or because it has no enabled devices associated with it.
I was able to run it locally, so I wonder if it's kind of permission issue on the salve...

PowerShell Computer StartUp-Script - Switch user-context?

Through Microsoft Group Policy I did define to run a Powershell-Script on Computer Start-Up. Also I have the requirement to run a Powershell-Script as Scheduled Task without saving credentials.
On both scenarios I have the same problem ...
I want to run a Citrix Powershell-Command (PSSnapIn) like:
Set-BrokerMachine -MachineName "domain.local\$env:COMPUTERNAME" -AdminAddress "RemoteServer.domain.local" -InMaintenanceMode $True
Manual: https://citrix.github.io/delivery-controller-sdk/Broker/Set-BrokerMachine/
Of course only users who have the permission could run those Citrix-commands. I would be able to give a domain-user the permission to run the command "Set-BrokerMachine", but in the mentioned scenarios the PowerShell-scripts run in context of the system-user.
I did simulate the system-user by PSExec:
Error running as System-User
My scripts do other things of course and I want to keep them running as System-User, but now I am looking for a clean solution to get those Citrix-commands running.
If possible, I don't want to save credentials in my scripts.
EDIT #1:
I would be able to workaround with the following code:
$Username = "MySpecialUser"
$Password = 'MyPassword'
$SecurePassword = ConvertTo-SecureString $Password -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential $Username, $SecurePassword
$Result = Invoke-Command -Session ( New-PSSession -ComputerName "RemoteServer.domain.local" -Credential $Credential ) -ScriptBlock {
Add-PSSnapin Citrix*
Set-BrokerMachine -MachineName "domain.local\$args" -InMaintenanceMode $True
} -ArgumentList $env:COMPUTERNAME -HideComputerName
Remove-PSSession -InstanceId $Result.RunspaceId
I don't like this because:
The code has to contain credentials (ofc I could encrypt it ...)
I have to create a permission-system for this special user in Citrix
I have to put the special-user into a local-group on every server, to allow the remote-administration (security-risk)
I don't like to use PSSession
...
Is there a better/cleaner solution? Any ideas?

PowerShell Remote script exiting, but not exiting parent script

Below is a script we are using in TeamCity. We are sporadically getting a hung build during this step and some others similarly written. From what I've been able to find out is that the error is occurring between the two servers.
The script creates a remote session and executes on the remote machine. The remote script completes successfully, but never causes this script to exit which leads to a build step hanging.
$username = '%SvcAcct%'
$password = '%SvcAcctPwd%'
$credentials = New-Object System.Management.Automation.PSCredential `
-ArgumentList #($username,(ConvertTo-SecureString -String $password -AsPlainText -Force))
$remoteSession = New-PSSession -ComputerName %RemoteServer% -Authentication Credssp -Credential $credentials
Invoke-Command -FilePath %teamcity.build.checkoutDir%\NovoDeploy\Powershell\InstallNovo.ps1 `
-ArgumentList "C:\NovoDeploy\Installers","C:\NovoDeploy\%InstallSettingsConfigFileName%","%SvcAcctPwd%" -Session $remoteSession
#Get the exit code from the remote session so
#we can pass it through to TeamCity and fail the build.
$remoteSessionExitCode = Invoke-Command { $lastexitcode } -Session $remoteSession
exit $remoteSessionExitCode
Try using remove-pssession -$remoteSession at the end of your script.
Remove-PSSessioncloses one or more Windows PowerShell sessions (PSSessions). I'm thinking maybe your exit command is just exiting the remote powershell session you use to run the remote command and then continuing as a local powershell session after your exit. If you add remove-pssession after you assign the exitcode variable, then maybe your exitcommand will exit the local terminal as needed.
Just a theory but it's worth testing out.

Powershell - Running remote session on intended server

So I have a server set up for remoting called "Server01" so I can use the PS2 configuration.
Problem is I want to run the ISE as PS2 on the same machine.
So I am trying:
$username = "Domain\User"
$password = "Password"
$cred = new-object -typename System.Management.Automation.PSCredential -ArgumentList $username, $password
$s=new-PSsession "Server01" -authentication Credssp -credential $cred -ConfigurationName PS2
Invoke-Command -Session $s -ScriptBlock {
}
Remove-PSSession $s
while on "Server01" and I am getting an access denied error. I have made sure "Allow Delegating Fresh Credentials" is enabled and configured properly.
I am trying to avoid running this through the Management Shell because I would like to have a scheduled task kick off this script automatically.
Any suggestions/ideas?
You don't have to use session configurations to invoke PowerShell with version 2.0 in a scheduled task.
Just use:
powershell.exe -Version 2.0
In your task definition. This is way easier and safer than trying to remote into the local machine with CredSSP.

Need to connect to remote server and execute ps1 script using jenkins

I created a Jenkins job that needs to connect to a remote machine and execute a ps1 script.
$pw = convertto-securestring -AsPlainText -Force -String "4444"
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "eeeee\eee",$pw
$sess = New-PSSession -ComputerName server1 -Credential $cred
Enter-PSSession $sess
Looks like you may be better served with Invoke-Command than Enter-PSSession.
https://technet.microsoft.com/en-us/library/hh849719.aspx
Something along the lines of:
Invoke-Command -Credential $creds -ComputerName $server -FilePath $scriptname -ArgumentList $arg1, $arg2
Add the remote machine as a slave, then run your script from 'execute windows Batch command' or install Powershell plugin and 'Run powershell script'.
Links:
Add windows slave: https://wiki.jenkins.io/display/JENKINS/Step+by+step+guide+to+set+up+master+and+agent+machines+on+Windows
Powershell plugin: https://wiki.jenkins-ci.org/display/JENKINS/PowerShell+Plugin