different behaviour of azure devops agents on hosted vm when different computer access the vm - excel

Edit : After a lots of testing, we managed to find a comon point between the machines which, when connected using RDP to our environment, breaked the excecution of excel funtionnalities called from a powershell script launched by an azure devops agent : All these machines have a touchscreen, machines without a touchscreen do not break it (tryed with 3 machines with touchscreen, different contructors and 4 machines without touchscreen)
Edit 2: When the touchscreen is disabled being connected to the machine with RDP do not break the script anymore
I'm using AzureDevops agents to execute a powershell task on a Cloud Hosted environment, the task is very simple it justs creates a workbook and saves it:
try{
write-host 'initalized excel'
$Excel = New-Object -ComObject Excel.Application
write-host 'adding WB'
$Workbook = $Excel.Workbooks.Add()
write-host 'Saving Wb'
$Workbook.SaveAs('C:\test\test.xlsx')
}
finally{
write-host 'quitting excel'
$Excel.quit()
}
Here's the output of the devops Task :
##[section]Starting: PowerShell Script
==============================================================================
Task : PowerShell
Description : Run a PowerShell script on Linux, macOS, or Windows
Version : 2.151.2
Author : Microsoft Corporation
Help : https://learn.microsoft.com/azure/devops/pipelines/tasks/utility/powershell
==============================================================================
Generating script.
========================== Starting Command Output ===========================
##[command]"C:\windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'C:\agent\_work\_temp\33ed6d09-53ba-427a-a7ac-ea425a98767c.ps1'"
initalized excel
adding WB
quitting excel
Exception from HRESULT: 0x800A03EC
At C:\agent\_work\_temp\33ed6d09-53ba-427a-a7ac-ea425a98767c.ps1:6 char:5
+ $Workbook = $Excel.Workbooks.Add()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (:) [], COMException
+ FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
This is what happens when my colleague is connected to the virtual machine on which the agent executes the script. My colleague is connected with the windows remote desktop tool.
When I'm the one connected on the VM using RDP it works fine :
##[section]Starting: PowerShell Script
==============================================================================
Task : PowerShell
Description : Run a PowerShell script on Linux, macOS, or Windows
Version : 2.151.2
Author : Microsoft Corporation
Help : https://learn.microsoft.com/azure/devops/pipelines/tasks/utility/powershell
==============================================================================
Generating script.
========================== Starting Command Output ===========================
##[command]"C:\windows\System32\WindowsPowerShell\v1.0\powershell.exe" -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Unrestricted -Command ". 'C:\agent\_work\_temp\436b2d56-2a41-4f75-97bb-01d4c41407e6.ps1'"
initalized excel
adding WB
Saving Wb
quitting excel
##[section]Finishing: PowerShell Script
My colleage and I RDP to the virtual machine with the same exact user.
We tried on another virtual machine with another devops agent, the same issue arise.
I'm a bit lost and I dont know how to troubleshoot this issue at all, also if you have any other suggestion for the title I'll take every piece of advice.
Edit:
We also tried to put this script in a loop and write if it succeed or fail, when I rdp to the virtual machine, it works, if I disconnect it works, as soon as my colleague RDP into the virtual machine it starts failing, if I reconnect (thus disconnecting my colleague) it works again. (We RDP with the same user)
Edit2 :
I'm receiving an edit suggestion from someone who noticed me that :
From the user's comment->' when the agent is already running and
creating excel files in a loop, the simple fact my colleague rdp to
the vm breaks the excel file creation.' This issue seems to have
nothing to do with azure devops. The reason for the problem is due to
rdp
Well it's an azure devops agent problem as well since simply running the script manually works for both of us. It's a RDP issue that cause the Devops agent to be unable to use some of the excel-powershell functions, so I think the Azure Devops tag is still accurate
Edit :
In the finally block try outputting the full error stack with: $Error
| Format-List -Force – HAL9256
Here's the error :
Exception : System.Runtime.InteropServices.COMException (0x800706BE): The remote procedure call failed.
(Exception from HRESULT: 0x800706BE)
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode,
IntPtr errorInfo)
at System.Management.Automation.ComInterop.ComRuntimeHelpers.CheckThrowException(Int32
hresult, ExcepInfo& excepInfo, ComMethodDesc method, Object[] args, UInt32 argErr)
at CallSite.Target(Closure , CallSite , ComObject )
at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
at CallSite.Target(Closure , CallSite , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
at System.Management.Automation.Interpreter.DynamicInstruction`2.Run(InterpretedFrame frame)
at
System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame
frame)
TargetObject :
CategoryInfo : OperationStopped: (:) [], COMException
FullyQualifiedErrorId : System.Runtime.InteropServices.COMException
ErrorDetails :
InvocationInfo : System.Management.Automation.InvocationInfo
ScriptStackTrace : at <ScriptBlock>, C:\agent\_work\_temp\fae3ef7a-700d-49c1-8f1f-7f7d2bc0d49e.ps1: line 8
at <ScriptBlock>, <No file>: line 1
PipelineIterationInfo : {}
PSMessageDetails :

Running Excel under an automated, unattended process (such as an Azure DevOps Agent) in unsupported and can lead to all kinds issues, like the ones you are running into.
The official recommendation is to rely on a 3rd party component like Excel Package Plus (free), NPOI (free), SpreadSheetGear (Commercial) or Aspose Cells.NET (Commercial). Or to use System.IO.Packaging and edit the XML for the Office document directly. These do not depend on having Excel installed on your server, are actually supported and don't have all kinds of license issues associated with them. Migrating your scrips over to these other package types is often not very hard, since they take a very similar API for portability.
Besides the technical issues you're running into, the licensing may be even hairier, as Office isn't allowed to be automated 'on behalf of other users' and generally isn't allowed to run on a server.
Besides the technical problems, you must also consider licensing issues. Current licensing guidelines prevent Office applications from being used on a server to service client requests, unless those clients themselves have licensed copies of Office. Using server-side Automation to provide Office functionality to unlicensed workstations is not covered by the End User License Agreement (EULA).
https://support.microsoft.com/en-us/help/257757/considerations-for-server-side-automation-of-office
You may be able to solve some of the issues, like the one you are experiencing now, but you're likely going to run into new ones. Running the Azure DevOps agent interactively may help, that way Excel will be launched in the interactive session as well, instead of a protected hidden user session with no real desktop. What's likely happening, is that the second user connecting over RDP is closing all other sessions when they log on, or locking all sessions as they log off.
here are security risks when you enable automatic logon or disable the screen saver because you enable other users to walk up to the computer and use the account that automatically logs on. If you configure the agent to run in this way, you must ensure the computer is physically protected; for example, located in a secure facility. If you use Remote Desktop to access the computer on which an agent is running with auto-logon, simply closing the Remote Desktop causes the computer to be locked and any UI tests that run on this agent may fail. To avoid this, use the tscon command to disconnect from Remote Desktop. For example:
%windir%\System32\tscon.exe 1 /dest:console
https://learn.microsoft.com/en-us/azure/devops/pipelines/agents/agents?view=azure-devops#interactive-or-service
Another problem concerning excel automation on a server, is that existing Excel instances are re-used. This may cause the host excel to run under different credentials than the process doing the automation.
To run the agent interactively configure the serves to auto-logon (this utility encrypts the credentials used) and add run.cmd in the agent folder to the start-up executable list (either in the registry or a shortcut in the start menu). You can also make the agent executable (c:\windows\system32\cmd.exe /c path\to\agent\run.cmd) the default shell. There are quite a few docs on setting a custom shell.
You'll need to disable the screensaver and lockscreen for this session as well, which well require you to physically secure the server, otherwise anyone with access to the servers console will be able to access the running interactive session.
And you must unsure you always disconnect the remote desktop session without locking it (like above).

We finally identified that the problem only happened when using the RDP from a laptop having a touchscreen.
We then disabled the touchscreen using this documentation :
In the search box on the taskbar, type Device Manager, then select
Device Manager.
Select the arrow next to Human Interface Devices and
then select HID-compliant touch screen. (There may be more than one
listed.)
Select the Action tab at the top of the window.
Select Disable device or Enable device, and then confirm. If there's more
than one HID-compliant touchscreen device listed, perform steps 2–3
for that one too.
https://support.microsoft.com/en-us/help/4028019/windows-enable-and-disable-your-touchscreen-in-windows-10
And the script stopped crashing.
If someone want to post an answer to solve this problem without disabling touchscreen by tweaking the parameters in RDP or in the server we RDP to, i'd accept his answer as it's easier to change the parameter once than to ask people to disable their touchscreen when they rdp to our machine.

Related

Open Excel File on Azure VM with Powershell Script Sent from Local Computer

Can someone show how I can open an Excel document and show it visually on an Azure virtual machine using a Powershell script sent from my local machine? I have already figured out how to run Powershell script on the VM through the AzureVM module but am running into the issue of Windows not allowing remote Powershell users to interact with a user interface. Notes:
I have tried PSEXEC with no luck. This may be the way to go, but I have had no luck getting it to actually work.
I am not smart, so please use the most dumbed-down terminology as possible.
My end goal is exactly that stated above - nothing more nothing less.
Riches and honor to the one who can solve this.

Notes cannot create automation object

I have created an agent iin which I call a dll file so that I can get data from another system eventually..
When I manually run this agent then the call to the dll file works and I get data from it.
When I call this agent from a browser then I get:
Error Description : Cannot create automation object
The security of the agent is on 3.Allow restricted operations with full administration rights.
Any idea why I get Cannot create automation object when running agent from browser?
When you start the agent from browser then the agent runs on Domino server.
So, you need to install automation object's software on this server.
When you manually run the agent then the code is executed on your client. This works because you installed the software necessary for creating the automation object on your client.
I found the same error but in my case everything was working properly until we restored a backup of Windows. The issue was caused because Office had to be reactivated again.
Sometimes this happens too because a corruption of the Word document, so you have to rebuild it.
I hope this could be helpful in future to other people

Connect to multiple remote machines to run automation scripts

I am an automation engineer where I need to run 450 CodedUI scripts on multiple machines. I have 15 machines on which I run these scripts.
To resolve my trouble I am using Microsoft's tool Remote Desktop Connection Manager to login to these machines. But I am getting the error on failed scripts that "Either the window is locked or minimized", but when I used to directly login to these machines and run the scripts there were no such issues.
I am unable to find any resolution. I tried one more tool to connect to 15 machines , i.e. AppVision tool as well. Even with that tool I am facing the errors on all my scripts that Some control is blocking the control to be clicked in.
I need to know if I can have any other tool or way where I would be able to login to the machines in one go and run automation scripts without any errors.
Any help is appreciated.
Thanks in adavance.
Coded UI requires that the screen saver is disabled on the remote machines.
Coded UI interacts with the desktop of the machine running the tests. When the screen saver is active it controls the desktop and, effectively, prevents Coded UI from interacting with the application under test.
The question refers to "Microsoft's tool Remote Desktop Connection Manager" so perhaps you are not using test agent software to run the test. Check this Microsoft web page and this Microsoft forum question for more details on how to set up remote computers to run Coded UI.

powershell IQY dump script fails

I'm currently working on automating a powershell script to make a dump of a small DB.
The database is accessible through a company Sharepoint and I am leveraging an IQY file exported from said Sharepoint to read the database contents.
When I run the script manually (i.e. calling it from the command line), it works with no issues, but when I try and start the script from Task Scheduler, the following exception is raised:
System.Reflection.TargetInvocationException
the line that is generating the exception is:
$iqy = $xl.Workbooks.Open($query, 2, $true)
Where $xl is a new Excel.Application ComObject, created correctly and $query is a string containing the full file path of the iqy file.
As for my configuration, I'm trying to run my script on a Windows Server 2008R2, using a local administrator user (same user that is supposed to launch the scheduled script), which is also authorized to access the Sharepoint. I'm running Powershell 3.0. I'm not loading any Sharepoint-related snapins.
The only answers I found poking around hinted at granting "Trust" to the IQY file location and the Sharepoint itself in Excel. That did not help.
The Exception also seems to point at a sharepoint issue, but since the script runs fine when started manually, I cannot understand how it could be anything to do with Sharepoint.
Am I missing some intricacy of the Task Scheduler?
Any help would be greatly appreciated.
Never mind, I seem to have found an answer.
If anyone is encountering the same issue, it appear the Excel Com Object has a bug that does not allow it to run from the Task Scheduler if you set it to run regardless of whether the user is logged in.
To circumvent that create the following 2 folders on the machine where the script is supposed to run:
(32Bit, always)
C:\Windows\System32\config\systemprofile\Dektop
(64Bit)
C:\Windows\SysWOW64\config\systemprofile\Desktop
After creating the folders, it worked as expected.
Source: http://social.technet.microsoft.com/Forums/windowsserver/en-US/aede572b-4c1f-4729-bc9d-899fed5fad02/run-powershell-script-as-scheduled-task-that-uses-excel-com-object?forum=winserverpowershell

Forced using the PSSessionOption -NoMachineProfile BUT SPFarm.Local is null

I am currently writing a Powershell module to provide functions for installing / operating SharePoint 2007.
One of my scripts checks the health of SharePoint servers farm.
So I use Remote Powershell : using New-PSSession.
In my Virtualized test farm (Windows server 2003, same domain, same admin...), the New-PSSession cmdlet failed :
After googling it, the only solution I saw was to use the NoMachineProfile option :
That solved my problem.
Now the problem :
I need to use SharePoint object : SPFarm.Local (on all servers)
[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
[Microsoft.SharePoint.Administration.SPFarm]::Local
This code works locally (on all servers)
But when I run it remotely (using the NoMachineProfile option), SPFarm.Local is null !
I Suppose (I cannot check it) it is because SharePoint uses some registry values that are not loaded because of the NoMachineProfile option.
So :
1 - Do you think SPFarm.Local is null because of the NoMachineProfile option ?
2 - Do you know how can I solve the first problem without using the -NoMachineProfile option ?
Thx a lot !
I believe your problem is related to the PowerShell Multi-Hop (Diagram below of what a multi-hop operation is) issue Which was discussed here... PowerShell is not able to perform a multi-hop operation by default, because your credential are not being passed to the next server... Since you are trying to contact different SP servers in the farm from a remote host. I would recommend reading the following blog entry related to multi-hop scenarios and following his instructions to correct your issue.
Using CredSSP for multi-hop authentication
http://www.ravichaganti.com/blog/?p=1230
I know this diagram mentions file server but it’s the same basic principle.

Resources