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
Related
Using this Powershell script I try to write and read a variable on VM from host.
$Username = 'administrator'
$Password = 'password'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$Cred = New-Object System.Management.Automation.PSCredential -ArgumentList $Username,$pass
#Added value to a variable on VM
Invoke-Command -VMName VM_Windows_2016 -Credential $Cred -ScriptBlock {$InstallPath="C:\Install\install-1.ps1"}
#Trying to read the variable on VM but with no result
Invoke-Command -VMName VM_Windows_2016 -Credential $Cred -ScriptBlock {Write-Host($InstallPath)}
As you see the result is empty. Can anyone help me to show how to write and read an variable on VM from host machine? Thanks!
When using Invoke-Command to run a command remotely, any variables in the command are evaluated on the remote computer. So when you run the first Invoke-Command you are only defining the variable $InstallPath and terminating the remote PS session. When you are run the Invoke-Command second time it create entirely new PS session, hence InstallPath would be null. Instead of this you can define and read the variable in a single Cmdlet like this.
$remoteScriptblock = {
$InstallPath = "C:\Install\install-1.ps1"
Write-Host($InstallPath)
}
Invoke-Command -VMName VM_Windows_2016 -Credential $Cred -ScriptBlock $remoteScriptblock
If you still want to run this in multiple Cmdlets you may consider Run a command in a persistent connection
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...
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.
I am familiar with Linux envs and using SSH to run remote scripts and programs and automatic scripts from my desktop.
I would like to have a similar workflow with Windows VMs that I have on my Azure Account. However, I canĀ“t find a straight forward instructions on how to build my local PowerShell scripts.
I need only to connect to a VM and call some scripts within it.
The best I could find would be this guide from MS
https://learn.microsoft.com/en-us/azure/virtual-machines/windows/winrm
Or this a litte older blog post.
http://fabriccontroller.net/using-remote-powershell-with-windows-azure-virtual-machines/
According to your description, we can use New-Pssession to execute script to stop/start service, like this:
$username = 'jason'
$pass = ConvertTo-SecureString -string 'password' -AsPlainText -Force
$cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $pass
$s = New-PSSession -ConnectionUri 'http://23.99.82.2:5985' -Credential $cred -SessionOption (New-PSSessionOption -SkipCACheck -SkipCNCheck -SkipRevocationCheck)
Invoke-Command -Session $s -ScriptBlock {Get-Process PowerShell}
Result like this:
Another way, we can use Azure custom script extension to run script, we can upload script to Azure storage account, and use Set-AzureRmVMCustomScriptExtension to set custom script:
PS C:\> Set-AzureRmVMCustomScriptExtension -ResourceGroupName "ResourceGroup11" -Location "Central US" -VMName "VirtualMachine07" -Name "ContosoTest" -TypeHandlerVersion "1.1" -StorageAccountName "Contoso" -StorageAccountKey <StorageKey> -FileName "ContosoScript.exe" -ContainerName "Scripts"
But custom script only can run one time, if you want to re-run this script, we should remove it with this command Remove-AzureRmVMCustomScriptExtension, then re-set it.
More information about Azure custom script extension, please refer to this link.
I ran into a lot of trouble using the accepted answer, and found I wanted to use SSL in my remote execution. I could not find anywhere this was succinctly put, so here's what worked for me. Essentially, use the built-in Azure command to enable remote PowerShell on the VM, and then run secure remote sessions to your heart's content!
Invoke-AzureRmVMRunCommand -ResourceGroupName $vmResourceGroupName -Name $vmName -CommandId 'EnableRemotePS'
$cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist $username, $secureStringPassword
$sessionOptions = New-PSSessionOption -SkipCACheck -SkipCNCheck
Invoke-Command -ComputerName $ipAddress -Credential $cred -UseSSL -SessionOption $sessionOptions -FilePath $scriptPath
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.