The term New-AzPortalDashboard is not recognized as a name in a azure pipeline - powershell

In summary I am ask to add an Azure Dashboard via an ansible playbook.
I always get the error "The term New-AzPortalDashboard is not recognized as a name"
There is a pipeline file that
install python
"pip install ansible"
"pip install -r https://raw.githubusercontent.com/ansible-collections/azure/dev/requirements-azure.txt"
"ansible-galaxy collection install azure.azcollection"
In the playbook it's basically doing stuff with an api and "include_tasks" an yml file.
This yml file call a ps1 file to create stuff.
In that ps1 file I added a function to get the format of a azure dashboard do some update and call the New-AzPortalDashboard.
function Add-Dashboard {
param ([String]$subscriptionID,[String]$resourceGroup,[String]$apiManagementName,[String]$dashboardTitle,[String]$location)
$file = New-TemporaryFile
$Content = Get-Content ./templates/api-management-dashboard.json
$Content = $Content -replace '<subscriptionID>', $subscriptionID
$Content = $Content -replace '<ressourceGroupName>', $resourceGroup
$Content = $Content -replace '<apiManagementName>', $apiManagementName
$Content = $Content -replace '<dashboardTitle>', $dashboardTitle
$Content = $Content -replace '<location>', $location
$Content | Set-Content $file
$DashboardParams = #{
DashboardPath = $file
ResourceGroupName = $resourceGroup
DashboardName = $dashboardTitle
}
New-AzPortalDashboard #DashboardParams
Remove-Item -Path $file
}
I try to Install-Module for "Az", "Az.Portal" and "Az.Ressource" in the pipeline and the ps1 but it did not work.

Did you check the solution here: Azure DevOps CI/CD missing command: New-AzPortalDashboard
Additionally, verify you are using pwsh core on your build agent:
for classic:
for yaml:
- task: PowerShell#2
inputs:
targetType: filePath
filePath: .....
pwsh: true

Related

Get files that were changed in the repository push that triggered an Azure DevOps release pipeline

I'm trying to get the files added or changed in the repository push that triggered the release pipeline.
Using a PowerShell task, I've been able to identify the files that were changed if they are include in the push's most-recent commit:
$Instance = 'my.org'
$Collection = 'MyCollection'
$Project = 'MyProject'
$RepositoryId = 'my_repo'
$BaseUri = "https://{0}/{1}/{2}/_apis/git/repositories/{3}" -f $Instance, $Collection, $Project, $RepositoryId
$ReleaseDirectory = Join-Path $env:AGENT_RELEASEDIRECTORY $env:RELEASE_PRIMARYARTIFACTSOURCEALIAS
# the BUILD_BUILDID has the GUID for the latest commit
$env:BUILD_BUILDID | ForEach-Object {
$Uri = "$BaseUri/commits/$_/changes?api-version=5.0"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$Response = Invoke-WebRequest -Uri $Uri -UseDefaultCredentials -UseBasicParsing
$Content = $Response | ConvertFrom-Json
$Content.changes | Select-Object #{name='path';expression={$_.item.path}} | ForEach-Object {
$ChangedItemPath = Join-Path $ReleaseDirectory $_.path
Get-Item -Path $ChangedItemPath
} | Where-Object { $_.PSIsContainer -eq $false }
}
The Get Push Commits API method looks promising, but I can't find the pushId in the pipeline's environment variables.
Is the pushId available? Do I need to take different approach?

Using Nuget package feed from PowerShell in Azure pipeline

