Skip to content

Commit 36c0fda

Browse files
authored
PowerShell best practice styles (#305)
1 parent 31a5b4b commit 36c0fda

20 files changed

+760
-837
lines changed

.gitignore

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -374,5 +374,3 @@ Microsoft.WinGet.*.Documentation.xml
374374
# Developer ARM template
375375
src/WinGet.RestSource.Infrastructure/**/*.dev.*json
376376

377-
# VS Code
378-
.vscode/

.vscode/settings.json

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,22 @@
1+
{
2+
"editor.formatOnSave": true,
3+
"[powershell]": {
4+
"files.encoding": "utf8bom",
5+
"files.autoGuessEncoding": true
6+
},
7+
"powershell.codeFormatting.preset": "OTBS",
8+
"powershell.codeFormatting.useConstantStrings": true,
9+
"powershell.codeFormatting.trimWhitespaceAroundPipe": true,
10+
"powershell.codeFormatting.useCorrectCasing": true,
11+
"powershell.codeFormatting.whitespaceBeforeOpenParen": true,
12+
"powershell.codeFormatting.whitespaceBetweenParameters": true,
13+
"powershell.codeFormatting.addWhitespaceAroundPipe": true,
14+
"powershell.codeFormatting.alignPropertyValuePairs": true,
15+
"powershell.codeFormatting.autoCorrectAliases": true,
16+
"powershell.codeFormatting.avoidSemicolonsAsLineTerminators": true,
17+
"powershell.codeFormatting.ignoreOneLineBlock": true,
18+
"powershell.codeFormatting.whitespaceBeforeOpenBrace": true,
19+
"powershell.codeFormatting.whitespaceAroundOperator": true,
20+
"powershell.codeFormatting.whitespaceAfterSeparator": true,
21+
"powershell.codeFormatting.whitespaceInsideBrace": true
22+
}

Tools/PowershellModule/src/Library/Add-AzureResourceGroup.ps1

Lines changed: 10 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
# Copyright (c) Microsoft Corporation.
22
# Licensed under the MIT License.
3-
Function Add-AzureResourceGroup
4-
{
3+
function Add-AzureResourceGroup {
54
<#
65
.SYNOPSIS
76
Adds a Resource Group to the connected to Subscription.
@@ -24,16 +23,16 @@ Function Add-AzureResourceGroup
2423
Assumes an active connection to Azure. Creates a new Resource Group named "contosorestsource" in the West US region.
2524
#>
2625

27-
PARAM(
28-
[Parameter(Position=0, Mandatory=$true)] [string]$Name,
29-
[Parameter(Position=1, Mandatory=$true)] [string]$Region
26+
param(
27+
[Parameter(Position = 0, Mandatory = $true)] [string]$Name,
28+
[Parameter(Position = 1, Mandatory = $true)] [string]$Region
3029
)
3130

3231
$Return = $false
3332

3433
## Normalize resource group name
35-
$NormalizedName = $Name -replace "[^a-zA-Z0-9-()_.]", ""
36-
if($Name -cne $NormalizedName) {
34+
$NormalizedName = $Name -replace '[^a-zA-Z0-9-()_.]', ''
35+
if ($Name -cne $NormalizedName) {
3736
$Name = $NormalizedName
3837
Write-Warning "Removed special characters from the Azure Resource Group Name (New Name: $Name)."
3938
}
@@ -45,19 +44,17 @@ Function Add-AzureResourceGroup
4544
Write-Verbose "Retrieving details from Azure for the Resource Group name $Name"
4645
$Result = Get-AzResourceGroup -Name $Name -ErrorAction SilentlyContinue -ErrorVariable ErrorGet
4746

48-
if(!$Result) {
47+
if (!$Result) {
4948
Write-Information "Failed to retrieve Resource Group, will attempt to create $Name in the specified $Region."
5049

5150
$Result = New-AzResourceGroup -Name $Name -Location $Region
52-
if($Result) {
51+
if ($Result) {
5352
Write-Information "Resource Group $Name has been created in the $Region region."
5453
$Return = $true
55-
}
56-
else {
54+
} else {
5755
Write-Error "Failed to retrieve or create Resource Group with name $Name."
5856
}
59-
}
60-
else {
57+
} else {
6158
## Found an existing Resource Group matching the name of $Name
6259
Write-Warning "Found an existing Resource Group matching the name of $Name. Will not create a new Resource Group."
6360
$Return = $true
Lines changed: 37 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,13 @@
11
# Copyright (c) Microsoft Corporation.
22
# Licensed under the MIT License.
3-
Function Add-WinGetManifest
4-
{
3+
function Add-WinGetManifest {
54
<#
65
.SYNOPSIS
76
Submits a Manifest to the Windows Package Manager REST source.
87
9-
.DESCRIPTION
8+
.DESCRIPTION
109
Submits a Manifest to the Windows Package Manager REST source.
11-
Running this function will first connect to the Azure Tenant that hosts the Windows Package Manager REST source.
10+
Running this function will first connect to the Azure Tenant that hosts the Windows Package Manager REST source.
1211
The function will then collect the required URL before retrieving the contents of the Manifest for submission.
1312
1413
.PARAMETER FunctionName
@@ -41,75 +40,73 @@ Function Add-WinGetManifest
4140
specified Manifest (*.json) to the Windows Package Manager REST source.
4241
#>
4342

44-
PARAM(
45-
[Parameter(Position=0, Mandatory=$true)] [string]$FunctionName,
46-
[Parameter(Position=1, Mandatory=$true, ValueFromPipeline=$true)] [string]$Path,
47-
[Parameter(Mandatory=$false)] [string]$SubscriptionName = ""
43+
param(
44+
[Parameter(Position = 0, Mandatory = $true)] [string]$FunctionName,
45+
[Parameter(Position = 1, Mandatory = $true, ValueFromPipeline = $true)] [string]$Path,
46+
[Parameter(Mandatory = $false)] [string]$SubscriptionName = ''
4847
)
49-
BEGIN
50-
{
48+
begin {
5149
[WinGetManifest[]] $Return = @()
5250

5351
###############################
5452
## Connects to Azure, if not already connected.
55-
Write-Verbose -Message "Validating connection to azure, will attempt to connect if not already connected."
53+
Write-Verbose -Message 'Validating connection to azure, will attempt to connect if not already connected.'
5654
$Result = Connect-ToAzure -SubscriptionName $SubscriptionName
57-
if(!($Result)) {
58-
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
55+
if (!($Result)) {
56+
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
5957
}
6058

6159
###############################
6260
## Gets Resource Group name of the Azure Function
63-
Write-Verbose -Message "Determines the Azure Function Resource Group Name"
64-
$ResourceGroupName = $(Get-AzFunctionApp).Where({$_.Name -eq $FunctionName}).ResourceGroupName
65-
if(!$ResourceGroupName) {
61+
Write-Verbose -Message 'Determines the Azure Function Resource Group Name'
62+
$ResourceGroupName = $(Get-AzFunctionApp).Where({ $_.Name -eq $FunctionName }).ResourceGroupName
63+
if (!$ResourceGroupName) {
6664
Write-Error "Failed to confirm Azure Function exists in Azure. Please verify and try again. Function Name: $FunctionName" -ErrorAction Stop
6765
}
6866

6967
#############################################
7068
############## REST api call ##############
7169

7270
## Specifies the REST api call that will be performed
73-
$ApiContentType = "application/json"
74-
$ApiMethodPost = "Post"
75-
$ApiMethodGet = "Get"
76-
$ApiMethodPut = "Put"
71+
$ApiContentType = 'application/json'
72+
$ApiMethodPost = 'Post'
73+
$ApiMethodGet = 'Get'
74+
$ApiMethodPut = 'Put'
7775

7876
## Retrieves the Azure Function URL used to add new manifests to the REST source
7977
Write-Verbose -Message "Retrieving the Azure Function $FunctionName to build out the REST API request."
8078
$FunctionApp = Get-AzFunctionApp -ResourceGroupName $ResourceGroupName -Name $FunctionName
8179

82-
$FunctionAppId = $FunctionApp.Id
80+
$FunctionAppId = $FunctionApp.Id
8381
$DefaultHostName = $FunctionApp.DefaultHostName
8482
$FunctionKeyPost = (Invoke-AzResourceAction -ResourceId "$FunctionAppId/functions/ManifestPost" -Action listkeys -Force).default
8583
$FunctionKeyGet = (Invoke-AzResourceAction -ResourceId "$FunctionAppId/functions/ManifestGet" -Action listkeys -Force).default
8684
$FunctionKeyPut = (Invoke-AzResourceAction -ResourceId "$FunctionAppId/functions/ManifestPut" -Action listkeys -Force).default
8785

8886

8987
## Creates the API Post Header
90-
$ApiHeader = New-Object "System.Collections.Generic.Dictionary[[String],[String]]"
91-
$ApiHeader.Add("Accept", 'application/json')
88+
$ApiHeader = New-Object 'System.Collections.Generic.Dictionary[[String],[String]]'
89+
$ApiHeader.Add('Accept', 'application/json')
9290

93-
$AzFunctionURLBase = "https://" + $DefaultHostName + "/api/packageManifests/"
91+
$AzFunctionURLBase = 'https://' + $DefaultHostName + '/api/packageManifests/'
9492
}
95-
PROCESS
96-
{
93+
process {
9794
$Path = [System.IO.Path]::GetFullPath($Path, $pwd.Path)
9895

9996
###############################
10097
## Gets the content from the Package Manifest (*.JSON, or *.YAML) file for posting to REST source.
101-
Write-Verbose -Message "Retrieving a copy of the app Manifest file for submission to WinGet source."
98+
Write-Verbose -Message 'Retrieving a copy of the app Manifest file for submission to WinGet source.'
10299
$ApplicationManifest = Get-WinGetManifest -Path $Path
103-
if($ApplicationManifest.Count -ne 1) {
104-
Write-Error "Failed to retrieve a proper manifest. Verify and try again."
100+
if ($ApplicationManifest.Count -ne 1) {
101+
Write-Error 'Failed to retrieve a proper manifest. Verify and try again.'
105102
return
106103
}
107104

108105
$Manifest = $ApplicationManifest[0]
109106
Write-Verbose -Message "Contents of manifest have been retrieved. Package Identifier: $($Manifest.PackageIdentifier)."
110107

111108
Write-Verbose -Message "Confirming that the Package ID doesn't already exist in Azure for $($Manifest.PackageIdentifier)."
112-
$ApiHeader["x-functions-key"] = $FunctionKeyGet
109+
$ApiHeader['x-functions-key'] = $FunctionKeyGet
113110
$AzFunctionURL = $AzFunctionURLBase + $Manifest.PackageIdentifier
114111
$Response = Invoke-RestMethod $AzFunctionURL -Headers $ApiHeader -Method $ApiMethodGet -ErrorVariable ErrorInvoke
115112

@@ -119,20 +116,19 @@ Function Add-WinGetManifest
119116

120117
$ApiMethod = $ApiMethodPost
121118
$AzFunctionURL = $AzFunctionURLBase
122-
$ApiHeader["x-functions-key"] = $FunctionKeyPost
123-
}
124-
else {
119+
$ApiHeader['x-functions-key'] = $FunctionKeyPost
120+
} else {
125121
## Existing manifest retrieved, submit as update existing manifest
126122
Write-Verbose "Found manifest that matched. Package Identifier: $($Manifest.PackageIdentifier)"
127123

128-
if($Response.Data.Count -gt 1) {
124+
if ($Response.Data.Count -gt 1) {
129125
Write-Error "Found conflicting manifests. Package Identifier: $($Manifest.PackageIdentifier)"
130126
return
131127
}
132128

133129
$ApiMethod = $ApiMethodPut
134130
$AzFunctionURL = $AzFunctionURLBase + $Manifest.PackageIdentifier
135-
$ApiHeader["x-functions-key"] = $FunctionKeyPut
131+
$ApiHeader['x-functions-key'] = $FunctionKeyPut
136132

137133
## Merge with prior manifest
138134
$PriorManifest = [WinGetManifest]::CreateFromObject($Response.Data[0])
@@ -144,7 +140,7 @@ Function Add-WinGetManifest
144140

145141
$Response = Invoke-RestMethod $AzFunctionURL -Headers $ApiHeader -Method $ApiMethod -Body $Manifest.GetJson() -ContentType $ApiContentType -ErrorVariable ErrorInvoke
146142

147-
if($ErrorInvoke) {
143+
if ($ErrorInvoke) {
148144
$ErrReturnObject = @{
149145
AzFunctionURL = $AzFunctionURL
150146
ApiMethod = $ApiMethod
@@ -154,21 +150,19 @@ Function Add-WinGetManifest
154150
InvokeError = $ErrorInvoke
155151
}
156152

157-
Write-Error -Message "Failed to add manifest." -TargetObject $ErrReturnObject
158-
}
159-
else {
153+
Write-Error -Message 'Failed to add manifest.' -TargetObject $ErrReturnObject
154+
} else {
160155
if ($Response.Data.Count -ne 1) {
161156
Write-Warning "Returned conflicting manifests after adding the manifest. Package Identifier: $($Manifest.PackageIdentifier)"
162157
}
163158

164-
foreach ($ResponseData in $Response.Data){
159+
foreach ($ResponseData in $Response.Data) {
165160
Write-Verbose "Parsing through the returned results: $ResponseData"
166161
$Return += [WinGetManifest]::CreateFromObject($ResponseData)
167162
}
168163
}
169164
}
170-
END
171-
{
165+
end {
172166
return $Return
173167
}
174-
}
168+
}

Tools/PowershellModule/src/Library/Connect-ToAzure.ps1

Lines changed: 17 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,6 @@
11
# Copyright (c) Microsoft Corporation.
22
# Licensed under the MIT License.
3-
Function Connect-ToAzure
4-
{
3+
function Connect-ToAzure {
54
<#
65
.SYNOPSIS
76
Connects to an Azure environment and connects to a specific Azure Subscription if a name of the subscription has been provided.
@@ -37,74 +36,68 @@ Function Connect-ToAzure
3736
3837
#>
3938

40-
PARAM(
41-
[Parameter(Mandatory=$false)] [string]$SubscriptionName = "",
42-
[Parameter(Mandatory=$false)] [string]$SubscriptionId = ""
39+
param(
40+
[Parameter(Mandatory = $false)] [string]$SubscriptionName = '',
41+
[Parameter(Mandatory = $false)] [string]$SubscriptionId = ''
4342
)
4443

4544
$TestAzureConnection = $false
4645

47-
if($SubscriptionName -and $SubscriptionId){
46+
if ($SubscriptionName -and $SubscriptionId) {
4847
## 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.
4948
Write-Verbose -Message "Verifying if PowerShell session is currently connected to your Azure Subscription Name $SubscriptionName and Subscription Id $SubscriptionId"
5049
$TestAzureConnection = Test-ConnectionToAzure -SubscriptionName $SubscriptionName -SubscriptionId $SubscriptionId
51-
}
52-
elseif($SubscriptionName){
50+
} elseif ($SubscriptionName) {
5351
## If connected to Azure, and the Subscription Name are provided then verify that the connected Azure session matches the provided Subscription Name.
5452
Write-Verbose -Message "Verifying if PowerShell session is currently connected to your Azure Subscription Name $SubscriptionName"
5553
$TestAzureConnection = Test-ConnectionToAzure -SubscriptionName $SubscriptionName
56-
}
57-
elseif($SubscriptionId){
54+
} elseif ($SubscriptionId) {
5855
## If connected to Azure, and the Subscription Id are provided then verify that the connected Azure session matches the provided Subscription Id.
5956
Write-Verbose -Message "Verifying if PowerShell session is currently connected to your Azure Subscription Id $SubscriptionId"
6057
$TestAzureConnection = Test-ConnectionToAzure -SubscriptionId $SubscriptionId
61-
}
62-
else{
63-
Write-Information "No Subscription Name or Subscription Id provided. Will test connection to default Azure Subscription"
58+
} else {
59+
Write-Information 'No Subscription Name or Subscription Id provided. Will test connection to default Azure Subscription'
6460
$TestAzureConnection = Test-ConnectionToAzure
6561
}
6662

6763
Write-Verbose -Message "Test Connection Result: $TestAzureConnection"
6864

69-
if(!$TestAzureConnection) {
70-
if($SubscriptionName -and $SubscriptionId) {
65+
if (!$TestAzureConnection) {
66+
if ($SubscriptionName -and $SubscriptionId) {
7167
## Attempts a connection to Azure using both the Subscription Name and Subscription Id
7268
Write-Information "Initiating a connection to your Azure Subscription Name $SubscriptionName and Subscription Id $SubscriptionId"
7369
$ConnectResult = Connect-AzAccount -SubscriptionName $SubscriptionName -SubscriptionId $SubscriptionId
7470

7571
$TestAzureConnection = Test-ConnectionToAzure -SubscriptionName $SubscriptionName -SubscriptionId $SubscriptionId
76-
}
77-
elseif($SubscriptionName) {
72+
} elseif ($SubscriptionName) {
7873
## Attempts a connection to Azure using Subscription Name
7974
Write-Information "Initiating a connection to your Azure Subscription Name $SubscriptionName"
8075
$ConnectResult = Connect-AzAccount -SubscriptionName $SubscriptionName
8176

8277
$TestAzureConnection = Test-ConnectionToAzure -SubscriptionName $SubscriptionName
83-
}
84-
elseif($SubscriptionId) {
78+
} elseif ($SubscriptionId) {
8579
## Attempts a connection to Azure using Subscription Id
8680
Write-Information "Initiating a connection to your Azure Subscription Id $SubscriptionId"
8781
$ConnectResult = Connect-AzAccount -SubscriptionId $SubscriptionId
8882

8983
$TestAzureConnection = Test-ConnectionToAzure -SubscriptionId $SubscriptionId
90-
}
91-
else{
84+
} else {
9285
## Attempts a connection to Azure with the users default Subscription
93-
Write-Information "Initiating a connection to your Azure environment."
86+
Write-Information 'Initiating a connection to your Azure environment.'
9487
$ConnectResult = Connect-AzAccount
9588

9689
$TestAzureConnection = Test-ConnectionToAzure
9790
}
9891

99-
if(!$TestAzureConnection) {
92+
if (!$TestAzureConnection) {
10093
## If the connection fails, or the user cancels the login request, then return as failed.
10194
$ErrReturnObject = @{
10295
SubscriptionName = $SubscriptionName
10396
SubscriptionId = $SubscriptionId
10497
AzureConnected = $TestAzureConnection
10598
}
10699

107-
Write-Error -Message "Failed to connect to Azure" -TargetObject $ErrReturnObject
100+
Write-Error -Message 'Failed to connect to Azure' -TargetObject $ErrReturnObject
108101
}
109102
}
110103

0 commit comments

Comments
 (0)