Running Azure CLI script in Azure DevOps Pipeline however unable to find the CLI script - azure-devops

param (
$ProjectFilePath= $(Buildin.SourcesDirectory)\TESTREPO7\RuleConfig.json
$ExecutableFilePath= $(Buildin.SourcesDirectory)\TESTREPO7\Studio.zip\Studio\UiPath.Studio.CommandLine.exe
$OutputFilePath= $(Buildin.SourcesDirectory)\$(Get-Date -Format 'yyyy-MM-dd-HH-mm-ss')-Workflow-Analysis.json
)
Write-Output "$(Get-Date -Format 'HH:mm:ss') - STARTED - Workflow Analyzer CLI Script"
$Command = "$ExecutableFilePath analyze -p $ProjectFilePath"
Invoke-Expression $Command | Out-File -FilePath $OutputFilePath
Write-Output "$(Get-Date -Format 'HH:mm:ss') - COMPLETED - Workflow Analyzer CLI Script"
XXXXXXXXXXXXXXXXXXXXXXXXXXXX
Error:
##[section]Starting: Azure CLI UiPathWorkFlow
==============================================================================
Task : Azure CLI
Description : Run Azure CLI commands against an Azure subscription in a Shell script when running on Linux agent or Batch script when running on Windows agent.
Version : 1.152.1
Author : Microsoft Corporation
Help : https://learn.microsoft.com/azure/devops/pipelines/tasks/deploy/azure-cli
==============================================================================
##[error]Script failed with error: Error: Unable to locate executable file: 'C:\agent1\_work\362\s\TESTREPO7\UiPathAnalyze.ps1'. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.
##[section]Finishing: Azure CLI UiPathWorkFlow
XXXXXXXXXXXXXXXXXXXX
Very important- When on a local computer, uiath.studio.commandline.exe (workflow analyzer) has rules stored in User directory (%LocalAppData%\UiPath\Rules = C:\Users\User1\AppData\Local\UiPath\Rules). How would I be able to input this information in the script provided above??
Azure CLI latest version installed on azure DevOps agent server.
Tried adding environment parameter but not sure what to enter but this error occurred anyways. Added Environment made did not fix the error.
added both below environmentals—
PATH $(Buildin.SourcesDirectory)\TESTREPO7\UipathAnalyze.ps1
Build.SourcesDirectory $(Buildin.SourcesDirectory)\TESTREPO7\UipathAnalyze.ps1

Check this doc predefined variables, the path should be $(Build.SourcesDirectory) instead of $(Buildin.SourcesDirectory)
The error message is: Unable to locate executable file: 'C:\agent1\_work\362\s\TESTREPO7\UiPathAnalyze.ps1'
The UipathAnalyze.ps1 is the code you shared and it it the Script Path in the task Azure CLI, right? We need open the folder path C:\agent1\_work\362\s\TESTREPO7 to check if the file exists.
In addition, could you successfully run the .ps1 file on the local agent machine?

Related

The Azure CLI task on my classic pipeline shows an error using inlinescript

I use the Azure CLI task on my Azure classic pipeline (no YAML). The pipeline works appropriately, the only problem is that this task shows an error. I use this inline script for the task:
$containers = $(call az storage container list --connection-string '...') | ConvertFrom-Json -Depth 5
$containers | where{$_.name -like "..."}
$lastContainers = $containers | Select-Object -Last 5
$containers.ForEach({ If ($_ -notin $lastContainers) {call az storage container delete --name $_.name --connection-string '...' } });
I replaced my real connection string with .... I get this error about the last task (Azure CLI) when I run the pipeline (all of the previous steps end successfully):
D:\a\9\s>$containers = $(call az storage container list --connection-string '...') | ConvertFrom-Json -Depth 5
'$containers' is not recognized as an internal or external command, operable program or batch file.
##[error]Script failed with error: Error: The process 'D:\a\_temp\azureclitaskscript1587632019088.bat' failed with exit code 255
I have a similar YAML pipeline that uses this same script and everything works just fine. I use call in front of Azure commands as suggested on GitHub.
In AzureCLI#2 you select script type:
Type of script: PowerShell/PowerShell Core/Bat/Shell script. Select
bash/pscore script when running on Linux agent or batch/ps/pscore
script when running on Windows agent. PowerShell Core script can run
on cross-platform agents (Linux, macOS, or Windows)
Additionally there may appear some differences in Linux and Windows (this issue with call statement), but if you select there pscore for instance you should get rid of 'call` statement.
So please provide more info in what system and terminal you run this script to give you more help.
I ran you script without call in powershell and all was fine. Please try run it in that way.

