From 88a2c7a03904c24e2e83cdf4db773330a9681c7e Mon Sep 17 00:00:00 2001 From: "G.Reijn" Date: Sun, 29 Dec 2024 06:06:05 +0100 Subject: [PATCH] Apply PowerShell Practice Styles --- .gitignore | 2 - .vscode/settings.json | 22 ++ .../src/Library/Add-AzureResourceGroup.ps1 | 21 +- .../src/Library/Add-WinGetManifest.ps1 | 72 +++-- .../src/Library/Connect-ToAzure.ps1 | 39 ++- .../src/Library/Find-WinGetManifest.ps1 | 103 ++++--- .../src/Library/Get-PairedAzureRegion.ps1 | 254 ++++++++---------- .../src/Library/Get-WinGetManifest.ps1 | 145 +++++----- .../src/Library/New-MicrosoftEntraIdApp.ps1 | 49 ++-- .../src/Library/New-WinGetSource.ps1 | 74 +++-- .../src/Library/Remove-WinGetManifest.ps1 | 77 +++--- .../src/Library/Test-ARMTemplates.ps1 | 16 +- .../src/Library/Test-ConnectionToAzure.ps1 | 26 +- .../Library/Test-PowerShellModuleExist.ps1 | 13 +- .../src/Library/Test-WinGetManifest.ps1 | 18 +- .../src/Library/Update-WinGetSource.ps1 | 70 +++-- .../src/Library/WinGetManifest.ps1 | 67 ++--- .../src/Microsoft.WinGet.RestSource.psd1 | 31 ++- .../src/Microsoft.WinGet.RestSource.psm1 | 18 +- 19 files changed, 519 insertions(+), 598 deletions(-) create mode 100644 .vscode/settings.json diff --git a/.gitignore b/.gitignore index c220ff39..14fcccbd 100644 --- a/.gitignore +++ b/.gitignore @@ -374,5 +374,3 @@ Microsoft.WinGet.*.Documentation.xml # Developer ARM template src/WinGet.RestSource.Infrastructure/**/*.dev.*json -# VS Code -.vscode/ diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..e45de607 --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,22 @@ +{ + "editor.formatOnSave": true, + "[powershell]": { + "files.encoding": "utf8bom", + "files.autoGuessEncoding": true + }, + "powershell.codeFormatting.preset": "OTBS", + "powershell.codeFormatting.useConstantStrings": true, + "powershell.codeFormatting.trimWhitespaceAroundPipe": true, + "powershell.codeFormatting.useCorrectCasing": true, + "powershell.codeFormatting.whitespaceBeforeOpenParen": true, + "powershell.codeFormatting.whitespaceBetweenParameters": true, + "powershell.codeFormatting.addWhitespaceAroundPipe": true, + "powershell.codeFormatting.alignPropertyValuePairs": true, + "powershell.codeFormatting.autoCorrectAliases": true, + "powershell.codeFormatting.avoidSemicolonsAsLineTerminators": true, + "powershell.codeFormatting.ignoreOneLineBlock": true, + "powershell.codeFormatting.whitespaceBeforeOpenBrace": true, + "powershell.codeFormatting.whitespaceAroundOperator": true, + "powershell.codeFormatting.whitespaceAfterSeparator": true, + "powershell.codeFormatting.whitespaceInsideBrace": true +} \ No newline at end of file diff --git a/Tools/PowershellModule/src/Library/Add-AzureResourceGroup.ps1 b/Tools/PowershellModule/src/Library/Add-AzureResourceGroup.ps1 index 2572f7fe..26358ed7 100644 --- a/Tools/PowershellModule/src/Library/Add-AzureResourceGroup.ps1 +++ b/Tools/PowershellModule/src/Library/Add-AzureResourceGroup.ps1 @@ -1,7 +1,6 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -Function Add-AzureResourceGroup -{ +Function Add-AzureResourceGroup { <# .SYNOPSIS Adds a Resource Group to the connected to Subscription. @@ -25,15 +24,15 @@ Function Add-AzureResourceGroup #> PARAM( - [Parameter(Position=0, Mandatory=$true)] [string]$Name, - [Parameter(Position=1, Mandatory=$true)] [string]$Region + [Parameter(Position = 0, Mandatory = $true)] [string]$Name, + [Parameter(Position = 1, Mandatory = $true)] [string]$Region ) $Return = $false ## Normalize resource group name - $NormalizedName = $Name -replace "[^a-zA-Z0-9-()_.]", "" - if($Name -cne $NormalizedName) { + $NormalizedName = $Name -replace '[^a-zA-Z0-9-()_.]', '' + if ($Name -cne $NormalizedName) { $Name = $NormalizedName Write-Warning "Removed special characters from the Azure Resource Group Name (New Name: $Name)." } @@ -45,19 +44,17 @@ Function Add-AzureResourceGroup Write-Verbose "Retrieving details from Azure for the Resource Group name $Name" $Result = Get-AzResourceGroup -Name $Name -ErrorAction SilentlyContinue -ErrorVariable ErrorGet - if(!$Result) { + if (!$Result) { Write-Information "Failed to retrieve Resource Group, will attempt to create $Name in the specified $Region." $Result = New-AzResourceGroup -Name $Name -Location $Region - if($Result) { + if ($Result) { Write-Information "Resource Group $Name has been created in the $Region region." $Return = $true - } - else { + } else { Write-Error "Failed to retrieve or create Resource Group with name $Name." } - } - else { + } else { ## Found an existing Resource Group matching the name of $Name Write-Warning "Found an existing Resource Group matching the name of $Name. Will not create a new Resource Group." $Return = $true diff --git a/Tools/PowershellModule/src/Library/Add-WinGetManifest.ps1 b/Tools/PowershellModule/src/Library/Add-WinGetManifest.ps1 index b09e46b6..9f422984 100644 --- a/Tools/PowershellModule/src/Library/Add-WinGetManifest.ps1 +++ b/Tools/PowershellModule/src/Library/Add-WinGetManifest.ps1 @@ -1,7 +1,6 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -Function Add-WinGetManifest -{ +Function Add-WinGetManifest { <# .SYNOPSIS Submits a Manifest file to the Azure REST source @@ -42,27 +41,26 @@ Function Add-WinGetManifest #> PARAM( - [Parameter(Position=0, Mandatory=$true)] [string]$FunctionName, - [Parameter(Position=1, Mandatory=$true, ValueFromPipeline=$true)] [string]$Path, - [Parameter(Mandatory=$false)] [string]$SubscriptionName = "" + [Parameter(Position = 0, Mandatory = $true)] [string]$FunctionName, + [Parameter(Position = 1, Mandatory = $true, ValueFromPipeline = $true)] [string]$Path, + [Parameter(Mandatory = $false)] [string]$SubscriptionName = '' ) - BEGIN - { + BEGIN { [WinGetManifest[]] $Return = @() ############################### ## Connects to Azure, if not already connected. - Write-Verbose -Message "Validating connection to azure, will attempt to connect if not already connected." + Write-Verbose -Message 'Validating connection to azure, will attempt to connect if not already connected.' $Result = Connect-ToAzure -SubscriptionName $SubscriptionName - if(!($Result)) { - Write-Error "Failed to connect to Azure. Please run Connect-AzAccount to connect to Azure, or re-run the cmdlet and enter your credentials." -ErrorAction Stop + if (!($Result)) { + Write-Error 'Failed to connect to Azure. Please run Connect-AzAccount to connect to Azure, or re-run the cmdlet and enter your credentials.' -ErrorAction Stop } ############################### ## Gets Resource Group name of the Azure Function - Write-Verbose -Message "Determines the Azure Function Resource Group Name" - $ResourceGroupName = $(Get-AzFunctionApp).Where({$_.Name -eq $FunctionName}).ResourceGroupName - if(!$ResourceGroupName) { + Write-Verbose -Message 'Determines the Azure Function Resource Group Name' + $ResourceGroupName = $(Get-AzFunctionApp).Where({ $_.Name -eq $FunctionName }).ResourceGroupName + if (!$ResourceGroupName) { Write-Error "Failed to confirm Azure Function exists in Azure. Please verify and try again. Function Name: $FunctionName" -ErrorAction Stop } @@ -70,16 +68,16 @@ Function Add-WinGetManifest ############## REST api call ############## ## Specifies the REST api call that will be performed - $ApiContentType = "application/json" - $ApiMethodPost = "Post" - $ApiMethodGet = "Get" - $ApiMethodPut = "Put" + $ApiContentType = 'application/json' + $ApiMethodPost = 'Post' + $ApiMethodGet = 'Get' + $ApiMethodPut = 'Put' ## Retrieves the Azure Function URL used to add new manifests to the REST source Write-Verbose -Message "Retrieving the Azure Function $FunctionName to build out the REST API request." $FunctionApp = Get-AzFunctionApp -ResourceGroupName $ResourceGroupName -Name $FunctionName - $FunctionAppId = $FunctionApp.Id + $FunctionAppId = $FunctionApp.Id $DefaultHostName = $FunctionApp.DefaultHostName $FunctionKeyPost = (Invoke-AzResourceAction -ResourceId "$FunctionAppId/functions/ManifestPost" -Action listkeys -Force).default $FunctionKeyGet = (Invoke-AzResourceAction -ResourceId "$FunctionAppId/functions/ManifestGet" -Action listkeys -Force).default @@ -87,21 +85,20 @@ Function Add-WinGetManifest ## Creates the API Post Header - $ApiHeader = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" - $ApiHeader.Add("Accept", 'application/json') + $ApiHeader = New-Object 'System.Collections.Generic.Dictionary[[String],[String]]' + $ApiHeader.Add('Accept', 'application/json') - $AzFunctionURLBase = "https://" + $DefaultHostName + "/api/packageManifests/" + $AzFunctionURLBase = 'https://' + $DefaultHostName + '/api/packageManifests/' } - PROCESS - { + PROCESS { $Path = [System.IO.Path]::GetFullPath($Path, $pwd.Path) ############################### ## Gets the content from the Package Manifest (*.JSON, or *.YAML) file for posting to REST source. - Write-Verbose -Message "Retrieving a copy of the app Manifest file for submission to WinGet source." + Write-Verbose -Message 'Retrieving a copy of the app Manifest file for submission to WinGet source.' $ApplicationManifest = Get-WinGetManifest -Path $Path - if($ApplicationManifest.Count -ne 1) { - Write-Error "Failed to retrieve a proper manifest. Verify and try again." + if ($ApplicationManifest.Count -ne 1) { + Write-Error 'Failed to retrieve a proper manifest. Verify and try again.' return } @@ -109,7 +106,7 @@ Function Add-WinGetManifest Write-Verbose -Message "Contents of manifest have been retrieved. Package Identifier: $($Manifest.PackageIdentifier)." Write-Verbose -Message "Confirming that the Package ID doesn't already exist in Azure for $($Manifest.PackageIdentifier)." - $ApiHeader["x-functions-key"] = $FunctionKeyGet + $ApiHeader['x-functions-key'] = $FunctionKeyGet $AzFunctionURL = $AzFunctionURLBase + $Manifest.PackageIdentifier $Response = Invoke-RestMethod $AzFunctionURL -Headers $ApiHeader -Method $ApiMethodGet -ErrorVariable ErrorInvoke @@ -119,20 +116,19 @@ Function Add-WinGetManifest $ApiMethod = $ApiMethodPost $AzFunctionURL = $AzFunctionURLBase - $ApiHeader["x-functions-key"] = $FunctionKeyPost - } - else { + $ApiHeader['x-functions-key'] = $FunctionKeyPost + } else { ## Existing manifest retrieved, submit as update existing manifest Write-Verbose "Found manifest that matched. Package Identifier: $($Manifest.PackageIdentifier)" - if($Response.Data.Count -gt 1) { + if ($Response.Data.Count -gt 1) { Write-Error "Found conflicting manifests. Package Identifier: $($Manifest.PackageIdentifier)" return } $ApiMethod = $ApiMethodPut $AzFunctionURL = $AzFunctionURLBase + $Manifest.PackageIdentifier - $ApiHeader["x-functions-key"] = $FunctionKeyPut + $ApiHeader['x-functions-key'] = $FunctionKeyPut ## Merge with prior manifest $PriorManifest = [WinGetManifest]::CreateFromObject($Response.Data[0]) @@ -144,7 +140,7 @@ Function Add-WinGetManifest $Response = Invoke-RestMethod $AzFunctionURL -Headers $ApiHeader -Method $ApiMethod -Body $Manifest.GetJson() -ContentType $ApiContentType -ErrorVariable ErrorInvoke - if($ErrorInvoke) { + if ($ErrorInvoke) { $ErrReturnObject = @{ AzFunctionURL = $AzFunctionURL ApiMethod = $ApiMethod @@ -154,21 +150,19 @@ Function Add-WinGetManifest InvokeError = $ErrorInvoke } - Write-Error -Message "Failed to add manifest." -TargetObject $ErrReturnObject - } - else { + Write-Error -Message 'Failed to add manifest.' -TargetObject $ErrReturnObject + } else { if ($Response.Data.Count -ne 1) { Write-Warning "Returned conflicting manifests after adding the manifest. Package Identifier: $($Manifest.PackageIdentifier)" } - foreach ($ResponseData in $Response.Data){ + foreach ($ResponseData in $Response.Data) { Write-Verbose "Parsing through the returned results: $ResponseData" $Return += [WinGetManifest]::CreateFromObject($ResponseData) } } } - END - { + END { return $Return } } \ No newline at end of file diff --git a/Tools/PowershellModule/src/Library/Connect-ToAzure.ps1 b/Tools/PowershellModule/src/Library/Connect-ToAzure.ps1 index c4ee44a4..bf1937af 100644 --- a/Tools/PowershellModule/src/Library/Connect-ToAzure.ps1 +++ b/Tools/PowershellModule/src/Library/Connect-ToAzure.ps1 @@ -1,7 +1,6 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -Function Connect-ToAzure -{ +Function Connect-ToAzure { <# .SYNOPSIS Connects to an Azure environment and connects to a specific Azure Subscription if a name of the subscription has been provided. @@ -38,65 +37,59 @@ Function Connect-ToAzure #> PARAM( - [Parameter(Mandatory=$false)] [string]$SubscriptionName = "", - [Parameter(Mandatory=$false)] [string]$SubscriptionId = "" + [Parameter(Mandatory = $false)] [string]$SubscriptionName = '', + [Parameter(Mandatory = $false)] [string]$SubscriptionId = '' ) $TestAzureConnection = $false - if($SubscriptionName -and $SubscriptionId){ + if ($SubscriptionName -and $SubscriptionId) { ## If connected to Azure, and the Subscription Name and Id are provided then verify that the connected Azure session matches the provided Subscription Name and Id. Write-Verbose -Message "Verifying if PowerShell session is currently connected to your Azure Subscription Name $SubscriptionName and Subscription Id $SubscriptionId" $TestAzureConnection = Test-ConnectionToAzure -SubscriptionName $SubscriptionName -SubscriptionId $SubscriptionId - } - elseif($SubscriptionName){ + } elseif ($SubscriptionName) { ## If connected to Azure, and the Subscription Name are provided then verify that the connected Azure session matches the provided Subscription Name. Write-Verbose -Message "Verifying if PowerShell session is currently connected to your Azure Subscription Name $SubscriptionName" $TestAzureConnection = Test-ConnectionToAzure -SubscriptionName $SubscriptionName - } - elseif($SubscriptionId){ + } elseif ($SubscriptionId) { ## If connected to Azure, and the Subscription Id are provided then verify that the connected Azure session matches the provided Subscription Id. Write-Verbose -Message "Verifying if PowerShell session is currently connected to your Azure Subscription Id $SubscriptionId" $TestAzureConnection = Test-ConnectionToAzure -SubscriptionId $SubscriptionId - } - else{ - Write-Information "No Subscription Name or Subscription Id provided. Will test connection to default Azure Subscription" + } else { + Write-Information 'No Subscription Name or Subscription Id provided. Will test connection to default Azure Subscription' $TestAzureConnection = Test-ConnectionToAzure } Write-Verbose -Message "Test Connection Result: $TestAzureConnection" - if(!$TestAzureConnection) { - if($SubscriptionName -and $SubscriptionId) { + if (!$TestAzureConnection) { + if ($SubscriptionName -and $SubscriptionId) { ## Attempts a connection to Azure using both the Subscription Name and Subscription Id Write-Information "Initiating a connection to your Azure Subscription Name $SubscriptionName and Subscription Id $SubscriptionId" $ConnectResult = Connect-AzAccount -SubscriptionName $SubscriptionName -SubscriptionId $SubscriptionId $TestAzureConnection = Test-ConnectionToAzure -SubscriptionName $SubscriptionName -SubscriptionId $SubscriptionId - } - elseif($SubscriptionName) { + } elseif ($SubscriptionName) { ## Attempts a connection to Azure using Subscription Name Write-Information "Initiating a connection to your Azure Subscription Name $SubscriptionName" $ConnectResult = Connect-AzAccount -SubscriptionName $SubscriptionName $TestAzureConnection = Test-ConnectionToAzure -SubscriptionName $SubscriptionName - } - elseif($SubscriptionId) { + } elseif ($SubscriptionId) { ## Attempts a connection to Azure using Subscription Id Write-Information "Initiating a connection to your Azure Subscription Id $SubscriptionId" $ConnectResult = Connect-AzAccount -SubscriptionId $SubscriptionId $TestAzureConnection = Test-ConnectionToAzure -SubscriptionId $SubscriptionId - } - else{ + } else { ## Attempts a connection to Azure with the users default Subscription - Write-Information "Initiating a connection to your Azure environment." + Write-Information 'Initiating a connection to your Azure environment.' $ConnectResult = Connect-AzAccount $TestAzureConnection = Test-ConnectionToAzure } - if(!$TestAzureConnection) { + if (!$TestAzureConnection) { ## If the connection fails, or the user cancels the login request, then return as failed. $ErrReturnObject = @{ SubscriptionName = $SubscriptionName @@ -104,7 +97,7 @@ Function Connect-ToAzure AzureConnected = $TestAzureConnection } - Write-Error -Message "Failed to connect to Azure" -TargetObject $ErrReturnObject + Write-Error -Message 'Failed to connect to Azure' -TargetObject $ErrReturnObject } } diff --git a/Tools/PowershellModule/src/Library/Find-WinGetManifest.ps1 b/Tools/PowershellModule/src/Library/Find-WinGetManifest.ps1 index e9efe8c2..59683efe 100644 --- a/Tools/PowershellModule/src/Library/Find-WinGetManifest.ps1 +++ b/Tools/PowershellModule/src/Library/Find-WinGetManifest.ps1 @@ -1,8 +1,7 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -Function Find-WinGetManifest -{ +Function Find-WinGetManifest { <# .SYNOPSIS Connects to the specified source REST API to retrieve the package manifests, returning manifest package identifier, name, publisher and versions. @@ -46,30 +45,29 @@ Function Find-WinGetManifest #> PARAM( - [Parameter(Position=0, Mandatory=$true)] [string]$FunctionName, - [Parameter(Mandatory=$false)] [string]$Query = "", - [Parameter(Mandatory=$false)] [string]$PackageIdentifier = "", - [Parameter(Mandatory=$false)] [string]$PackageName = "", - [Parameter(Mandatory=$false)] [string]$SubscriptionName = "", + [Parameter(Position = 0, Mandatory = $true)] [string]$FunctionName, + [Parameter(Mandatory = $false)] [string]$Query = '', + [Parameter(Mandatory = $false)] [string]$PackageIdentifier = '', + [Parameter(Mandatory = $false)] [string]$PackageName = '', + [Parameter(Mandatory = $false)] [string]$SubscriptionName = '', [Parameter()] [switch]$Exact ) - BEGIN - { + BEGIN { [PSCustomObject[]] $Return = @() ############################### ## Connects to Azure, if not already connected. - Write-Verbose "Validating connection to azure, will attempt to connect if not already connected." + Write-Verbose 'Validating connection to azure, will attempt to connect if not already connected.' $Result = Connect-ToAzure -SubscriptionName $SubscriptionName - if(!($Result)) { - Write-Error "Failed to connect to Azure. Please run Connect-AzAccount to connect to Azure, or re-run the cmdlet and enter your credentials." -ErrorAction Stop + if (!($Result)) { + Write-Error 'Failed to connect to Azure. Please run Connect-AzAccount to connect to Azure, or re-run the cmdlet and enter your credentials.' -ErrorAction Stop } ############################### ## Gets Resource Group name of the Azure Function - Write-Verbose -Message "Determines the Azure Function Resource Group Name" - $ResourceGroupName = $(Get-AzFunctionApp).Where({$_.Name -eq $FunctionName}).ResourceGroupName - if(!$ResourceGroupName) { + Write-Verbose -Message 'Determines the Azure Function Resource Group Name' + $ResourceGroupName = $(Get-AzFunctionApp).Where({ $_.Name -eq $FunctionName }).ResourceGroupName + if (!$ResourceGroupName) { Write-Error "Failed to confirm Azure Function exists in Azure. Please verify and try again. Function Name: $FunctionName" -ErrorAction Stop } @@ -77,35 +75,33 @@ Function Find-WinGetManifest Write-Verbose -Message "Retrieving Azure Function Web Applications matching to: $FunctionName." $FunctionApp = Get-AzFunctionApp -ResourceGroupName $ResourceGroupName -Name $FunctionName - $FunctionAppId = $FunctionApp.Id + $FunctionAppId = $FunctionApp.Id $DefaultHostName = $FunctionApp.DefaultHostName - $TriggerName = "ManifestSearchPost" - $ApiContentType = "application/json" - $ApiMethod = "Post" + $TriggerName = 'ManifestSearchPost' + $ApiContentType = 'application/json' + $ApiMethod = 'Post' ## Creates the API Post Header - $ApiHeader = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" - $ApiHeader.Add("Accept", 'application/json') + $ApiHeader = New-Object 'System.Collections.Generic.Dictionary[[String],[String]]' + $ApiHeader.Add('Accept', 'application/json') $FunctionKey = (Invoke-AzResourceAction -ResourceId "$FunctionAppId/functions/$TriggerName" -Action listkeys -Force).default - $ApiHeader.Add("x-functions-key", $FunctionKey) + $ApiHeader.Add('x-functions-key', $FunctionKey) - $AzFunctionURL = "https://" + $DefaultHostName + "/api/manifestSearch" + $AzFunctionURL = 'https://' + $DefaultHostName + '/api/manifestSearch' } - PROCESS - { - Write-Verbose -Message "Invoking the REST API call." + PROCESS { + Write-Verbose -Message 'Invoking the REST API call.' ## Internal scan does not recognize ternary oprator, use if else here if ($Exact) { - $QueryMatchType = "Exact" - } - else { - $QueryMatchType = "Substring" + $QueryMatchType = 'Exact' + } else { + $QueryMatchType = 'Substring' } $RequestBody = @{ - Query = @{ - KeyWord = $Query + Query = @{ + KeyWord = $Query MatchType = $QueryMatchType } Filters = @() @@ -113,25 +109,24 @@ Function Find-WinGetManifest ## Internal scan does not recognize ternary oprator, use if else here if ($Exact) { - $FilterMatchType = "Exact" - } - else { - $FilterMatchType = "CaseInsensitive" + $FilterMatchType = 'Exact' + } else { + $FilterMatchType = 'CaseInsensitive' } if (![string]::IsNullOrWhiteSpace($PackageIdentifier)) { $RequestBody.Filters += @{ - PackageMatchField = "PackageIdentifier" - RequestMatch = @{ - KeyWord = $PackageIdentifier + PackageMatchField = 'PackageIdentifier' + RequestMatch = @{ + KeyWord = $PackageIdentifier MatchType = $FilterMatchType } } } if (![string]::IsNullOrWhiteSpace($PackageName)) { $RequestBody.Filters += @{ - PackageMatchField = "PackageName" - RequestMatch = @{ - KeyWord = $PackageName + PackageMatchField = 'PackageName' + RequestMatch = @{ + KeyWord = $PackageName MatchType = $FilterMatchType } } @@ -143,7 +138,7 @@ Function Find-WinGetManifest $ContinuationToken = $null do { if ($ContinuationToken) { - $ApiHeader["ContinuationToken"] = $ContinuationToken + $ApiHeader['ContinuationToken'] = $ContinuationToken } $Response = Invoke-RestMethod $AzFunctionURL -Headers $ApiHeader -Method $ApiMethod -Body $RequestBodyJson -ContentType $ApiContentType -ErrorVariable ErrorInvoke @@ -151,26 +146,25 @@ Function Find-WinGetManifest if ($ErrorInvoke) { $ErrorMessage = "Failed to get search result from $FunctionName. Verify the information you provided and try again." $ErrReturnObject = @{ - AzFunctionURL = $AzFunctionURL - ApiMethod = $ApiMethod - ApiContentType = $ApiContentType - Response = $Response - InvokeError = $ErrorInvoke + AzFunctionURL = $AzFunctionURL + ApiMethod = $ApiMethod + ApiContentType = $ApiContentType + Response = $Response + InvokeError = $ErrorInvoke } Write-Error -Message $ErrorMessage -TargetObject $ErrReturnObject return - } - else { + } else { Write-Verbose "Found ($($Response.Data.Count)) Manifests that matched." foreach ($ResponseData in $Response.Data) { Write-Verbose -Message "Parsing through the returned results: $ResponseData" $ManifestInfo = [PSCustomObject]@{ PackageIdentifier = $ResponseData.PackageIdentifier - PackageName = $ResponseData.PackageName - Publisher = $ResponseData.Publisher - Versions = [string[]]@() + PackageName = $ResponseData.PackageName + Publisher = $ResponseData.Publisher + Versions = [string[]]@() } foreach ($Version in $ResponseData.Versions) { $ManifestInfo.Versions += $Version.PackageVersion @@ -182,8 +176,7 @@ Function Find-WinGetManifest $ContinuationToken = $Response.ContinuationToken } while (![string]::IsNullOrWhiteSpace($ContinuationToken)) } - END - { + END { ## Returns results Write-Verbose -Message "Returning ($($Return.Count)) manifests based on search." return $Return diff --git a/Tools/PowershellModule/src/Library/Get-PairedAzureRegion.ps1 b/Tools/PowershellModule/src/Library/Get-PairedAzureRegion.ps1 index 114713fe..d3f61da6 100644 --- a/Tools/PowershellModule/src/Library/Get-PairedAzureRegion.ps1 +++ b/Tools/PowershellModule/src/Library/Get-PairedAzureRegion.ps1 @@ -1,249 +1,233 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -Function Get-PairedAzureRegion -{ +Function Get-PairedAzureRegion { PARAM( - [Parameter(Position=0, Mandatory=$true)] [string]$Region + [Parameter(Position = 0, Mandatory = $true)] [string]$Region ) - $Result = "westus" + $Result = 'westus' - if($Region -like "*canada*") { + if ($Region -like '*canada*') { switch ($Region) { - "canadacentral" { - $Result = "canadaeast" + 'canadacentral' { + $Result = 'canadaeast' } - "canadaeast" { - $Result = "canadacentral" + 'canadaeast' { + $Result = 'canadacentral' } Default { - $Result = "canadacentral" + $Result = 'canadacentral' } } - } - elseif($Region -like "*asia*") { + } elseif ($Region -like '*asia*') { switch ($Region) { - "eastasia" { - $Result = "southeastasia" + 'eastasia' { + $Result = 'southeastasia' } - "southeastasia" { - $Result = "eastasia" + 'southeastasia' { + $Result = 'eastasia' } Default { - $Result = "eastasia" + $Result = 'eastasia' } } - } - elseif($Region -like "*japan*") { + } elseif ($Region -like '*japan*') { switch ($Region) { - "japanwest" { - $Result = "japaneast" + 'japanwest' { + $Result = 'japaneast' } - "japaneast" { - $Result = "japanwest" + 'japaneast' { + $Result = 'japanwest' } Default { - $Result = "japanwest" + $Result = 'japanwest' } } - } - elseif($Region -like "*europe*") { + } elseif ($Region -like '*europe*') { switch ($Region) { - "northeurope" { - $Result = "westeurope" + 'northeurope' { + $Result = 'westeurope' } - "westeurope" { - $Result = "northeurope" + 'westeurope' { + $Result = 'northeurope' } Default { - $Result = "westeurope" + $Result = 'westeurope' } } - } - elseif($Region -like "*brazil*") { + } elseif ($Region -like '*brazil*') { switch ($Region) { - "brazilsouth" { - $Result = "brazilsoutheast" + 'brazilsouth' { + $Result = 'brazilsoutheast' } - "brazilsoutheast" { - $Result = "brazilsouth" + 'brazilsoutheast' { + $Result = 'brazilsouth' } Default { - $Result = "brazilsoutheast" + $Result = 'brazilsoutheast' } } - } - elseif($Region -like "*australia*") { + } elseif ($Region -like '*australia*') { switch ($Region) { - "australiaeast" { - $Result = "australiasoutheast" + 'australiaeast' { + $Result = 'australiasoutheast' } - "australiasoutheast" { - $Result = "australiaeast" + 'australiasoutheast' { + $Result = 'australiaeast' } - "australiacentral" { - $Result = "australiacentral2" + 'australiacentral' { + $Result = 'australiacentral2' } - "australiacentral2" { - $Result = "australiacentral" + 'australiacentral2' { + $Result = 'australiacentral' } Default { - $Result = "australiasoutheast" + $Result = 'australiasoutheast' } } - } - elseif($Region -like "*us*") { + } elseif ($Region -like '*us*') { switch ($Region) { - "eastus" { - $Result = "westus" + 'eastus' { + $Result = 'westus' } - "westus" { - $Result = "centralus" + 'westus' { + $Result = 'centralus' } - "eastus2" { - $Result = "centralus" + 'eastus2' { + $Result = 'centralus' } - "centralus" { - $Result = "eastus2" + 'centralus' { + $Result = 'eastus2' } - "northcentralus" { - $Result = "southcentralus" + 'northcentralus' { + $Result = 'southcentralus' } - "southcentralus" { - $Result = "northcentralus" + 'southcentralus' { + $Result = 'northcentralus' } - "westus2" { - $Result = "westcentralus" + 'westus2' { + $Result = 'westcentralus' } - "westcentralus" { - $Result = "westus2" + 'westcentralus' { + $Result = 'westus2' } - "westus3" { - $Result = "westcentralus" + 'westus3' { + $Result = 'westcentralus' } Default { - $Result = "westus" + $Result = 'westus' } } - } - elseif($Region -like "*india*") { + } elseif ($Region -like '*india*') { switch ($Region) { - "westindia" { - $Result = "southindia" + 'westindia' { + $Result = 'southindia' } - "centralindia" { - $Result = "southindia" + 'centralindia' { + $Result = 'southindia' } - "southindia" { - $Result = "centralindia" + 'southindia' { + $Result = 'centralindia' } Default { - $Result = "southindia" + $Result = 'southindia' } } - } - elseif($Region -like "*uk*") { + } elseif ($Region -like '*uk*') { switch ($Region) { - "uksouth" { - $Result = "ukwest" + 'uksouth' { + $Result = 'ukwest' } - "ukwest" { - $Result = "uksouth" + 'ukwest' { + $Result = 'uksouth' } Default { - $Result = "uksouth" + $Result = 'uksouth' } } - } - elseif($Region -like "*korea*") { + } elseif ($Region -like '*korea*') { switch ($Region) { - "koreacentral" { - $Result = "koreasouth" + 'koreacentral' { + $Result = 'koreasouth' } - "koreasouth" { - $Result = "koreacentral" + 'koreasouth' { + $Result = 'koreacentral' } Default { - $Result = "koreacentral" + $Result = 'koreacentral' } } - } - elseif($Region -like "*france*") { + } elseif ($Region -like '*france*') { switch ($Region) { - "francecentral" { - $Result = "francesouth" + 'francecentral' { + $Result = 'francesouth' } - "francesouth" { - $Result = "francecentral" + 'francesouth' { + $Result = 'francecentral' } Default { - $Result = "francecentral" + $Result = 'francecentral' } } - } - elseif($Region -like "*africa*") { + } elseif ($Region -like '*africa*') { switch ($Region) { - "southafricanorth" { - $Result = "southafricawest" + 'southafricanorth' { + $Result = 'southafricawest' } - "southafricawest" { - $Result = "southafricanorth" + 'southafricawest' { + $Result = 'southafricanorth' } Default { - $Result = "southafricanorth" + $Result = 'southafricanorth' } } - } - elseif($Region -like "*switzerland*") { + } elseif ($Region -like '*switzerland*') { switch ($Region) { - "switzerlandnorth" { - $Result = "switzerlandwest" + 'switzerlandnorth' { + $Result = 'switzerlandwest' } - "switzerlandwest" { - $Result = "switzerlandnorth" + 'switzerlandwest' { + $Result = 'switzerlandnorth' } Default { - $Result = "switzerlandwest" + $Result = 'switzerlandwest' } } - } - elseif($Region -like "*germany*") { + } elseif ($Region -like '*germany*') { switch ($Region) { - "germanynorth" { - $Result = "germanywestcentral" + 'germanynorth' { + $Result = 'germanywestcentral' } - "germanywestcentral" { - $Result = "germanynorth" + 'germanywestcentral' { + $Result = 'germanynorth' } Default { - $Result = "germanywestcentral" + $Result = 'germanywestcentral' } } - } - elseif($Region -like "*norway*") { + } elseif ($Region -like '*norway*') { switch ($Region) { - "norwaywest" { - $Result = "norwayeast" + 'norwaywest' { + $Result = 'norwayeast' } - "norwayeast" { - $Result = "norwaywest" + 'norwayeast' { + $Result = 'norwaywest' } Default { - $Result = "norwaywest" + $Result = 'norwaywest' } } - } - elseif($Region -like "*uae*") { + } elseif ($Region -like '*uae*') { switch ($Region) { - "uaecentral" { - $Result = "uaenorth" + 'uaecentral' { + $Result = 'uaenorth' } - "uaenorth" { - $Result = "uaecentral" + 'uaenorth' { + $Result = 'uaecentral' } Default { - $Result = "uaecentral" + $Result = 'uaecentral' } } } diff --git a/Tools/PowershellModule/src/Library/Get-WinGetManifest.ps1 b/Tools/PowershellModule/src/Library/Get-WinGetManifest.ps1 index e396f48a..7283d8a0 100644 --- a/Tools/PowershellModule/src/Library/Get-WinGetManifest.ps1 +++ b/Tools/PowershellModule/src/Library/Get-WinGetManifest.ps1 @@ -1,8 +1,7 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -Function Get-WinGetManifest -{ +Function Get-WinGetManifest { <# .SYNOPSIS Connects to the specified source REST API, or local file system path to retrieve the package manifests, returning @@ -59,33 +58,32 @@ Function Get-WinGetManifest #> [CmdletBinding(DefaultParameterSetName = 'Azure')] PARAM( - [Parameter(Position=0, Mandatory=$true, ParameterSetName="File")] [string]$Path, - [Parameter(Mandatory=$false,ParameterSetName="File")] [WinGetManifest]$PriorManifest = $null, - [Parameter(Position=0, Mandatory=$true, ParameterSetName="Azure")] [string]$FunctionName, - [Parameter(Position=1, Mandatory=$true, ParameterSetName="Azure", ValueFromPipeline=$true)][ValidateNotNullOrEmpty()] [string]$PackageIdentifier, - [Parameter(Mandatory=$false,ParameterSetName="Azure")] [string]$SubscriptionName = "" + [Parameter(Position = 0, Mandatory = $true, ParameterSetName = 'File')] [string]$Path, + [Parameter(Mandatory = $false, ParameterSetName = 'File')] [WinGetManifest]$PriorManifest = $null, + [Parameter(Position = 0, Mandatory = $true, ParameterSetName = 'Azure')] [string]$FunctionName, + [Parameter(Position = 1, Mandatory = $true, ParameterSetName = 'Azure', ValueFromPipeline = $true)][ValidateNotNullOrEmpty()] [string]$PackageIdentifier, + [Parameter(Mandatory = $false, ParameterSetName = 'Azure')] [string]$SubscriptionName = '' ) - BEGIN - { + BEGIN { [WinGetManifest[]] $Return = @() ############################### ## Determines the PowerShell Parameter Set that was used in the call of this Function. switch ($PsCmdlet.ParameterSetName) { - "Azure" { + 'Azure' { ############################### ## Connects to Azure, if not already connected. - Write-Verbose "Validating connection to azure, will attempt to connect if not already connected." + Write-Verbose 'Validating connection to azure, will attempt to connect if not already connected.' $Result = Connect-ToAzure -SubscriptionName $SubscriptionName - if(!($Result)) { - Write-Error "Failed to connect to Azure. Please run Connect-AzAccount to connect to Azure, or re-run the cmdlet and enter your credentials." -ErrorAction Stop + if (!($Result)) { + Write-Error 'Failed to connect to Azure. Please run Connect-AzAccount to connect to Azure, or re-run the cmdlet and enter your credentials.' -ErrorAction Stop } ############################### ## Gets Resource Group name of the Azure Function - Write-Verbose -Message "Determines the Azure Function Resource Group Name" - $ResourceGroupName = $(Get-AzFunctionApp).Where({$_.Name -eq $FunctionName}).ResourceGroupName - if(!$ResourceGroupName) { + Write-Verbose -Message 'Determines the Azure Function Resource Group Name' + $ResourceGroupName = $(Get-AzFunctionApp).Where({ $_.Name -eq $FunctionName }).ResourceGroupName + if (!$ResourceGroupName) { Write-Error "Failed to confirm Azure Function exists in Azure. Please verify and try again. Function Name: $FunctionName" -ErrorAction Stop } @@ -93,80 +91,78 @@ Function Get-WinGetManifest Write-Verbose -Message "Retrieving Azure Function Web Applications matching to: $FunctionName." $FunctionApp = Get-AzFunctionApp -ResourceGroupName $ResourceGroupName -Name $FunctionName - $FunctionAppId = $FunctionApp.Id + $FunctionAppId = $FunctionApp.Id $DefaultHostName = $FunctionApp.DefaultHostName - $TriggerName = "ManifestGet" - $ApiMethod = "Get" + $TriggerName = 'ManifestGet' + $ApiMethod = 'Get' ## Creates the API Post Header - $ApiHeader = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" - $ApiHeader.Add("Accept", 'application/json') + $ApiHeader = New-Object 'System.Collections.Generic.Dictionary[[String],[String]]' + $ApiHeader.Add('Accept', 'application/json') $FunctionKey = (Invoke-AzResourceAction -ResourceId "$FunctionAppId/functions/$TriggerName" -Action listkeys -Force).default - $ApiHeader.Add("x-functions-key", $FunctionKey) + $ApiHeader.Add('x-functions-key', $FunctionKey) } - "File" { + 'File' { ## Nothing to prepare } } } - PROCESS - { + PROCESS { switch ($PsCmdlet.ParameterSetName) { - "Azure" { - $AzFunctionURL = "https://" + $DefaultHostName + "/api/packageManifests/" + $PackageIdentifier + 'Azure' { + $AzFunctionURL = 'https://' + $DefaultHostName + '/api/packageManifests/' + $PackageIdentifier ## Publishes the Manifest to the Windows Package Manager REST source - Write-Verbose -Message "Invoking the REST API call." + Write-Verbose -Message 'Invoking the REST API call.' $Response = Invoke-RestMethod $AzFunctionURL -Headers $ApiHeader -Method $ApiMethod -ErrorVariable ErrorInvoke - if($ErrorInvoke) { + if ($ErrorInvoke) { $ErrorMessage = "Failed to get Manifest from $FunctionName. Verify the information you provided and try again." $ErrReturnObject = @{ - AzFunctionURL = $AzFunctionURL - ApiMethod = $ApiMethod - Response = $Response - InvokeError = $ErrorInvoke + AzFunctionURL = $AzFunctionURL + ApiMethod = $ApiMethod + Response = $Response + InvokeError = $ErrorInvoke } Write-Error -Message $ErrorMessage -TargetObject $ErrReturnObject - } - else { + } else { Write-Verbose "Found ($($Response.Data.Count)) Manifests that matched." - foreach ($ResponseData in $Response.Data){ + foreach ($ResponseData in $Response.Data) { Write-Verbose -Message "Parsing through the returned results: $ResponseData" $Return += [WinGetManifest]::CreateFromObject($ResponseData) Write-Information "Returned Manifest from JSON file: $($Return[-1].PackageIdentifier)" } } } - "File" { + 'File' { ## Convert to full path if applicable $Path = [System.IO.Path]::GetFullPath($Path, $pwd.Path) - $ManifestFileExists = Test-Path -Path $Path + $ManifestFileExists = Test-Path -Path $Path - if(!$ManifestFileExists) { + if (!$ManifestFileExists) { $ErrReturnObject = @{ FilePath = $Path ManifestFileExists = $ManifestFileExists } - Write-Error -Message "Target path did not point to an object." -TargetObject $ErrReturnObject + Write-Error -Message 'Target path did not point to an object.' -TargetObject $ErrReturnObject return } $PathItem = Get-Item $Path - $ManifestFile = "" - $ApplicationManifest = "" - $ManifestFileType = "" + $ManifestFile = '' + $ApplicationManifest = '' + $ManifestFileType = '' - if($PathItem.PSIsContainer) { + if ($PathItem.PSIsContainer) { ## $Path variable is pointing at a directory - $PathChildItemsJSON = Get-ChildItem -Path $Path -Filter "*.json" - $PathChildItemsYAML = Get-ChildItem -Path $Path -Filter "*.yaml" + $PathChildItemsJSON = Get-ChildItem -Path $Path -Filter '*.json' + $PathChildItemsYAML = Get-ChildItem -Path $Path -Filter '*.yaml' Write-Verbose -Message "Path pointed to a directory, found $($PathChildItemsJSON.count) JSON files, and $($PathChildItemsYAML.Count) YAML files." @@ -180,66 +176,60 @@ Function Get-WinGetManifest ## Validating found objects if ($PathChildItemsJSON.Count -eq 0 -and $PathChildItemsYAML.Count -eq 0) { ## No JSON or YAML files were found in the directory. - $ErrorMessage = "Directory does not contain any JSON or YAML files." + $ErrorMessage = 'Directory does not contain any JSON or YAML files.' Write-Error -Message $ErrorMessage -TargetObject $ErrReturnObject return - } - elseif ($PathChildItemsJSON.Count -gt 0 -and $PathChildItemsYAML.Count -gt 0) { + } elseif ($PathChildItemsJSON.Count -gt 0 -and $PathChildItemsYAML.Count -gt 0) { ## A combination of JSON and YAML Files were found. - $ErrorMessage = "Directory contains a combination of JSON and YAML files." + $ErrorMessage = 'Directory contains a combination of JSON and YAML files.' Write-Error -Message $ErrorMessage -TargetObject $ErrReturnObject return - } - elseif ($PathChildItemsJSON.Count -gt 1) { + } elseif ($PathChildItemsJSON.Count -gt 1) { ## More than one Package Manifest's JSON files was found. - $ErrorMessage = "Directory contains more than one JSON file." + $ErrorMessage = 'Directory contains more than one JSON file.' Write-Error -Message $ErrorMessage -TargetObject $ErrReturnObject return - } - elseif ($PathChildItemsJSON.Count -eq 1) { + } elseif ($PathChildItemsJSON.Count -eq 1) { ## Single JSON has been found in the target folder. - Write-Verbose -Message "Single JSON has been found in the specified directory." - $ManifestFile = $PathChildItemsJSON + Write-Verbose -Message 'Single JSON has been found in the specified directory.' + $ManifestFile = $PathChildItemsJSON $ApplicationManifest = Get-Content -Path $PathChildItemsJSON[0].FullName -Raw - $ManifestFileType = ".json" - } - elseif ($PathChildItemsYAML.Count -gt 0) { - Write-Verbose -Message "YAML has been found in the specified directory." + $ManifestFileType = '.json' + } elseif ($PathChildItemsYAML.Count -gt 0) { + Write-Verbose -Message 'YAML has been found in the specified directory.' ## YAML has been found in the target folder. - $ManifestFile = $PathChildItemsYAML - $ManifestFileType = ".yaml" + $ManifestFile = $PathChildItemsYAML + $ManifestFileType = '.yaml' } - } - else { + } else { ## $Path variable is pointing at a file Write-Verbose -Message "Retrieving the Package Manifest for: $Path" ## Gets the Manifest object and contents of the Manifest - identifying the manifest file extension. $ApplicationManifest = Get-Content -Path $Path -Raw - $ManifestFile = Get-Item -Path $Path - $ManifestFileType = $ManifestFile.Extension.ToLower() + $ManifestFile = Get-Item -Path $Path + $ManifestFileType = $ManifestFile.Extension.ToLower() Write-Verbose -Message "Retrieved content from the manifest ($($ManifestFile.Name))." } switch ($ManifestFileType) { ## If the path resolves to a JSON file - ".json" { + '.json' { ## Sets the return result to be the contents of the JSON file if the Manifest test passed. $Return += [WinGetManifest]::CreateFromString($ApplicationManifest) Write-Information "Returned Manifest from JSON file: $($Return[-1].PackageIdentifier)" } ## If the path resolves to a YAML file - ".yaml" { + '.yaml' { ## Directory - *.yaml files included within. - Write-Verbose -Message "YAML Files have been found in the target directory. Building a JSON manifest with found files." - if($PriorManifest){ - Write-Verbose "Prior manifest provided. New manifest will be merged with prior manifest." + Write-Verbose -Message 'YAML Files have been found in the target directory. Building a JSON manifest with found files.' + if ($PriorManifest) { + Write-Verbose 'Prior manifest provided. New manifest will be merged with prior manifest.' $Return += [WinGetManifest]::CreateFromString([Microsoft.WinGet.RestSource.PowershellSupport.YamlToRestConverter]::AddManifestToPackageManifest($Path, $PriorManifest.GetJson())) - } - else{ - Write-Verbose "Prior manifest not provided." - $Return += [WinGetManifest]::CreateFromString([Microsoft.WinGet.RestSource.PowershellSupport.YamlToRestConverter]::AddManifestToPackageManifest($Path, "")) + } else { + Write-Verbose 'Prior manifest not provided.' + $Return += [WinGetManifest]::CreateFromString([Microsoft.WinGet.RestSource.PowershellSupport.YamlToRestConverter]::AddManifestToPackageManifest($Path, '')) } Write-Information "Returned Manifest from JSON file: $($Return[-1].PackageIdentifier)" @@ -258,8 +248,7 @@ Function Get-WinGetManifest } } } - END - { + END { ## Returns results Write-Verbose -Message "Returning ($($Return.Count)) manifests based on search." return $Return diff --git a/Tools/PowershellModule/src/Library/New-MicrosoftEntraIdApp.ps1 b/Tools/PowershellModule/src/Library/New-MicrosoftEntraIdApp.ps1 index 0c13a830..bdfa5190 100644 --- a/Tools/PowershellModule/src/Library/New-MicrosoftEntraIdApp.ps1 +++ b/Tools/PowershellModule/src/Library/New-MicrosoftEntraIdApp.ps1 @@ -1,7 +1,6 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -Function New-MicrosoftEntraIdApp -{ +Function New-MicrosoftEntraIdApp { <# .SYNOPSIS Creates a new Microsoft Entra Id app registration to be used for WinGet rest source Microsoft Entra Id based authentication. @@ -20,18 +19,18 @@ Function New-MicrosoftEntraIdApp #> PARAM( - [Parameter(Position=0, Mandatory=$true)] [string]$Name + [Parameter(Position = 0, Mandatory = $true)] [string]$Name ) $Return = @{ - Result = $false - Resource = "" - ResourceScope = "" + Result = $false + Resource = '' + ResourceScope = '' } ## Normalize Microsoft Entra Id app name - $NormalizedName = $Name -replace "[^a-zA-Z0-9-()_.]", "" - if($Name -cne $NormalizedName) { + $NormalizedName = $Name -replace '[^a-zA-Z0-9-()_.]', '' + if ($Name -cne $NormalizedName) { $Name = $NormalizedName Write-Warning "Removed special characters from the Microsoft Entra Id app name (New Name: $Name)." } @@ -40,8 +39,7 @@ Function New-MicrosoftEntraIdApp Write-Information "Microsoft Entra Id app name to be created: $Name" $App = New-AzADApplication -DisplayName $Name -AvailableToOtherTenants $false - if (!$App) - { + if (!$App) { Write-Error "Failed to create Microsoft Entra Id app. Name: $Name" return $Return } @@ -49,32 +47,30 @@ Function New-MicrosoftEntraIdApp ## Add App Id Uri $AppId = $App.AppId $App = Update-AzADApplication -ApplicationId $AppId -IdentifierUri "api://$AppId" -ErrorVariable ErrorUpdate - if ($ErrorUpdate) - { + if ($ErrorUpdate) { Write-Error "Failed to add App Id Uri. Error: $ErrorUpdate" return $Return } ## Add Api scope $ScopeId = [guid]::NewGuid().ToString() - $ScopeName = "user_impersonation" + $ScopeName = 'user_impersonation' $Api = @{ oauth2PermissionScopes = @( @{ adminConsentDescription = "Sign in to access $Name WinGet rest source" - adminConsentDisplayName = "Access WinGet rest source" + adminConsentDisplayName = 'Access WinGet rest source' userConsentDescription = "Sign in to access $Name WinGet rest source" - userConsentDisplayName = "Access WinGet rest source" - id = $ScopeId - isEnabled = $true - type = "User" - value = $ScopeName + userConsentDisplayName = 'Access WinGet rest source' + id = $ScopeId + isEnabled = $true + type = 'User' + value = $ScopeName } ) } $App = Update-AzADApplication -ApplicationId $AppId -Api $Api -ErrorVariable ErrorUpdate - if ($ErrorUpdate) - { + if ($ErrorUpdate) { Write-Error "Failed to add Api scope. Error: $ErrorUpdate" return $Return } @@ -83,23 +79,22 @@ Function New-MicrosoftEntraIdApp $Api = @{ preAuthorizedApplications = @( @{ - appId = "7b8ea11a-7f45-4b3a-ab51-794d5863af15" + appId = '7b8ea11a-7f45-4b3a-ab51-794d5863af15' delegatedPermissionIds = @($ScopeId) } @{ - appId = "04b07795-8ddb-461a-bbee-02f9e1bf7b46" + appId = '04b07795-8ddb-461a-bbee-02f9e1bf7b46' delegatedPermissionIds = @($ScopeId) } @{ - appId = "1950a258-227b-4e31-a9cf-717495945fc2" + appId = '1950a258-227b-4e31-a9cf-717495945fc2' delegatedPermissionIds = @($ScopeId) } ) } $App = Update-AzADApplication -ApplicationId $AppId -Api $Api -ErrorVariable ErrorUpdate - if ($ErrorUpdate) - { - Write-Error "Failed to add authorized clients" + if ($ErrorUpdate) { + Write-Error 'Failed to add authorized clients' return $Return } diff --git a/Tools/PowershellModule/src/Library/New-WinGetSource.ps1 b/Tools/PowershellModule/src/Library/New-WinGetSource.ps1 index 04feaa00..f8c08137 100644 --- a/Tools/PowershellModule/src/Library/New-WinGetSource.ps1 +++ b/Tools/PowershellModule/src/Library/New-WinGetSource.ps1 @@ -1,7 +1,6 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -Function New-WinGetSource -{ +Function New-WinGetSource { <# .SYNOPSIS Creates a Windows Package Manager REST source in Azure for the storage of Windows Package Manager package Manifests. @@ -80,27 +79,27 @@ Function New-WinGetSource #> PARAM( - [Parameter(Position=0, Mandatory=$true)] [string]$Name, - [Parameter(Mandatory=$false)] [string]$ResourceGroup = "WinGetRestSource", - [Parameter(Mandatory=$false)] [string]$SubscriptionName = "", - [Parameter(Mandatory=$false)] [string]$Region = "westus", - [Parameter(Mandatory=$false)] [string]$TemplateFolderPath = "$PSScriptRoot\..\Data\ARMTemplates", - [Parameter(Mandatory=$false)] [string]$ParameterOutputPath = "$($(Get-Location).Path)\Parameters", - [Parameter(Mandatory=$false)] [string]$RestSourcePath = "$PSScriptRoot\..\Data\WinGet.RestSource.Functions.zip", - [Parameter(Mandatory=$false)] [string]$PublisherName = "", - [Parameter(Mandatory=$false)] [string]$PublisherEmail = "", - [ValidateSet("Developer", "Basic", "Enhanced")] - [Parameter(Mandatory=$false)] [string]$ImplementationPerformance = "Basic", - [ValidateSet("None", "MicrosoftEntraId")] - [Parameter(Mandatory=$false)] [string]$RestSourceAuthentication = "None", + [Parameter(Position = 0, Mandatory = $true)] [string]$Name, + [Parameter(Mandatory = $false)] [string]$ResourceGroup = 'WinGetRestSource', + [Parameter(Mandatory = $false)] [string]$SubscriptionName = '', + [Parameter(Mandatory = $false)] [string]$Region = 'westus', + [Parameter(Mandatory = $false)] [string]$TemplateFolderPath = "$PSScriptRoot\..\Data\ARMTemplates", + [Parameter(Mandatory = $false)] [string]$ParameterOutputPath = "$($(Get-Location).Path)\Parameters", + [Parameter(Mandatory = $false)] [string]$RestSourcePath = "$PSScriptRoot\..\Data\WinGet.RestSource.Functions.zip", + [Parameter(Mandatory = $false)] [string]$PublisherName = '', + [Parameter(Mandatory = $false)] [string]$PublisherEmail = '', + [ValidateSet('Developer', 'Basic', 'Enhanced')] + [Parameter(Mandatory = $false)] [string]$ImplementationPerformance = 'Basic', + [ValidateSet('None', 'MicrosoftEntraId')] + [Parameter(Mandatory = $false)] [string]$RestSourceAuthentication = 'None', [Parameter()] [switch]$CreateNewMicrosoftEntraIdAppRegistration, - [Parameter(Mandatory=$false)] [string]$MicrosoftEntraIdResource = "", - [Parameter(Mandatory=$false)] [string]$MicrosoftEntraIdResourceScope = "", + [Parameter(Mandatory = $false)] [string]$MicrosoftEntraIdResource = '', + [Parameter(Mandatory = $false)] [string]$MicrosoftEntraIdResourceScope = '', [Parameter()] [switch]$ShowConnectionInstructions, - [Parameter(Mandatory=$false)] [int]$MaxRetryCount = 5 + [Parameter(Mandatory = $false)] [int]$MaxRetryCount = 5 ) - if($ImplementationPerformance -eq "Developer") { + if ($ImplementationPerformance -eq 'Developer') { Write-Warning "The ""Developer"" build creates the Azure Cosmos DB Account with the ""Free-tier"" option selected which offset the total cost. Only 1 Cosmos DB Account per tenant can make use of this tier.`n" } @@ -121,8 +120,8 @@ Function New-WinGetSource ############################### ## Check Microsoft Entra Id input - if ($RestSourceAuthentication -eq "MicrosoftEntraId" -and !$CreateNewMicrosoftEntraIdAppRegistration -and !$MicrosoftEntraIdResource) { - Write-Error "When Microsoft Entra Id authentication is requested, either CreateNewMicrosoftEntraIdAppRegistration should be requested or MicrosoftEntraIdResource should be provided." + if ($RestSourceAuthentication -eq 'MicrosoftEntraId' -and !$CreateNewMicrosoftEntraIdAppRegistration -and !$MicrosoftEntraIdResource) { + Write-Error 'When Microsoft Entra Id authentication is requested, either CreateNewMicrosoftEntraIdAppRegistration should be requested or MicrosoftEntraIdResource should be provided.' return $false } @@ -131,30 +130,28 @@ Function New-WinGetSource $Result = New-Item -ItemType Directory -Path $ParameterOutputPath -Force if ($Result) { Write-Verbose -Message "Created Directory to contain the ARM Parameter files ($($Result.FullName))." - } - else { + } else { Write-Error "Failed to create ARM parameter files output path. Path: $ParameterOutputPath" return $false } ############################### ## Connects to Azure, if not already connected. - Write-Information "Validating connection to azure, will attempt to connect if not already connected." + Write-Information 'Validating connection to azure, will attempt to connect if not already connected.' $Result = Connect-ToAzure -SubscriptionName $SubscriptionName if (!($Result)) { - Write-Error "Failed to connect to Azure. Please run Connect-AzAccount to connect to Azure, or re-run the cmdlet and enter your credentials." + Write-Error 'Failed to connect to Azure. Please run Connect-AzAccount to connect to Azure, or re-run the cmdlet and enter your credentials.' return $false } ############################### ## Create new Microsoft Entra Id app registration if requested - if ($RestSourceAuthentication -eq "MicrosoftEntraId" -and $CreateNewMicrosoftEntraIdAppRegistration) { + if ($RestSourceAuthentication -eq 'MicrosoftEntraId' -and $CreateNewMicrosoftEntraIdAppRegistration) { $Result = New-MicrosoftEntraIdApp -Name $Name if (!$Result.Result) { - Write-Error "Failed to create new Microsoft Entra Id app registration." + Write-Error 'Failed to create new Microsoft Entra Id app registration.' return $false - } - else { + } else { $MicrosoftEntraIdResource = $Result.Resource $MicrosoftEntraIdResourceScope = $Result.ResourceScope } @@ -164,7 +161,7 @@ Function New-WinGetSource ## Creates the ARM files $ARMObjects = New-ARMParameterObjects -ParameterFolderPath $ParameterOutputPath -TemplateFolderPath $TemplateFolderPath -Name $Name -Region $Region -ImplementationPerformance $ImplementationPerformance -PublisherName $PublisherName -PublisherEmail $PublisherEmail -RestSourceAuthentication $RestSourceAuthentication -MicrosoftEntraIdResource $MicrosoftEntraIdResource -MicrosoftEntraIdResourceScope $MicrosoftEntraIdResourceScope if (!$ARMObjects) { - Write-Error "Failed to create ARM parameter objects." + Write-Error 'Failed to create ARM parameter objects.' return $false } @@ -180,7 +177,7 @@ Function New-WinGetSource ############################### ## Verifies ARM Parameters are correct. If any failed, the return results will contain failed objects. Otherwise, success. $Result = Test-ARMTemplates -ARMObjects $ARMObjects -ResourceGroup $ResourceGroup - if($Result){ + if ($Result) { $ErrReturnObject = @{ ARMObjects = $ARMObjects ResourceGroup = $ResourceGroup @@ -203,11 +200,10 @@ Function New-WinGetSource if (!$Result) { if ($Attempt -lt $MaxRetryCount) { $Retry = $true - Write-Verbose "Retrying deployment after 15 seconds." + Write-Verbose 'Retrying deployment after 15 seconds.' Start-Sleep -Seconds 15 - } - else { - Write-Error "Failed to create Azure resources for WinGet rest source." + } else { + Write-Error 'Failed to create Azure resources for WinGet rest source.' return $false } } @@ -215,13 +211,13 @@ Function New-WinGetSource ############################### ## Shows how to connect local Windows Package Manager Client to newly created REST source - if($ShowConnectionInstructions) { - $ApiManagementName = $ARMObjects.Where({$_.ObjectType -eq "ApiManagement"}).Parameters.Parameters.serviceName.value - $ApiManagementURL = (Get-AzApiManagement -Name $ApiManagementName -ResourceGroupName $ResourceGroup).RuntimeUrl + if ($ShowConnectionInstructions) { + $ApiManagementName = $ARMObjects.Where({ $_.ObjectType -eq 'ApiManagement' }).Parameters.Parameters.serviceName.value + $ApiManagementURL = (Get-AzApiManagement -Name $ApiManagementName -ResourceGroupName $ResourceGroup).RuntimeUrl ## Post script Run Informational: #### Instructions on how to add the REST source to your Windows Package Manager Client - Write-Information -MessageData "Use the following command to register the new REST source with your Windows Package Manager Client:" -InformationAction Continue + Write-Information -MessageData 'Use the following command to register the new REST source with your Windows Package Manager Client:' -InformationAction Continue Write-Information -MessageData " winget source add -n ""$Name"" -a ""$ApiManagementURL/winget/"" -t ""Microsoft.Rest""" -InformationAction Continue #### For more information about how to use the solution, visit the aka.ms link. diff --git a/Tools/PowershellModule/src/Library/Remove-WinGetManifest.ps1 b/Tools/PowershellModule/src/Library/Remove-WinGetManifest.ps1 index 97df1f49..a0d591e2 100644 --- a/Tools/PowershellModule/src/Library/Remove-WinGetManifest.ps1 +++ b/Tools/PowershellModule/src/Library/Remove-WinGetManifest.ps1 @@ -1,7 +1,6 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -Function Remove-WinGetManifest -{ +Function Remove-WinGetManifest { <# .SYNOPSIS Removes a Manifest file from the Azure REST source @@ -31,28 +30,27 @@ Function Remove-WinGetManifest #> PARAM( - [Parameter(Position=0, Mandatory=$true)] [string]$FunctionName, - [Parameter(Position=1, Mandatory=$true, ValueFromPipelineByPropertyName=$true)] [string]$PackageIdentifier, - [Parameter(Mandatory=$false, ValueFromPipelineByPropertyName=$true)] [string]$PackageVersion = "", - [Parameter(Mandatory=$false)] [string]$SubscriptionName = "" + [Parameter(Position = 0, Mandatory = $true)] [string]$FunctionName, + [Parameter(Position = 1, Mandatory = $true, ValueFromPipelineByPropertyName = $true)] [string]$PackageIdentifier, + [Parameter(Mandatory = $false, ValueFromPipelineByPropertyName = $true)] [string]$PackageVersion = '', + [Parameter(Mandatory = $false)] [string]$SubscriptionName = '' ) - BEGIN - { + BEGIN { [PSCustomObject[]]$Return = @() ############################### ## Connects to Azure, if not already connected. - Write-Verbose -Message "Validating connection to azure, will attempt to connect if not already connected." + Write-Verbose -Message 'Validating connection to azure, will attempt to connect if not already connected.' $Result = Connect-ToAzure -SubscriptionName $SubscriptionName - if(!($Result)) { - Write-Error "Failed to connect to Azure. Please run Connect-AzAccount to connect to Azure, or re-run the cmdlet and enter your credentials." -ErrorAction Stop + if (!($Result)) { + Write-Error 'Failed to connect to Azure. Please run Connect-AzAccount to connect to Azure, or re-run the cmdlet and enter your credentials.' -ErrorAction Stop } ############################### ## Gets Resource Group name of the Azure Function - Write-Verbose -Message "Determines the Azure Function Resource Group Name" - $ResourceGroupName = $(Get-AzFunctionApp).Where({$_.Name -eq $FunctionName}).ResourceGroupName - if(!$ResourceGroupName) { + Write-Verbose -Message 'Determines the Azure Function Resource Group Name' + $ResourceGroupName = $(Get-AzFunctionApp).Where({ $_.Name -eq $FunctionName }).ResourceGroupName + if (!$ResourceGroupName) { Write-Error "Failed to confirm Azure Function exists in Azure. Please verify and try again. Function Name: $FunctionName" -ErrorAction Stop } @@ -60,62 +58,57 @@ Function Remove-WinGetManifest ## REST api call ## Specifies the REST api call that will be performed - $TriggerNameManifestDelete = "ManifestDelete" - $TriggerNameVersionDelete = "VersionDelete" + $TriggerNameManifestDelete = 'ManifestDelete' + $TriggerNameVersionDelete = 'VersionDelete' - $ApiMethod = "Delete" + $ApiMethod = 'Delete' $FunctionApp = Get-AzFunctionApp -ResourceGroupName $ResourceGroupName -Name $FunctionName ## can function key be part of the header - $FunctionAppId = $FunctionApp.Id + $FunctionAppId = $FunctionApp.Id $DefaultHostName = $FunctionApp.DefaultHostName $FunctionKeyManifestDelete = (Invoke-AzResourceAction -ResourceId "$FunctionAppId/functions/$TriggerNameManifestDelete" -Action listkeys -Force).default $FunctionKeyVersionDelete = (Invoke-AzResourceAction -ResourceId "$FunctionAppId/functions/$TriggerNameVersionDelete" -Action listkeys -Force).default ## Creates the API Post Header - $ApiHeader = New-Object "System.Collections.Generic.Dictionary[[String],[String]]" - $ApiHeader.Add("Accept", 'application/json') + $ApiHeader = New-Object 'System.Collections.Generic.Dictionary[[String],[String]]' + $ApiHeader.Add('Accept', 'application/json') - $AzFunctionURLBase = "https://" + $DefaultHostName + "/api/" + $AzFunctionURLBase = 'https://' + $DefaultHostName + '/api/' } - PROCESS - { - Write-Verbose -Message "Constructing the REST API call for removal of manifest." + PROCESS { + Write-Verbose -Message 'Constructing the REST API call for removal of manifest.' $AzFunctionURL = $AzFunctionURLBase - if([string]::IsNullOrWhiteSpace($PackageVersion)) { - $AzFunctionURL += "packageManifests/" + $PackageIdentifier - $ApiHeader["x-functions-key"] = $FunctionKeyManifestDelete - } - else { - $AzFunctionURL += "packages/" + $PackageIdentifier + "/versions/" + $PackageVersion - $ApiHeader["x-functions-key"] = $FunctionKeyVersionDelete + if ([string]::IsNullOrWhiteSpace($PackageVersion)) { + $AzFunctionURL += 'packageManifests/' + $PackageIdentifier + $ApiHeader['x-functions-key'] = $FunctionKeyManifestDelete + } else { + $AzFunctionURL += 'packages/' + $PackageIdentifier + '/versions/' + $PackageVersion + $ApiHeader['x-functions-key'] = $FunctionKeyVersionDelete } $Response = Invoke-RestMethod $AzFunctionURL -Headers $ApiHeader -Method $ApiMethod -ErrorVariable ErrorInvoke - if($ErrorInvoke) { + if ($ErrorInvoke) { $ErrorMessage = "Failed to remove Manifest from $FunctionName. Verify the information you provided and try again." $ErrReturnObject = @{ - AzFunctionURL = $AzFunctionURL - ApiMethod = $ApiMethod - Response = $Response - InvokeError = $ErrorInvoke + AzFunctionURL = $AzFunctionURL + ApiMethod = $ApiMethod + Response = $Response + InvokeError = $ErrorInvoke } Write-Error -Message $ErrorMessage -TargetObject $ErrReturnObject - } - else - { + } else { $Return += [PSCustomObject]@{ PackageIdentidier = $PackageIdentifier - PackageVersion = $PackageVersion + PackageVersion = $PackageVersion } } } - END - { + END { return $Return } } \ No newline at end of file diff --git a/Tools/PowershellModule/src/Library/Test-ARMTemplates.ps1 b/Tools/PowershellModule/src/Library/Test-ARMTemplates.ps1 index 08f5cbcb..79133fe4 100644 --- a/Tools/PowershellModule/src/Library/Test-ARMTemplates.ps1 +++ b/Tools/PowershellModule/src/Library/Test-ARMTemplates.ps1 @@ -1,7 +1,6 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -Function Test-ARMTemplates -{ +Function Test-ARMTemplates { <# .SYNOPSIS Validates that the parameter files have been build correctly, matches to the template files, and can be used to build Azure @@ -26,24 +25,23 @@ Function Test-ARMTemplates #> PARAM( - [Parameter(Position=0, Mandatory=$true)] [array] $ARMObjects, - [Parameter(Position=1, Mandatory=$true)] [string] $ResourceGroup + [Parameter(Position = 0, Mandatory = $true)] [array] $ARMObjects, + [Parameter(Position = 1, Mandatory = $true)] [string] $ResourceGroup ) - Write-Information "Verifying the ARM Resource Templates and Parameters are valid:" + Write-Information 'Verifying the ARM Resource Templates and Parameters are valid:' [PSCustomObject[]]$Return = @() ## Parses through all ARM Parameter objects to validate they are properly configured. - foreach($Object in $ARMObjects) - { + foreach ($Object in $ARMObjects) { ## Validates that each ARM object will work. Write-Information "Validation testing on ARM Resource ($($Object.ObjectType))." $AzResourceResult = Test-AzResourceGroupDeployment -ResourceGroupName $ResourceGroup -Mode Complete -TemplateFile $Object.TemplatePath -TemplateParameterFile $Object.ParameterPath ## If the ARM object fails validation, report error to screen. - if($AzResourceResult) { + if ($AzResourceResult) { [PSCustomObject]$ErrReturnObject = [PSCustomObject]@{ - ARMObject = $Object + ARMObject = $Object TestResult = $AzResourceResult } diff --git a/Tools/PowershellModule/src/Library/Test-ConnectionToAzure.ps1 b/Tools/PowershellModule/src/Library/Test-ConnectionToAzure.ps1 index 5eaa734e..ff1910a2 100644 --- a/Tools/PowershellModule/src/Library/Test-ConnectionToAzure.ps1 +++ b/Tools/PowershellModule/src/Library/Test-ConnectionToAzure.ps1 @@ -1,7 +1,6 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -Function Test-ConnectionToAzure -{ +Function Test-ConnectionToAzure { <# .SYNOPSIS Validates that a connection is existing to Azure and/or Azure Subscription Name / Id. @@ -32,32 +31,29 @@ Function Test-ConnectionToAzure #> PARAM( - [Parameter(Mandatory=$false)] [string] $SubscriptionName = "", - [Parameter(Mandatory=$false)] [string] $SubscriptionId = "" + [Parameter(Mandatory = $false)] [string] $SubscriptionName = '', + [Parameter(Mandatory = $false)] [string] $SubscriptionId = '' ) - $Result = $false + $Result = $false $AzContext = Get-AzContext - if($AzContext) { - if($SubscriptionName -and $AzContext.Subscription.Name -ne $SubscriptionName) { + if ($AzContext) { + if ($SubscriptionName -and $AzContext.Subscription.Name -ne $SubscriptionName) { ## If Subscription Name paramter is passed in, and the value doesn't match current connection return $false Write-Error "Connection to an unmatched Subscription in Azure. Not connected to $SubscriptionName" $Result = $false - } - elseif($SubscriptionId -and $AzContext.Subscription.Id -ne $SubscriptionId) { + } elseif ($SubscriptionId -and $AzContext.Subscription.Id -ne $SubscriptionId) { ## If Subscription Id paramter is passed in, and the value doesn't match current connection return $false Write-Error "Connection to an unmatched Subscription in Azure. Not connected to $SubscriptionId" $Result = $false - } - else { - Write-Information "Connected to Azure" + } else { + Write-Information 'Connected to Azure' $Result = $true } - } - else { + } else { ## Not currently connected to Azure - Write-Error "Not connected to Azure, please connect to your Azure Subscription" + Write-Error 'Not connected to Azure, please connect to your Azure Subscription' $Result = $false } diff --git a/Tools/PowershellModule/src/Library/Test-PowerShellModuleExist.ps1 b/Tools/PowershellModule/src/Library/Test-PowerShellModuleExist.ps1 index fd831cc3..9d27a321 100644 --- a/Tools/PowershellModule/src/Library/Test-PowerShellModuleExist.ps1 +++ b/Tools/PowershellModule/src/Library/Test-PowerShellModuleExist.ps1 @@ -1,7 +1,6 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -Function Test-PowerShellModuleExist -{ +Function Test-PowerShellModuleExist { <# .SYNOPSIS Verifies that the provided Modules are installed. @@ -28,15 +27,15 @@ Function Test-PowerShellModuleExist #> [CmdletBinding(DefaultParameterSetName = 'Multiple')] PARAM( - [Parameter(Position=0, Mandatory=$true, ParameterSetName="Single")] [string]$Name, - [Parameter(Position=0, Mandatory=$true, ParameterSetName="Multiple")] [string[]]$Modules + [Parameter(Position = 0, Mandatory = $true, ParameterSetName = 'Single')] [string]$Name, + [Parameter(Position = 0, Mandatory = $true, ParameterSetName = 'Multiple')] [string[]]$Modules ) ## Validation result to be returned is True until proven otherwise. $ValidationStatus = $true switch ($PsCmdlet.ParameterSetName) { - "Multiple" { + 'Multiple' { foreach ($RequiredModule in $RequiredModules) { ## Tests if the module is installed $Result = Test-PowerShellModuleExist -Name $RequiredModule @@ -44,9 +43,9 @@ Function Test-PowerShellModuleExist $ValidationStatus = $ValidationStatus -and $Result } } - "Single" { + 'Single' { ## Determines if the PowerShell Module is installed - if(!$(Get-Module -ListAvailable -Name $RequiredModule)) { + if (!$(Get-Module -ListAvailable -Name $RequiredModule)) { $ValidationStatus = $false Write-Warning -Message "Missing required PowerShell modules. Run the following command to install the missing modules: Install-Module $RequiredModule" } diff --git a/Tools/PowershellModule/src/Library/Test-WinGetManifest.ps1 b/Tools/PowershellModule/src/Library/Test-WinGetManifest.ps1 index b75d71f6..c1b5b2c4 100644 --- a/Tools/PowershellModule/src/Library/Test-WinGetManifest.ps1 +++ b/Tools/PowershellModule/src/Library/Test-WinGetManifest.ps1 @@ -1,7 +1,6 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -Function Test-WinGetManifest -{ +Function Test-WinGetManifest { <# .SYNOPSIS [TODO: Stub for a backlog issue, essentially does nothing today.] @@ -29,29 +28,26 @@ Function Test-WinGetManifest #> [CmdletBinding(DefaultParameterSetName = 'File')] PARAM( - [Parameter(Position=0, Mandatory=$true, ParameterSetName="File")] [string]$Path, - [Parameter(Position=0, Mandatory=$true, ParameterSetName="Object")] [WinGetManifest]$Manifest + [Parameter(Position = 0, Mandatory = $true, ParameterSetName = 'File')] [string]$Path, + [Parameter(Position = 0, Mandatory = $true, ParameterSetName = 'Object')] [WinGetManifest]$Manifest ) $Return = $false switch ($($PSCmdlet.ParameterSetName)) { - "File"{ + 'File' { ## Convert to full path if applicable $Path = [System.IO.Path]::GetFullPath($Path, $pwd.Path) $PathFound = Test-Path -Path $Path - if ($PathFound) - { + if ($PathFound) { ## Construct $Manifest from path then validate $Return = $true - } - else - { + } else { Write-Error "Manifest path not found: $Path" } } - "Object" { + 'Object' { ## Validate manifest $Return = $true } diff --git a/Tools/PowershellModule/src/Library/Update-WinGetSource.ps1 b/Tools/PowershellModule/src/Library/Update-WinGetSource.ps1 index 5239a63a..f27def4c 100644 --- a/Tools/PowershellModule/src/Library/Update-WinGetSource.ps1 +++ b/Tools/PowershellModule/src/Library/Update-WinGetSource.ps1 @@ -1,7 +1,6 @@ # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. -Function Update-WinGetSource -{ +Function Update-WinGetSource { <# .SYNOPSIS Updates a Windows Package Manager REST source in Azure for the storage of Windows Package Manager package Manifests. @@ -82,22 +81,22 @@ Function Update-WinGetSource #> PARAM( - [Parameter(Mandatory=$false)] [string]$Name, - [Parameter(Mandatory=$false)] [string]$ResourceGroup = "WinGetRestSource", - [Parameter(Mandatory=$false)] [string]$SubscriptionName = "", - [Parameter(Mandatory=$false)] [string]$TemplateFolderPath = "$PSScriptRoot\..\Data\ARMTemplates", - [Parameter(Mandatory=$false)] [string]$ParameterOutputPath = "$($(Get-Location).Path)\Parameters", - [Parameter(Mandatory=$false)] [string]$RestSourcePath = "$PSScriptRoot\..\Data\WinGet.RestSource.Functions.zip", - [Parameter(Mandatory=$false)] [string]$PublisherName = "", - [Parameter(Mandatory=$false)] [string]$PublisherEmail = "", - [ValidateSet("Developer", "Basic", "Enhanced")] - [Parameter(Mandatory=$false)] [string]$ImplementationPerformance = "Basic", - [ValidateSet("None", "MicrosoftEntraId")] - [Parameter(Mandatory=$false)] [string]$RestSourceAuthentication = "None", - [Parameter(Mandatory=$false)] [string]$MicrosoftEntraIdResource = "", - [Parameter(Mandatory=$false)] [string]$MicrosoftEntraIdResourceScope = "", - [Parameter(Mandatory=$false)] [int]$MaxRetryCount = 3, - [Parameter(Mandatory=$false)] [string]$FunctionName = "", + [Parameter(Mandatory = $false)] [string]$Name, + [Parameter(Mandatory = $false)] [string]$ResourceGroup = 'WinGetRestSource', + [Parameter(Mandatory = $false)] [string]$SubscriptionName = '', + [Parameter(Mandatory = $false)] [string]$TemplateFolderPath = "$PSScriptRoot\..\Data\ARMTemplates", + [Parameter(Mandatory = $false)] [string]$ParameterOutputPath = "$($(Get-Location).Path)\Parameters", + [Parameter(Mandatory = $false)] [string]$RestSourcePath = "$PSScriptRoot\..\Data\WinGet.RestSource.Functions.zip", + [Parameter(Mandatory = $false)] [string]$PublisherName = '', + [Parameter(Mandatory = $false)] [string]$PublisherEmail = '', + [ValidateSet('Developer', 'Basic', 'Enhanced')] + [Parameter(Mandatory = $false)] [string]$ImplementationPerformance = 'Basic', + [ValidateSet('None', 'MicrosoftEntraId')] + [Parameter(Mandatory = $false)] [string]$RestSourceAuthentication = 'None', + [Parameter(Mandatory = $false)] [string]$MicrosoftEntraIdResource = '', + [Parameter(Mandatory = $false)] [string]$MicrosoftEntraIdResourceScope = '', + [Parameter(Mandatory = $false)] [int]$MaxRetryCount = 3, + [Parameter(Mandatory = $false)] [string]$FunctionName = '', [Parameter()] [switch]$PublishAzureFunctionOnly ) @@ -119,17 +118,16 @@ Function Update-WinGetSource $Result = New-Item -ItemType Directory -Path $ParameterOutputPath -Force if ($Result) { Write-Verbose -Message "Created Directory to contain the ARM Parameter files ($($Result.FullName))." - } - else { + } else { Write-Error "Failed to create ARM parameter files output path. Path: $ParameterOutputPath" return $false } ## Connects to Azure, if not already connected. - Write-Information "Validating connection to azure, will attempt to connect if not already connected." + Write-Information 'Validating connection to azure, will attempt to connect if not already connected.' $Result = Connect-ToAzure -SubscriptionName $SubscriptionName if (!($Result)) { - Write-Error "Failed to connect to Azure. Please run Connect-AzAccount to connect to Azure, or re-run the cmdlet and enter your credentials." + Write-Error 'Failed to connect to Azure. Please run Connect-AzAccount to connect to Azure, or re-run the cmdlet and enter your credentials.' return $false } @@ -143,17 +141,17 @@ Function Update-WinGetSource if ($PublishAzureFunctionOnly) { if ([string]::IsNullOrWhiteSpace($FunctionName)) { - Write-Error "FunctionName is null or empty" + Write-Error 'FunctionName is null or empty' return $false } - Write-Information -MessageData "Publishing function files to the Azure Function." + Write-Information -MessageData 'Publishing function files to the Azure Function.' $DeployResult = Publish-AzWebApp -ArchivePath $RestSourcePath -ResourceGroupName $ResourceGroup -Name $FunctionName -Force -ErrorVariable DeployError ## Verifies that no error occured when publishing the Function App if ($DeployError -or !$DeployResult) { $ErrReturnObject = @{ - DeployError = $DeployError + DeployError = $DeployError DeployResult = $DeployResult } @@ -162,34 +160,33 @@ Function Update-WinGetSource } ## Restart the Function App - Write-Verbose "Restarting Azure Function." + Write-Verbose 'Restarting Azure Function.' if (!$(Restart-AzFunctionApp -Name $FunctionName -ResourceGroupName $ResourceGroup -Force -PassThru)) { Write-Error "Failed to restart Function App. Name: $FunctionName" return $false } - } - else { + } else { if ([string]::IsNullOrWhiteSpace($Name)) { - Write-Error "Name is null or empty" + Write-Error 'Name is null or empty' return $false } ## Check Microsoft Entra Id input - if ($RestSourceAuthentication -eq "MicrosoftEntraId" -and !$MicrosoftEntraIdResource) { - Write-Error "When Microsoft Entra Id authentication is requested, MicrosoftEntraIdResource should be provided." + if ($RestSourceAuthentication -eq 'MicrosoftEntraId' -and !$MicrosoftEntraIdResource) { + Write-Error 'When Microsoft Entra Id authentication is requested, MicrosoftEntraIdResource should be provided.' return $false } ## Creates the ARM files $ARMObjects = New-ARMParameterObjects -ParameterFolderPath $ParameterOutputPath -TemplateFolderPath $TemplateFolderPath -Name $Name -Region $Region -ImplementationPerformance $ImplementationPerformance -PublisherName $PublisherName -PublisherEmail $PublisherEmail -RestSourceAuthentication $RestSourceAuthentication -MicrosoftEntraIdResource $MicrosoftEntraIdResource -MicrosoftEntraIdResourceScope $MicrosoftEntraIdResourceScope -ForUpdate if (!$ARMObjects) { - Write-Error "Failed to create ARM parameter objects." + Write-Error 'Failed to create ARM parameter objects.' return $false } ## Verifies ARM Parameters are correct $Result = Test-ARMTemplates -ARMObjects $ARMObjects -ResourceGroup $ResourceGroup - if($Result){ + if ($Result) { $ErrReturnObject = @{ ARMObjects = $ARMObjects ResourceGroup = $ResourceGroup @@ -211,11 +208,10 @@ Function Update-WinGetSource if (!$Result) { if ($Attempt -lt $MaxRetryCount) { $Retry = $true - Write-Verbose "Retrying deployment after 15 seconds." + Write-Verbose 'Retrying deployment after 15 seconds.' Start-Sleep -Seconds 15 - } - else { - Write-Error "Failed to create Azure resources for WinGet rest source." + } else { + Write-Error 'Failed to create Azure resources for WinGet rest source.' return $false } } diff --git a/Tools/PowershellModule/src/Library/WinGetManifest.ps1 b/Tools/PowershellModule/src/Library/WinGetManifest.ps1 index d59ff20c..3892340a 100644 --- a/Tools/PowershellModule/src/Library/WinGetManifest.ps1 +++ b/Tools/PowershellModule/src/Library/WinGetManifest.ps1 @@ -3,8 +3,7 @@ ## Classes representing WinGet manifest -class WinGetAgreement -{ +class WinGetAgreement { [string]$AgreementLabel [string]$Agreement [string]$AgreementUrl @@ -12,16 +11,14 @@ class WinGetAgreement WinGetAgreement () {} } -class WinGetDocumentation -{ +class WinGetDocumentation { [string]$DocumentLabel [string]$DocumentUrl WinGetDocumentation () {} } -class WinGetIcon -{ +class WinGetIcon { [string]$IconUrl [string]$IconFileType [string]$IconResolution @@ -31,8 +28,7 @@ class WinGetIcon WinGetIcon () {} } -class WinGetLocale -{ +class WinGetLocale { [string]$PackageLocale [string]$Publisher [string]$PublisherUrl @@ -62,8 +58,7 @@ class WinGetLocale WinGetLocale () {} } -class WinGetInstallerSwitch -{ +class WinGetInstallerSwitch { [string]$Silent [string]$SilentWithProgress [string]$Interactive @@ -76,8 +71,7 @@ class WinGetInstallerSwitch WinGetInstallerSwitch () {} } -class WinGetExpectedReturnCode -{ +class WinGetExpectedReturnCode { [long]$InstallerReturnCode [string]$ReturnResponse [string]$ReturnResponseUrl @@ -85,16 +79,14 @@ class WinGetExpectedReturnCode WinGetExpectedReturnCode () {} } -class WinGetPackageDependency -{ +class WinGetPackageDependency { [string]$PackageIdentifier [string]$MinimumVersion WinGetPackageDependency () {} } -class WinGetDependencies -{ +class WinGetDependencies { [string[]]$WindowsFeatures [string[]]$WindowsLibraries [WinGetPackageDependency[]]$PackageDependencies @@ -103,8 +95,7 @@ class WinGetDependencies WinGetDependencies () {} } -class WinGetAppsAndFeaturesEntry -{ +class WinGetAppsAndFeaturesEntry { [string]$DisplayName [string]$Publisher [string]$DisplayVersion @@ -115,24 +106,21 @@ class WinGetAppsAndFeaturesEntry WinGetAppsAndFeaturesEntry () {} } -class WinGetMarkets -{ +class WinGetMarkets { [string[]]$AllowedMarkets [string[]]$ExcludedMarkets WinGetMarkets () {} } -class WinGetNestedInstallerFile -{ +class WinGetNestedInstallerFile { [string]$RelativeFilePath [string]$PortableCommandAlias WinGetNestedInstallerFile () {} } -class WinGetInstallationMetadataFile -{ +class WinGetInstallationMetadataFile { [string]$RelativeFilePath [string]$FileSha256 [string]$FileType @@ -142,16 +130,14 @@ class WinGetInstallationMetadataFile WinGetInstallationMetadataFile () {} } -class WinGetInstallationMetadata -{ +class WinGetInstallationMetadata { [string]$DefaultInstallLocation [WinGetInstallationMetadataFile[]]$Files WinGetInstallationMetadata () {} } -class WinGetInstaller -{ +class WinGetInstaller { [string]$InstallerIdentifier [string]$InstallerSha256 [string]$InstallerUrl @@ -188,16 +174,15 @@ class WinGetInstaller [WinGetNestedInstallerFile[]]$NestedInstallerFiles [Nullable[bool]]$DisplayInstallWarnings [string[]]$UnsupportedArguments - [WinGetInstallationMetadata]$InstallationMetadata - [Nullable[bool]]$DownloadCommandProhibited - [string]$RepairBehavior + [WinGetInstallationMetadata]$InstallationMetadata + [Nullable[bool]]$DownloadCommandProhibited + [string]$RepairBehavior [Nullable[bool]]$ArchiveBinariesDependOnPath WinGetInstaller () {} } -class WinGetVersion -{ +class WinGetVersion { [string]$PackageVersion [string]$Channel [WinGetLocale] $DefaultLocale @@ -207,15 +192,13 @@ class WinGetVersion WinGetVersion () {} } -class WinGetManifest -{ +class WinGetManifest { [string] $PackageIdentifier [WinGetVersion[]] $Versions WinGetManifest () {} - [string] GetJson () - { + [string] GetJson () { ## Not using ConvertTo-Json here since we want more control on null property handling $options = [System.Text.Json.JsonSerializerOptions]::new() $options.WriteIndented = $false @@ -227,18 +210,16 @@ class WinGetManifest return [System.Text.Json.JsonSerializer]::Serialize($this, $options) } - static [WinGetManifest] CreateFromString ([string] $a) - { - Write-Verbose -Message "Creating a WinGetManifest object from String." + static [WinGetManifest] CreateFromString ([string] $a) { + Write-Verbose -Message 'Creating a WinGetManifest object from String.' $options = [System.Text.Json.JsonSerializerOptions]::new() return [System.Text.Json.JsonSerializer]::Deserialize($a, [WinGetManifest], $options) } - static [WinGetManifest] CreateFromObject ([psobject] $a) - { - Write-Verbose -Message "Creating a WinGetManifest object from PsObject object." + static [WinGetManifest] CreateFromObject ([psobject] $a) { + Write-Verbose -Message 'Creating a WinGetManifest object from PsObject object.' $json = ConvertTo-Json $a -Depth 16 -Compress diff --git a/Tools/PowershellModule/src/Microsoft.WinGet.RestSource.psd1 b/Tools/PowershellModule/src/Microsoft.WinGet.RestSource.psd1 index 06770529..e8c730c4 100644 --- a/Tools/PowershellModule/src/Microsoft.WinGet.RestSource.psd1 +++ b/Tools/PowershellModule/src/Microsoft.WinGet.RestSource.psd1 @@ -6,58 +6,61 @@ @{ # Script module or binary module file associated with this manifest. - RootModule = 'Microsoft.WinGet.RestSource.psm1' + RootModule = 'Microsoft.WinGet.RestSource.psm1' # Version number of this module. - ModuleVersion = '0.1.0' + ModuleVersion = '0.1.0' # Compatible PowerShell edition CompatiblePSEditions = @('Core') # ID used to uniquely identify this module - GUID = 'b70c845d-ddb1-4454-bfc2-a874783c2d04' + GUID = 'b70c845d-ddb1-4454-bfc2-a874783c2d04' # Author of this module - Author = 'Microsoft Corporation' + Author = 'Microsoft Corporation' # Company or vendor of this module - CompanyName = 'Microsoft Corporation' + CompanyName = 'Microsoft Corporation' # Copyright statement for this module - Copyright = '(c) Microsoft Corporation. All rights reserved.' + Copyright = '(c) Microsoft Corporation. All rights reserved.' # Description of the functionality provided by this module - Description = 'This module provides support for working with Windows Package Manager REST based sources.' + Description = 'This module provides support for working with Windows Package Manager REST based sources.' # Minimum version of the PowerShell engine required by this module - PowerShellVersion = '7.4' + PowerShellVersion = '7.4' # Required modules. # Due to issue https://github.com/PowerShell/PowerShell/issues/11190, using RequiredModules will greatly slow down the import module. We'll handle them manually in psm1. # RequiredModules = @('Az') # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export. - FunctionsToExport = @("Add-WinGetManifest", "Get-WinGetManifest", "Find-WinGetManifest", "Remove-WinGetManifest", "New-WinGetSource", "Update-WinGetSource") + FunctionsToExport = @('Add-WinGetManifest', 'Get-WinGetManifest', 'Find-WinGetManifest', 'Remove-WinGetManifest', 'New-WinGetSource', 'Update-WinGetSource') # Cmdlets to export from this module, for best performance, do not use wild cards and do not delete the entry, use an empty array if there are no cmdlets to export. - CmdletsToExport = @() + CmdletsToExport = @() # Variables to export from this module - VariablesToExport = '*' + VariablesToExport = '*' # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export. - AliasesToExport = @() + AliasesToExport = @() # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell. - PrivateData = @{ + PrivateData = @{ PSData = @{ # Tags applied to this module. These help with module discovery in online galleries. - Tags = @( + Tags = @( 'PSEdition_Core', 'WindowsPackageManager', 'WinGet' ) + # A URL to the license for this module. + LicenseUri = 'https://github.com/microsoft/winget-cli-restsource/blob/main/LICENSE' + # A URL to the main website for this project. ProjectUri = 'https://github.com/microsoft/winget-cli-restsource' diff --git a/Tools/PowershellModule/src/Microsoft.WinGet.RestSource.psm1 b/Tools/PowershellModule/src/Microsoft.WinGet.RestSource.psm1 index 21a6b28a..8f04b4b9 100644 --- a/Tools/PowershellModule/src/Microsoft.WinGet.RestSource.psm1 +++ b/Tools/PowershellModule/src/Microsoft.WinGet.RestSource.psm1 @@ -8,27 +8,26 @@ try { $Architecture = [System.Runtime.InteropServices.RuntimeInformation]::ProcessArchitecture.ToString().ToLower() - if ($Architecture -eq "x64" -or $Architecture -eq "x86" -or $Architecture -eq "arm64") { + if ($Architecture -eq 'x64' -or $Architecture -eq 'x86' -or $Architecture -eq 'arm64') { Add-Type -Path "$PSScriptRoot\Library\WinGet.RestSource.PowershellSupport\Microsoft.Winget.PowershellSupport.dll" -ErrorAction Stop $DllSearchPath = "$PSScriptRoot\Library\WinGet.RestSource.PowershellSupport\runtimes\win-$Architecture\native" [Microsoft.WinGet.RestSource.PowershellSupport.AddDllSearchDirectory]::AddDirectory($DllSearchPath) - } - else { - Write-Error "Powershell Core runtime architecture not supported" -ErrorAction Stop + } else { + Write-Error 'Powershell Core runtime architecture not supported' -ErrorAction Stop } ## Load Test-PowerShellModuleExist first . "$PSScriptRoot\Library\Test-PowerShellModuleExist.ps1" ## Validates that the required Azure Modules are present when the script is imported. - [string[]]$RequiredModules = @("Az") + [string[]]$RequiredModules = @('Az') foreach ($RequiredModule in $RequiredModules) { ## Tests if the module is installed $Result = Test-PowerShellModuleExist -Name $RequiredModule ## Install the missing module - if(!($Result)) { + if (!($Result)) { Install-Module $RequiredModule -Force -AllowClobber } } @@ -37,16 +36,15 @@ try { [Boolean] $TestResult = Test-PowerShellModuleExist -Modules $RequiredModules if (!$TestResult) { ## Modules have been identified as missing - Write-Error "There are missing PowerShell modules that must be installed. Some or all PowerShell functions included in this library will fail." -ErrorAction Stop + Write-Error 'There are missing PowerShell modules that must be installed. Some or all PowerShell functions included in this library will fail.' -ErrorAction Stop } ## Load classes first . $PSScriptRoot\Library\WinGetManifest.ps1 ## Loads Libraries - Get-ChildItem -Path "$PSScriptRoot\Library" -Filter *.ps1 | foreach-object { . $_.FullName } -} -catch { + Get-ChildItem -Path "$PSScriptRoot\Library" -Filter *.ps1 | ForEach-Object { . $_.FullName } +} catch { ## Exceptions thrown in psm1 will not fail the Import-Module automatically. Catch and re-throw to fail the Import-Module. throw $_ } \ No newline at end of file