'Azure Pipelines: Start-Process with credentials not working

I am trying to start an application from Azure Pipelines YAML using Powershell.

I want the app to start with a non-administrator account, while the Azure Pipelines deployment agent uses an administrator account.

To do this, I am using a Powershell task running in a deployment job that calls Start-Process with -Credentials:

- task: PowerShell@2
  displayName: 'Start application'
  inputs:
    targetType: 'inline'
    script: |   
        $user = "myOrdinaryUser"
        $PWord = ConvertTo-SecureString -String "myPassword" -AsPlainText -Force

        $credentials = New-Object -TypeName System.Management.Automation.PSCredential ($user, $PWord)

        $process = Start-Process -FilePath "C:\Windows\notepad.exe" -PassThru -Credential $credentials -WorkingDirectory 'C:\Windows' -RedirectStandardOutput myOutputLogFile -RedirectStandardError myErrorLogFile
        

         Write-Host "Process ExitCode: " $process.ExitCode
         Write-Host "Process id: " $process.Id
         Write-Host "Process name: " $process.Name
         Write-Host "HasExited: " $process.HasExited
         Write-Host "StartTime: " $process.StartTime
         Write-Host "ExitTime: " $process.ExitTime

But it does not work.

Output:

Process ExitCode:

Process id: 11408

Process name:

HasExited: True

StartTime:

ExitTime:

Both the output log files get created, but contain nothing.

In Event Viewer, under Windows Logs -> System, there is the message

Source: Application Popup

notepad.exe - Application Error

The application was unable to start correctly (0xc0000142). Click OK to close the application.

If I do the same without credentials, it works. However, the app closes when the job finishes. Apparently, this is by design: https://developercommunity.visualstudio.com/t/starting-a-process-from-azure-deployment-agent-tas/1038946

$process = Start-Process -FilePath "C:\Windows\notepad.exe" -PassThru

Output:

Process ExitCode:

Process id: 10024

Process name: notepad

HasExited: False

StartTime: 19-04-2022 16:23:52

ExitTime:

Also, If I run the PS script in a Powershell prompt it works with credentials.

How can I get more information about why the process does not start and how do I fix it?



Solution 1:[1]

I solved this with the following workarounds:

1. Created a Windows Task with an event log trigger that runs the app under the correct user account.

Then, replaced Start-Process with this Powershell command:

Write-EventLog -LogName "Application" -Source "MySource" -EventID 999 -Message "Start application"

Installed a build agent instead of a deployment/resource agent. Configured to run in Interactive mode.

Start-Process works using -Credential in this mode.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1