Azure pipeline remote powershell task hanging - azure-devops

I try the "run powershell on remote machines" task to restart my Tomcat (java) service on the Windows server.
It just keep printing useless info in the console (target machine name)
Here is the detail about the powershell script:
stop Tomcat service (call a .bat file)
move .jar files to right location & replace old files
start Tomcat service (call a .bat file)
& D:\MY\PATH\stop.bat;
......
Copy-Item -Path "D:/s-1.0.jar" -Destination $sqs_path -Force;
......
& D:\MY\PATH\start.bat;
When I run the same command directly in target windows server, the "powershell part" trigger .bat script job, then get back to powershell console successfully .
Later, a new window pops out. The new window is Tomcat server that shows logs of my service.
However, when I do the same job with Azure release pipeline, the Tomcat window did not show up in target machine.
And release job console keep hanging (just print the name of targer machine).
I guess somewhat the output of popout window has be redirected to the console in release pipeline.
In addition, if I cancel the release job. my Tomcat service still working. (just without console to debug)
Or, another thought, can I achieve my goal with other 'task' in release pipeline? (powershell is not a "must")
Any suggestion would be appreciated.
[Update1]
I change the service start commamd to run the .bat in another window.
& D:\MY\PATH\stop.bat;
......
Copy-Item -Path "D:/s-1.0.jar" -Destination $sqs_path -Force;
......
Start-Process cmd.exe -ArgumentList "/C D:\sources\SQS.Dev\start.bat;"
And it turns out "nothing happens" ...
The remote powershell task finish immediately.

The PowerShell on Target Machines task uses WinRM to connect and access the remote target machine.
Normally, WinRM requires the agent machine and the remote target machine have been joined into the same domain or workgroup.
Please check with the following things:
Ensure the agent machine and the remote target machine have been joined into the same domain or workgroup.
Ensure you have followed the steps here to configure the WinRM.
If you have configured the WinRM. Login to the agent machine, ensure you can connect and access the remote target machine when you manually try to call the remote PowerShell. You can try with the following script on the agent machine to test if the WinRM can work well to connect and access the remote target machine.
Param(
# The IP address or FQDN of the remote machine
[string]$computerIp = "{computerIp}"
)
# Username and Password of the admin account on the remote machine
$Username = "{Username}"
$Password = ConvertTo-SecureString "{Password}" -AsPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($Username,$password)
# Call the remote PowerShell script
Invoke-Command -ComputerName $computerIp -Credential $cred -ErrorAction Stop -ScriptBlock {Invoke-Expression -Command:"powershell.exe /c '{absolute path of the remote PowerShell script}'"}
If it does not work when you try manually calling the remote PowerShell script on the agent machine, the task in the pipeline of course is not able to work. The issue should be on the WinRM, maybe, the WinRM is not configured well.
If it work well when you manually try on the the agent machine, the issue should be on the self-hosted agent. Try to set up a new self-hosted agent with the admin account to see if it can work.
[UPDATE]
As I mentioned above, please try manually calling the remote PowerShell script on the agent machine to see if the commands for 'start Tomcat service' can work.
The PowerShell on Target Machines task is running on the agent machine. If the remote PowerShell script cannot work as expected when you manually try it on the agent machine, it is of course not able to work on the task in pipeline.
At this time, the possible reason of the issue could be the following:
The connection between the machines has some problems.
The PowerShell script has some issues. Maybe you missed some settings for remoting call the script.

Related

Starting Service on remote server failed