How to use SharePointPnpPowerShellOnline PowerShell module in Azure DevOps?

I am failing to use the SharePointPnpPowerShellOnline PS Module as part of my release pipeline.
We are using Azure DevOps with a hosted build agent on a Azure VM. I want to accomplish uploading build artifacts into Microsoft Teams/Sharepoint.
I installed SharePointPnpPowerShellOnline on the server (under the account that the DevOps build agent operates with), yet the build agent fails to execute the script on the first line that uses said module (a call to Connect-PnPOnline -Url https://... -Credentials ...). Error message: "Connect-PnPOnline : The term 'Connect-PnPOnline' is not recognized as the name of a cmdlet, function, script file". So it behaves as if the module is not installed at all.
yet when I log onto the server (with the correct account), the module is found and I can execute Connect-PnPOnline succesfully.
the used Azure DevOps pipeline task is "PowerShell".
Shouldn't the build agent be able to find the installed module, as I installed it for its user?
Edit: I did some more "debugging", namely:
logging the Username the script is running under by [Environment]::UserName, to make sure I installed the module for the right user. result: matches the expected user.
Listing the installed modules by Get-InstalledModule in my script. Once it is executed in the Release pipeline by the agent it yields an empty list. yet executing the same script on the VM (via RemoteDesktop) yields the installed modules
My guess is I'm doing a stupid beginner mistake because I haven't that much experience with PowerShell...
Answering my own question: In the end I just installed the Module again as part of the script by prepending the following two lines. Of course I'd be happy if somebody could explain why it didn't work the other way...
Install-PackageProvider Nuget -ForceBootstrap -Force
Install-Module -Name SharePointPnPPowerShellOnline -Force -Verbose -Scope CurrentUser

Self-Hosted Agent Azure PowerShell (Core) - Module Not Found

I'm running a Self Hosted Windows Agent in Azure DevOps. I have installed PowerShell Core 6.2.3 and as the Administrator installed the Az module so that it is available to all users.
When I run a build using the Azure PowerShell task (V4) - marking as "Use PowerShell Core" and the "Latest Version" of Azure PowerShell I receive the following message:
==============================================================================
Task : Azure PowerShell
Description : Run a PowerShell script within an Azure environment
Version : 4.159.3
Author : Microsoft Corporation
Help : [Learn more about this task](https://go.microsoft.com/fwlink/?LinkID=613749)
==============================================================================
Added TLS 1.2 in session.
Disconnect-AzureRmAccount -Scope Process -ErrorAction Stop
##[warning]Run Connect-AzureRmAccount to login.
##[error]Could not find the modules: 'Az.Accounts' with Version: ''. If the module was recently installed, retry after restarting the Azure Pipelines task agent.
If I run the script on a Hosted Agent it works fine. I can't work out why it fails. I assume it is something different in the profile or environment that the build agent runs under - but I'm not sure how to check this.
On the build agent if I open a PSCore window and run:
Get-Module Az -ListAvailable
It finds the module correctly.
The DevOps Agent is most likely running as a different user and the Az modules have not been installed for that user. Assuming the agent is running as a service, you can check the user by running services.msc and look for "Azure Pipelines Agent", "VSTS Agent" or "vstsagent.[orgname].[agentname]" [1].
Run Get-Module Az -ListAvailable to see where the modules have been installed. Modules under C:\Program Files\PowerShell\Modules have been installed for all users [2].
You can install the modules for all users with:
Install-Module -Name Az -Scope AllUsers
[1] https://learn.microsoft.com/en-us/azure/devops/pipelines/agents/v2-windows?view=azure-devops#run-as-a-service
[2] https://learn.microsoft.com/en-us/powershell/module/powershellget/install-module?view=powershell-7.1#parameters

How to troubleshoot the error [The term 'pwsh.exe' is not recognized as the name of a cmdlet, function, script file, or operable program]?

While creating a new pipeline on Azure DevOps to set up a CI for a .NET project, I set up the following PowerShell script to automate the .NET Core setup.
Here is the script:
$ErrorActionPreference="Stop"
$ProgressPreference="SilentlyContinue"
# $LocalDotnet is the path to the locally-installed SDK to ensure the
# correct version of the tools are executed.
$LocalDotnet=""
# $InstallDir and $CliVersion variables can come from options to the
# script.
$InstallDir = "./cli-tools"
$CliVersion = "1.0.1"
# Test the path provided by $InstallDir to confirm it exists. If it
# does, it's removed. This is not strictly required, but it's a
# good way to reset the environment.
if (Test-Path $InstallDir)
{
rm -Recurse $InstallDir
}
New-Item -Type "directory" -Path $InstallDir
Write-Host "Downloading the CLI installer..."
# Use the Invoke-WebRequest PowerShell cmdlet to obtain the
# installation script and save it into the installation directory.
Invoke-WebRequest `
-Uri "https://dot.net/v1/dotnet-install.ps1" `
-OutFile "$InstallDir/dotnet-install.ps1"
Write-Host "Installing the CLI requested version ($CliVersion) ..."
# Install the SDK of the version specified in $CliVersion into the
# specified location ($InstallDir).
& $InstallDir/dotnet-install.ps1 -Version $CliVersion `
-InstallDir $InstallDir
Write-Host "Downloading and installation of the SDK is complete."
# $LocalDotnet holds the path to dotnet.exe for future use by the
# script.
$LocalDotnet = "$InstallDir/dotnet"
When I try to run the build, I have got the following error:
and
I've already searched on Google for people who have the same problem and how to fix it. But I haven't found much information yet. The Azure DevOps forum doesn't help either.
As mentioned in the comment from above, all you have to do is install the appropriate version of PowerShell on the machine that Agent is running on. For example, PowerShell 7. Then you have to make sure that the environment variable path is set. This variable should point to the directory with PowerShell Core.
Windows
Just install PowerShell Core with the Windows Installer (.msi file from PowerShell Git repository). In this case, the path environment variable is automatically set or expanded so that there will be the path to the directory with pwsh.exe under this variable.
Linux
Install PowerShell Core that is supported by your distribution. Make sure that there is a path variable in your ~/.bashrc file and that path contains the path to the directory with PowerShell Core.
Note: If Azure Agent is already running, you have to restart it so that it sees the changes in the path variable. Hence, on Windows, just restart the agent if run interactively and restart the service if run as a service. On Linux, you can follow this guide in order to update the environment variables that were passed to the Agent.
I know you have already configured your script as a PowerShell Core script, but for completeness I add this: If you use a PowerShell task in your Azure pipeline, the Core version of PowerShell is not set for it by default. In order to run the task as the PowerShell Core script, add this to the YAML code of the task: pwsh: true. Otherwise, if you are still using the old graphical interface, check the "Use PowerShell Core" checkbox under the "Advanced" heading for the task.

"The Azure PowerShell session has not been properly initialized" error message in Octopus

I am trying to run the Get-AzureRmEventHubNamespaceKey cmdlet in an Azure Powershell step within Octopus.
I am getting the following error:
Get-AzureRmEventHubNamespaceKey : The Azure PowerShell session has not been properly
initialized. Please import the module and try again
The module is installed in the following directory on the Octopus server:
C:\Program Files (x86)\Microsoft
SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.EventHub
I have tried importing the module first as part of the same step:
Import-Module –Name "C:\Program Files (x86)\Microsoft SDKs\Azure\PowerShell\ResourceManager\AzureResourceManager\AzureRM.EventHub" -Verbose
And I can see in the output that it has been imported:
VERBOSE: Importing cmdlet 'Get-AzureRmEventHubNamespaceKey'.
But it is immediately followed by the above error. If I RDP to the octopus server and run directly from there it runs fine.
Any ideas on what might be causing this?
To use any Azure related commands from your machine, you need to log in first.
Note that there are several Azure modules, and each has a different login cmdlet, but the link above is specific to the module you're using.