I'm trying to write a pipeline PowerShell task that checks that package version numbers in the csproj files have been incremented -- so that the push step doesn't fail because of duplicates when building new release packages. (We use allowPackageConflicts: false on the NuGetCommand#2 command: push task.)
The problem is to get Find-Package to use my Azure DevOps NuGet feed that all the packages go to.
- task: PowerShell#2
displayName: 'Check package version numbers'
inputs:
targetType: 'inline'
script: |
[bool] $bad = $false;
Get-PackageSource
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
Register-PackageSource -Name TheAzureDevOpsFeed -Trusted -Force -ProviderName NuGet -Location "https://pkgs.dev.azure.com/Organisation/_packaging/TheAzureDevOpsFeed/nuget/v3/index.json"
Get-PackageSource
foreach( $csproj in Get-ChildItem **\*.csproj ) {
$m = Select-String -Path $csproj.FullName -Pattern '<VersionPrefix>([\d\.]+)</VersionPrefix>'
$pkgName = [System.IO.Path]::GetFileNameWithoutExtension($csproj.FullName)
echo $pkgName
if( $m.Matches.Count -eq 1 )
{
$csprojVersion = $m.Matches[0].Groups[1].Value
$pkg = $null
try {
$pkg = Find-Package $pkgName -Source TheAzureDevOpsFeed -ErrorAction Stop
}
catch {
$pkg = $null
}
if( $pkg -eq $null )
{
echo " No existing package."
continue
}
$current = $pkg.Versions[0].OriginalVersion
if( [System.Version]"$csprojVersion" -le [System.Version]"$current" )
{
echo " REJECTED: current version is $current but csproj has version $csprojVersion."
$bad = $true
}
else {
echo " $current -> $csprojVersion"
}
}
else {
echo " skipped"
}
}
if( $bad ) {
exit 1
}
exit 0
When the task runs the output is:
Name ProviderName IsTrusted Location
---- ------------ --------- --------
nuget.org NuGet False https://api.nuget.org/v3/index.json
PSGallery PowerShellGet False https://www.powershellgallery.com/api/v2
Register-PackageSource : Source Location
'https://pkgs.dev.azure.com/Organisation/_packaging/TheAzureDevOpsFeed/nuget/v3/index.json' is not valid.
At D:\a\_temp\62c6a3fb-93a6-4d4a-8cf5-ce5dc7d9dcbf.ps1:7 char:1
+ Register-PackageSource -Name TheAzureDevOpsFeed -Trusted -Force -Provi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (TheAzureDevOpsFeed:String) [Register-PackageSource], Exception
+ FullyQualifiedErrorId : SourceLocationNotValid,Microsoft.PowerShell.PackageManagement.Cmdlets.RegisterPackageSou
rce
But why is it 'not valid'? It is valid -- it works fine in VisualStudio.
Things I've tried:
single quotes, double quotes, no quotes,
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12,
-Location https://pkgs.dev.azure.com/.../v2
I can reproduce your issue:
How I solve this:
$patToken = "<Your PAT here>" | ConvertTo-SecureString -AsPlainText -Force
$credsAzureDevopsServices = New-Object System.Management.Automation.PSCredential("<Your email address that related to PAT here>", $patToken)
Register-PackageSource -Name "xxx" -Location "https://pkgs.dev.azure.com/<organizaton name>/_packaging/<feed name>/nuget/v2" -ProviderName NuGet -Credential $credsAzureDevopsServices
Please refer to these official documents:
https://learn.microsoft.com/en-us/powershell/module/packagemanagement/register-packagesource?view=powershell-7.2
https://learn.microsoft.com/en-us/azure/devops/artifacts/tutorials/private-powershell-library?view=azure-devops#connecting-to-the-feed-as-a-powershell-repo
Let me know if you have more concerns.

How to download a file from a non static link using .bat script

I am trying to download the Total counts by date for all King County excel file using a script that will be run later on using task manager. I am stuck due to the link not being static and its naming convention will most likely change in the next few months.
Here's the code that I've written so far:
#echo off
::Script to download COVID-19 Data
echo "Downloading Total counts by date for all King County"
powershell -Command "Invoke-WebRequest https://www.kingcounty.gov/depts/health/covid-19/data/~/media/depts/health/communicable-diseases/documents/C19/data/covid-data-daily-counts-sept-14.ashx -Outfile CovidData.xlsx
echo "Download has been successful!"
cls
pause
I was wondering if there's a way to add a wild card like "*" in the invoke-webrequest to ignore the "sept-14" part of the link.
Link: https://www.kingcounty.gov/depts/health/covid-19/data/daily-summary.aspx
Link that needs a script to auto download with task manager (Total counts by date for all King County): https://www.kingcounty.gov/depts/health/covid-19/data/~/media/depts/health/communicable-diseases/documents/C19/data/covid-data-daily-counts-sept-14.ashx
I created and tested Powershell Script on my side with Windows Powershell ISE and it works 5/5, hope that will work too for you !
$start_time = Get-Date
$url = "https://www.kingcounty.gov/depts/health/covid-19/data/daily-summary.aspx"
$xlFile = "E:\Test\CovidData.xlsx"
$http_request = New-Object -ComObject Microsoft.XMLHTTP
$http_request.open('GET', $url, $false)
#Sending the request
$http_request.send()
$Contents = $http_request.ResponseText
$pattern = "([\w\-\.,#?^=%&/~\+#]*[\w\-\#?^=%&/~\+#])(\.ashx)"
$Links = $Contents | Select-String $pattern -AllMatches | ForEach-Object {$_.Matches.Value} | sort -unique
$Filter = $Links -match "data-daily"
$MyUrlFile = "https://www.kingcounty.gov/depts/health/covid-19/data/" + $Filter
$MyUrlFile
Invoke-WebRequest "$MyUrlFile" -Outfile $xlFile
if (Test-Path $xlFile) { Start $xlFile }
Write-Output "Running Script Time taken is : $((Get-Date).Subtract($start_time).Seconds) second(s)"

How to get the workitems from AzureDevOps with RestApi in Powershell

Param(
[string]$collectionurl = "https://dev.azure.com",
[string]$project = "projectname",
[string]$token = "PAT"
)
# Base64-encodes the Personal Access Token (PAT) appropriately
$base64AuthInfo =
[Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}" -f
$token)))
$baseUrl =
"$collectionurl/$project/_apis/wit/reporting/workitemrevisions?
includeLatestOnly=true&api-version=5.0-preview.2"
$response = (Invoke-RestMethod -Uri $baseUrl -Method Get -
UseDefaultCredential -Headers #{Authorization=("Basic {0}" -f
$base64AuthInfo)}).values
$wits = $response | where({$_.fields.'System.WorkItemType' -eq
'Task'}) # Only retrieve Tasks
$witrevisions = #()
foreach($wit in $wits){
$customObject = new-object PSObject -property #{
"WitID" = $wit.fields.'System.Id'
"rev" = $wit.fields.'System.Rev'
"Title" = $wit.fields.'System.Title'
"AssignedTo" = $wit.fields.'System.AssignedTo'
"ChangedDate" = $wit.fields.'System.ChangedDate'
"ChangedBy" = $wit.fields.'System.ChangedBy'
"WorkItemType" = $wit.fields.'System.WorkItemType'
}
$witrevisions += $customObject
}
$witrevisions | Select-Object `
WitID,
rev,
Title,
AssignedTo,
ChangedDate,
ChangedBy,
WorkItemType #|export-csv -Path E:\ashwin\devdata.csv -
NoTypeInformation
Write-Output $witrevisions
I want to display the workitems in my project to be displayed using powershell with the following Rest Api using my PAT.
https://dev.azure.com/{organization}/{project}/_apis/wit/workitems/{id}?api-version=5.1
How to get the workitems from AzureDevOps with RestApi in Powershell
The result will display in the output, you will find like following:
If you do not find above output, make sure you have workitem with Task type, because you have set the condition 'System.WorkItemType' -eq 'Task' in the powershell scripts.
On the other hand, you could export the work item list to a *.csv file, this part of the code is commented in powershell:
WorkItemType #| export-csv -Path G:\temp\WIT.csv -NoTypeInformation
If you want to create a *.csv file, you need to remove the # in that line, it should be :
WorkItemType | export-csv -Path G:\temp\WIT.csv -NoTypeInformation
Now, we could get that file in our local folder:
Note: The path is G:\temp is a local path, you should use the private agent, if you are using the hosted agent, you should copy that file from the hosted agent, and publish it to pipeline artifact.
Hope this helps.

Executing XMLA with AMO PowerShell does not create measures

I wrote a PowerShell script to automate deployment of SSAS Cubes. I use the Deployment Wizard to generate an XMLA file and then PowerShell AMO command to deploy it. However, when I run it the tabular database gets created but all measures are missing. Running the same XMLA from SQL Management Studio or using Invoke-ASCmd produce the correct database with all measures in it. Am I missing an option or something in the "Invoke" command?
[CmdletBinding()]
Param(
# InputDir is required
[Parameter(Mandatory=$True,Position=1)]
[string]$InputDir,
# Server is optional
[Parameter(Mandatory=$False,Position=2)]
[string]$Server=$env:computername
)
# Output execution parameters.
"Executing with the following parameters:"
" InputDir: $InputDir"
" AS Database Server: $Server`n"
$XmlaDir = Resolve-Path($InputDir)
$Xmla = Join-Path -Path $XmlaDir -ChildPath '\Model.xmla'
$ASFiles = Get-ChildItem -Recurse -Path $InputDir -Filter *.asdatabase
$Count = $ASFiles.Count
If($Count -ne 1)
{
Write-Host("`ERROR: Count asdatabase file(s) found at $inputdir")
Exit 1
}
$ASDatabase = $ASFiles[0].FullName
Write-Host("`nUsing $ASDatabase for deployment.")
Write-Host("`nAttempting to create $Xmla ...`n")
# Use Analysis Services Deployment Utility to generate XMLA file from
.asdatabase file
$Script:ASDeployWizard = "E:\Program Files (x86)\Microsoft SQL Server\110\Tools\Binn\ManagementStudio\Microsoft.AnalysisServices.Deployment.exe
"
$Arguments = #("`"$ASDatabase`"", "/s", "/o:`"$Xmla`"")
Start-Process -FilePath $Script:ASDeployWizard -ArgumentList $Arguments -Wait
If ((-Not $?) -Or -Not (Test-Path $Xmla))
{
"Cannot generate deployment descriptor. Deployment aborted."
Exit 1
}
Write-Host("XMLA deployment descriptor generated.`n")
Try {
Import-Module SQLPS -DisableNameChecking
# Deploy Cube
"Invoking deployment script. This may take several minutes...`n"
$AS = New-Object Microsoft.AnalysisServices.Server
$AS.connect($Server)
$CubeDescriptor = [string](Get-Content $Xmla)
$Results = $AS.Execute($CubeDescriptor)
Foreach ($r in $Results) {
$r.Messages.Description
}
"Done.`n"
} Catch {
Write-Host($_.Exception.GetType().FullName + "`n" + $_.Exception.Message + "`n")
Write-Host("Deployment FAILED.`n")
}
Exit 0