I encounter strange behavior when trying to remotely start a service.
on Server A i'm running this line (it's part of bigger script named RunRemoteService.ps1):
Invoke-Command -ComputerName $B_comp -ScriptBlock {Powershell.exe -File "run_service.ps1"} -Credential $cred
And the script run_service.ps1 contains the following line (it's also part of bigger script):
$my_service_name.Start()
Now here's the strange thing, If I run RunRemoteService.ps1 when I have an open remote connection (mstsc) to server B then the script works perfectly and the required service on B is really starting.
However, if I run RunRemoteService.ps1 when there is no mstsc connection with server B then the script failed (service doesn't start).
Why is this happening and how can it be resolved?
EDIT: I explored this issue a bit more and found out that this occurs only when trying to run my specific service.
that means that my service must run from a session of already logged on user (that is why it's working if I mstsc to the server before).
So I guess my new question is - is there a way I can login to remote machine from powershell?
Thanks.
If you cannot use Credential delegation as suggested by #EBGreen. Try using psexec.exe for calling the script instead of PowerShell remoting.
psexec \\server "cmd /c powershell.exe -f c:\script.ps1"
Get psexec from sysinternals.com
Ok, so my question had evolved and modified on the fly so this solution is to the latest issue I had which is - I couldn't remotely start my service if no user is logged on to remote machine.
The solution is a workaround:
I configured auto-login (using sysinternals auto-login tool) on remote server.
I used Restart-Computer cmdlet at the beginning of the test.
Now after the restart is complete and ps-session is restored, user is logged in automatically to server and I can remotely start my service.
Thanks.

Running a script off local machine to remote using Invoke-Command

Here is the command I am trying to run
Invoke-Command -ComputerName DOG-02 C:\Users\user\Documents\PowerShell\PowerShellmenuz.ps1
I want to be able to run the script PowerShellmenuz.ps1 on a remote machine. I am very close but am stuck at this point.
It is hard to tell where is the problem without error output, but probably you've missed first configuration step on remote machine. There things that should be done before executing scripts on remote machine.
Enabling PowerShell Remoting on the computer that you want access remotely. Open a PowerShell window as Administrator – right click the PowerShell shortcut and select "Run as Administrator". And execute the following command:
Enable-PSRemoting -Force - it will start service WinRM to allow incoming connections.

Running master script file on multiple remote servers without config changes

I have a master.bat file on Remote Server1 and I want to run it in parallel on 4 remote servers located on same network and having same username and password to login as Server1.
By googling i have explored following methods to do it but having some constraints in my case:
1.PsExec tool : psexec \\Server1 C:\master.bat ---- But I am not allowed to install PsExec tool for security reasons.
2.Powershell : Invoke-Command -ComputerName $client -ScriptBlock { cd C:\master.bat} -Credential $(Get-Credential) -Authentication CredSSP ----But I have to enable PS Remoting (WinRM) on every remote machine on whom I need to execute scripts using PowerShell, for which I am not allowed.
Is there any other way to run master.bat or master.ps1 on 4 remote servers??
And also if I am not mistaken....
1.Installing PsExec tool has security drawbacks...??
2.Enabling PS Remoting (WinRM) also has chances of security threats...??
One way to do this is to create scheduled tasks on the servers that you want to run the .bat file, and then use schtasks.exe to run the tasks on demand.
You can also set up WINRM to only provide a constrained PS session that can only be used to run that .bat file, using credentials stored in the session config to eliminate the need for credential delegation.
http://blogs.technet.com/b/heyscriptingguy/archive/2012/07/27/an-introduction-to-powershell-remoting-part-five-constrained-powershell-endpoints.aspx

Execute remote quiet MSI installs from Powershell

I am trying to use the Invoke-Command powershell cmdlet to install a MSI installer. From within powershell on the local machine and from the proper directory, the following works:
./setup /quiet
The following does not seem to work:
$script =
{
param($path)
cd "$path"
& ./setup /quiet
return pwd
}
return Invoke-Command -ComputerName $product.IPs -ScriptBlock $script -Args $sourcePath
For test purposes I am working on the local machine passing in "." for the -ComputerName argument. The paths have been verified correct before passing in to Invoke-Command, and errors generated on different versions of this code indicate the paths are correct. I have also tried with and without the "& " on the remote call to setup. Other Invoke-Command calls are working, so I doubt it is a permissions issue. I have verified that the return from the pwd call is the expected directory.
How do I get the install to work?
What error (if any) are you receiving? Unfortunately, you must run the shell as admin on your local machine to be able to connect to your local machine with invoke-command or any WINRM based command that requires administrative privilege (this is not a requirement when connecting remotely).
When connecting to loopback, I believe it is unable (for some security reason) to enumerate groups and determine if you are in an admin enabled AD or local group, which is how it auto elevates when invoking on a remote machine. The only solution may be to have a conditional which checks for localhost and if so, don't use the -ComputerName parameter.
This GitHub Issue covers it
You might try using Start-Process in your script block:
cd $path
start-process setup.exe -arg "/quiet"
Not sure if you will want or need to wait. Look at help for Start-Process.
I have had weird issues when trying to remotely execute a script on a local machine. In other words, remote powershell to the local machine. It comes back with an error that seems to say that PowerShell remoting is not enabled on the machine, but it was. I can run the script remotely from another machine to the target, but when using remoting to the same box, the issue crops up.
Verify that the WinRM service is running.
Verify powershell remoting has been enabled as in Enable-PSRemoting -force.
Verify your powershell execution policy is loose enough as in Set-ExecutionPolicy Unrestricted, for example. If the policy was set to RemoteSigned, this might be the problem.
You might also want to verify the user you are running the script as (locally, but using remoting) has privileges to "log on as a service" or as a batch job. Just guessing there, if the above list doesn't solve anything.

powershell v2 remote features?

Just listened to Hansellminutes podcast. He had a talk with two Microsoft PS developers. They mentioned PS V2 remoting features.
I have some scripts based on PS v1. In terms of remoting commands or executions, I installed PS on local and a remote machines. Then I use PsExec.exe to push bat on remote to execute PS scripts. Now I am thinking to take advantage of PS V2.
To simple questions I have, to get a list of files on local, I can use the following codes:
$fs = Get-Item -Path $Path | Where { !$_.PSIsContainer ... } # more constrains in ...
if ( $fs -ne $null )
{
# continue to work on each file in the collection
...
}
What is the equivalent command to get a collection of files from a remote? I prefer to get a similar collection of file objects back so that I can access to their properties.
The second question is how to exec a command on remote with external application? I tried to use WIM Process before, but I could not get WMI class working on a case of Windows 2008 server. Then I used PsExec.exe to push a bat to a remote to execute PS script. It works in the cases. However, the problem I have to install PS on the remote as well. I am going to working another remote. I'll try to avoid to install PS on the remote. Can I take PS V2 advantage to execute a command on a remote Windows? What's the new commands?
By the way, normally, I have to pass user name and pwd to a remote. I guess in PS I have to pass user/pwd as well.
You can either put your code above in a script file and invoke it on a remote computer using V2 remoting like so:
PS> Invoke-Command remotePCName -file c:\myscript.ps1
You will need to be running with admin privs (elevated if UAC enabled) in order to use remoting. The command above will copy the script to the remote machine, execute it and return deserialized objects. These objects are essentially property bags. They are not "live" objects and setting properties on them like IsReadOnly will not affect the remote file. If you want to set properties then do it in your script that executes on the remote PC.
The option if you have a little bit of script is to use a scriptblock like so:
PS> Invoke-Command remotePCName { Get-Item C:\*.txt | Where {$_.IsReadOnly }
You can execute native commands (EXE) on the remote computer in either script or a scriptblock. You only need to make sure the EXE is available on the remote PC.
Regarding credentials, if you're on a domain and you have admin privs on the remote computer you won't need to pass credentials as your default credentials should work. If you need to run as a specific user then use the -Credential parameter on Invoke-Command like so:
PS> $cred = Get-Credential
PS> icm remotePCName { gci c:\windows\system32 -r *.sys } -credential $cred
Regarding your last comment, no PowerShell will use Windows integrated security so you should not have to pass any username or password unless you wanted to run it as a different user.
If you haven't yet enabled PS remoting, every time I've tried I've had to actually turn off UAC while I was enabling remoting (then I could re-enable UAC once remoting was enabled). Running Enable-PSRemoting from an elevated command prompt was not enough and the error message was not at all useful.
EDIT: I've just confirmed in a fresh Windows 7 VM that this is not an issue. It could have been a beta issue that I am no longer experiencing as I've been using beta/rc/ctp of PowerShell and Windows 7 for a long time.