diff --git a/.gitignore b/.gitignore index 49e3957d..a3493a82 100644 --- a/.gitignore +++ b/.gitignore @@ -62,7 +62,7 @@ gen .profile.ps1 #VS Code files -.vscode +#.vscode # OS X .DS_Store diff --git a/.vscode/settings.json b/.vscode/settings.json new file mode 100644 index 00000000..a2519b0f --- /dev/null +++ b/.vscode/settings.json @@ -0,0 +1,28 @@ +{ + "editor.renderWhitespace": "boundary", + "editor.formatOnSave": true, + "editor.formatOnType": true, + "editor.rulers": [ + 116 + ], + "editor.tabCompletion": "on", + "files.encoding": "utf8", + "files.eol": "\r\n", + "files.trimTrailingWhitespace": true, + "files.insertFinalNewline": true, + "files.trimFinalNewlines": true, + "files.autoSave": "off", + // PowerShell Extension Related Stuff + "powershell.startAutomatically": true, + "powershell.codeFolding.enable": true, + "powershell.codeFormatting.alignPropertyValuePairs": true, + "powershell.codeFormatting.ignoreOneLineBlock": true, + "powershell.codeFormatting.newLineAfterCloseBrace": true, + "powershell.codeFormatting.newLineAfterOpenBrace": true, + "powershell.codeFormatting.openBraceOnSameLine": true, + "powershell.codeFormatting.preset": "Custom", + "powershell.codeFormatting.whitespaceAfterSeparator": true, + "powershell.codeFormatting.whitespaceAroundOperator": true, + "powershell.codeFormatting.whitespaceBeforeOpenBrace": true, + "powershell.codeFormatting.whitespaceBeforeOpenParen": true +} diff --git a/Tests/PSGetModuleSource.Tests.ps1 b/Tests/PSGetModuleSource.Tests.ps1 index 144c9e26..1fa0c521 100644 --- a/Tests/PSGetModuleSource.Tests.ps1 +++ b/Tests/PSGetModuleSource.Tests.ps1 @@ -18,7 +18,7 @@ function SuiteSetup { Import-Module "$PSScriptRoot\PSGetTestUtils.psm1" -WarningAction SilentlyContinue Import-Module "$PSScriptRoot\Asserts.psm1" -WarningAction SilentlyContinue - + $script:ProgramFilesModulesPath = Get-AllUsersModulesPath $script:MyDocumentsModulesPath = Get-CurrentUserModulesPath $script:PSGetLocalAppDataPath = Get-PSGetLocalAppDataPath @@ -84,7 +84,7 @@ function SuiteCleanup { RemoveItem $script:TempModulesPath } -Describe PowerShell.PSGet.ModuleSourceTests -Tags 'BVT','InnerLoop' { +Describe PowerShell.PSGet.ModuleSourceTests -Tags 'BVT', 'InnerLoop' { BeforeAll { SuiteSetup @@ -103,11 +103,11 @@ Describe PowerShell.PSGet.ModuleSourceTests -Tags 'BVT','InnerLoop' { #> It RegisterAngGetModuleSource { - $Name='MyTestModSourceForRegisterAngGet' - $Location='https://www.nuget.org/api/v2/' + $Name = 'MyTestModSourceForRegisterAngGet' + $Location = 'https://www.nuget.org/api/v2/' Register-PSRepository -Default -ErrorAction SilentlyContinue - + try { Register-PSRepository -Name $Name -SourceLocation $Location $moduleSource = Get-PSRepository -Name $Name @@ -137,10 +137,9 @@ Describe PowerShell.PSGet.ModuleSourceTests -Tags 'BVT','InnerLoop' { #> It RegisterSMBShareRepository { - $Name='MyTestModSource' - $Location=$script:TempModulesPath - try - { + $Name = 'MyTestModSource' + $Location = $script:TempModulesPath + try { Register-PSRepository -Name $Name -SourceLocation $Location -PublishLocation $Location $repo = Get-PSRepository -Name $Name @@ -148,8 +147,7 @@ Describe PowerShell.PSGet.ModuleSourceTests -Tags 'BVT','InnerLoop' { AssertEquals $repo.SourceLocation $Location "The SourceLocation is not same as the registered SourceLocation. Actual: $($repo.SourceLocation), Expected: $Location" AssertEquals $repo.PublishLocation $Location "The PublishLocation is not same as the registered PublishLocation. Actual: $($repo.PublishLocation), Expected: $Location" } - finally - { + finally { Get-PSRepository -Name $Name | Unregister-PSRepository } } @@ -163,10 +161,9 @@ Describe PowerShell.PSGet.ModuleSourceTests -Tags 'BVT','InnerLoop' { #> It SetPSRepositoryWithSMBSharePath { - $Name='MyTestModSource' - $Location=$script:TempModulesPath - try - { + $Name = 'MyTestModSource' + $Location = $script:TempModulesPath + try { Register-PSRepository -Name $Name -SourceLocation $Location Set-PSRepository -Name $Name -SourceLocation $Location -PublishLocation $Location $repo = Get-PSRepository -Name $Name @@ -175,8 +172,7 @@ Describe PowerShell.PSGet.ModuleSourceTests -Tags 'BVT','InnerLoop' { AssertEquals $repo.SourceLocation $Location "The SourceLocation is not same as the registered SourceLocation. Actual: $($repo.SourceLocation), Expected: $Location" AssertEquals $repo.PublishLocation $Location "The PublishLocation is not same as the registered PublishLocation. Actual: $($repo.PublishLocation), Expected: $Location" } - finally - { + finally { Get-PSRepository -Name $Name | Unregister-PSRepository } } @@ -190,8 +186,8 @@ Describe PowerShell.PSGet.ModuleSourceTests -Tags 'BVT','InnerLoop' { #> It UnregisterModuleSource { - $Name='MyTestModSource' - $Location='https://www.nuget.org/api/v2/' + $Name = 'MyTestModSource' + $Location = 'https://www.nuget.org/api/v2/' Register-PSRepository -Name $Name -SourceLocation $Location Unregister-PSRepository -Name $Name @@ -199,191 +195,9 @@ Describe PowerShell.PSGet.ModuleSourceTests -Tags 'BVT','InnerLoop' { $expectedFullyQualifiedErrorId = 'SourceNotFound,Microsoft.PowerShell.PackageManagement.Cmdlets.GetPackageSource' AssertFullyQualifiedErrorIdEquals -scriptblock {Get-PSRepository -Name $Name} ` - -expectedFullyQualifiedErrorId $expectedFullyQualifiedErrorId - } - - <# - Purpose: Test Check-PSGalleryApiAvailability and Get-PSGalleryApiAvailability cmdlet for Stage 1 of PSGallery V2/V3 Transition. - - Action: Check-PSGalleryApiAvailability -PSGalleryV2ApiUri $Uri200Ok -PSGalleryV3ApiUri $Uri404NotFound - Get-PSGalleryApiAvailability -Repository PSGallery - - Expected Result: Should show and do nothing. - #> - It CheckGetPSGalleryApiAvailabilityStage1 { - - $result = & $script:PowerShellGetModuleInfo Check-PSGalleryApiAvailability -PSGalleryV2ApiUri $script:Uri200Ok -PSGalleryV3ApiUri $script:Uri404NotFound - AssertNull $result "Check-PSGalleryApiAvailability Stage 1 should not return anything." - - $err = $null - try - { - $result = & $script:PowerShellGetModuleInfo Get-PSGalleryApiAvailability -Repository "PSGallery" -WarningVariable w - } - catch - { - $err = $_ - } - - AssertNull $result "Get-PSGalleryApiAvailability Stage 1 should not return anything." - AssertEquals 0 $w.Count "Get-PSGalleryApiAvailability Stage 1 should not write a warning." - AssertNull $err "Get-PSGalleryApiAvailability Stage 1 should not throw an error message." - } - - <# - Purpose: Test Check-PSGalleryApiAvailability and Get-PSGalleryApiAvailability cmdlet for Stage 2 of PSGallery V2/V3 Transition. - - Action: Check-PSGalleryApiAvailability -PSGalleryV2ApiUri $Uri200Ok -PSGalleryV3ApiUri $Uri200Ok - Get-PSGalleryApiAvailability -Repository PSGallery - - Expected Result: Should display a warning. - #> - It CheckGetPSGalleryApiAvailabilityStage2 { - - try { - $result = & $script:PowerShellGetModuleInfo Check-PSGalleryApiAvailability -PSGalleryV2ApiUri $script:Uri200Ok -PSGalleryV3ApiUri $script:Uri200Ok - AssertNull $result "Check-PSGalleryApiAvailability Stage 2 should not return anything." - - $err = $null - try - { - $result = & $script:PowerShellGetModuleInfo Get-PSGalleryApiAvailability -Repository "PSGallery" -WarningVariable w -WarningAction SilentlyContinue - } - catch - { - $err = $_ - } - - AssertNull $result "Get-PSGalleryApiAvailability Stage 2 should not return anything." - AssertNotEquals 0 $w.Count "Get-PSGalleryApiAvailability Stage 2 should write a warning." - #AssertEqualsCaseInsensitive $script:LocalizedData.PSGalleryApiV2Deprecated $w[0].Message "Get-PSGalleryApiAvailability Stage 2 wrote the wrong warning message." - AssertNull $err "Get-PSGalleryApiAvailability Stage 2 should not throw an error message." - } - finally { - # Set API availability for v2 back to true (no warnings or errors thrown) - $result = & $script:PowerShellGetModuleInfo Check-PSGalleryApiAvailability -PSGalleryV2ApiUri $script:Uri200Ok -PSGalleryV3ApiUri $script:URI404NotFound - } - } - - <# - Purpose: Test Check-PSGalleryApiAvailability and Get-PSGalleryApiAvailability cmdlet for Stage 3 of PSGallery V2/V3 Transition. - - Action: Check-PSGalleryApiAvailability -PSGalleryV2ApiUri $Uri404NotFound -PSGalleryV3ApiUri $Uri200Ok - Get-PSGalleryApiAvailability -Repository PSGallery - - Expected Result: Should throw an error. - #> - It CheckGetPSGalleryApiAvailabilityStage3 { - try { - $result = & $script:PowerShellGetModuleInfo Check-PSGalleryApiAvailability -PSGalleryV2ApiUri $script:Uri404NotFound -PSGalleryV3ApiUri $script:Uri200Ok - AssertNull $result "Check-PSGalleryApiAvailability Stage 3 should not return anything." - - $err = $null - try - { - $result = & $script:PowerShellGetModuleInfo Get-PSGalleryApiAvailability -Repository "PSGallery" -WarningVariable w - } - catch - { - $err = $_ - } - - AssertNull $result "Get-PSGalleryApiAvailability Stage 3 should not return anything." - AssertEquals 0 $w.Count "Get-PSGalleryApiAvailability Stage 3 should not write a warning." - AssertNotNull $err "Get-PSGalleryApiAvailability Stage 3 should throw an error message." - AssertEqualsCaseInsensitive "PSGalleryApiV2Discontinued,Get-PSGalleryApiAvailability" $err.FullyQualifiedErrorId "Get-PSGalleryApiAvailability Stage 3 threw a different error: $err" - } - finally { - # Set API availability for v2 back to true (no warnings or errors thrown) - $result = & $script:PowerShellGetModuleInfo Check-PSGalleryApiAvailability -PSGalleryV2ApiUri $script:Uri200Ok -PSGalleryV3ApiUri $script:URI404NotFound - } - } - - <# - Purpose: Test Check-PSGalleryApiAvailability and Get-PSGalleryApiAvailability cmdlet when no API is available. - This indicates that the site is down. - - Action: Check-PSGalleryApiAvailability -PSGalleryV2ApiUri $Uri404NotFound -PSGalleryV3ApiUri $Uri404NotFound - Get-PSGalleryApiAvailability -Repository PSGallery - - Expected Result: Should throw an error. - #> - It CheckGetPSGalleryUnavailable { - try { - $result = & $script:PowerShellGetModuleInfo Check-PSGalleryApiAvailability -PSGalleryV2ApiUri $script:Uri404NotFound -PSGalleryV3ApiUri $script:Uri404NotFound - AssertNull $result "Check-PSGalleryApiAvailability should not return anything." - - $err = $null - try - { - $result = & $script:PowerShellGetModuleInfo Get-PSGalleryApiAvailability -Repository "PSGallery" -WarningVariable w - } - catch - { - $err = $_ - } - - AssertNull $result "Get-PSGalleryApiAvailability should not return anything." - AssertEquals 0 $w.Count "Get-PSGalleryApiAvailability should not write a warning." - AssertNotNull $err "Get-PSGalleryApiAvailability Stage 3 should throw an error message." - AssertEqualsCaseInsensitive "PowerShellGalleryUnavailable,Get-PSGalleryApiAvailability" $err.FullyQualifiedErrorId "Get-PSGalleryApiAvailability Stage 3 threw a different error: $err" - } - finally { - # Set API availability for v2 back to true (no warnings or errors thrown) - $result = & $script:PowerShellGetModuleInfo Check-PSGalleryApiAvailability -PSGalleryV2ApiUri $script:Uri200Ok -PSGalleryV3ApiUri $script:URI404NotFound - } - } - - <# - Purpose: Test Get-PSGalleryApiAvailability cmdlet when no repository specified. - - Action: Get-PSGalleryApiAvailability - - Expected Result: Should show and do nothing. - #> - It GetPSGalleryApiAvailabilityNoRepositorySpecified { - - $err = $null - try - { - $result = & $script:PowerShellGetModuleInfo Get-PSGalleryApiAvailability -WarningVariable w - } - catch - { - $err = $_ - } - - AssertNull $result "Get-PSGalleryApiAvailability should not return anything." - AssertEquals 0 $w.Count "Get-PSGalleryApiAvailability should not write a warning." - AssertNull $err "Get-PSGalleryApiAvailability should not throw an error message." - } - - - <# - Purpose: Test Get-PSGalleryApiAvailability cmdlet when no repository specified. - - Action: Get-PSGalleryApiAvailability - - Expected Result: Should show and do nothing. - #> - It GetPSGalleryApiAvailabilityDifferentRepositorySpecified { - - $err = $null - try - { - $result = & $script:PowerShellGetModuleInfo Get-PSGalleryApiAvailability -Repository "MSPSGallery" -WarningVariable w - } - catch - { - $err = $_ - } - - AssertNull $result "Get-PSGalleryApiAvailability should not return anything." - AssertEquals 0 $w.Count "Get-PSGalleryApiAvailability should not write a warning." - AssertNull $err "Get-PSGalleryApiAvailability should not throw an error message." + -expectedFullyQualifiedErrorId $expectedFullyQualifiedErrorId } } - Describe PowerShell.PSGet.ModuleSourceTests.P1 -Tags 'P1','OuterLoop' { BeforeAll { @@ -591,7 +405,7 @@ Describe PowerShell.PSGet.ModuleSourceTests.P1 -Tags 'P1','OuterLoop' { AssertFullyQualifiedErrorIdEquals -scriptblock {Register-PSRepository -Name myNuGetSource1 -SourceLocation myget.org/F/powershellgetdemo} ` -expectedFullyQualifiedErrorId $expectedFullyQualifiedErrorId } - + <# Purpose: Validate Register-PSRepository functionality with wildcard in source name @@ -697,7 +511,7 @@ Describe PowerShell.PSGet.ModuleSourceTests.P1 -Tags 'P1','OuterLoop' { -expectedFullyQualifiedErrorId $expectedFullyQualifiedErrorId } - It RegisterPSRepositoryShouldFailWithPSModuleAsPMProviderName { + It RegisterPSRepositoryShouldFailWithPSModuleAsPMProviderName { AssertFullyQualifiedErrorIdEquals -scriptblock {Register-PSRepository -Name Foo -SourceLocation $script:TempPath -PackageManagementProvider PowerShellGet} ` -expectedFullyQualifiedErrorId "InvalidPackageManagementProviderValue,Register-PSRepository" } @@ -707,7 +521,7 @@ Describe PowerShell.PSGet.ModuleSourceTests.P1 -Tags 'P1','OuterLoop' { -expectedFullyQualifiedErrorId "InvalidPackageManagementProviderValue,Set-PSRepository" } - It RegisterPackageSourceShouldFailWithPSModuleAsPMProviderName { + It RegisterPackageSourceShouldFailWithPSModuleAsPMProviderName { AssertFullyQualifiedErrorIdEquals -scriptblock {Register-PackageSource -ProviderName PowerShellGet -Name Foo -Location $script:TempPath -PackageManagementProvider PowerShellGet} ` -expectedFullyQualifiedErrorId "InvalidPackageManagementProviderValue,Add-PackageSource,Microsoft.PowerShell.PackageManagement.Cmdlets.RegisterPackageSource" } @@ -715,7 +529,7 @@ Describe PowerShell.PSGet.ModuleSourceTests.P1 -Tags 'P1','OuterLoop' { Describe PowerShell.PSGet.FindModule.ModuleSourceTests.P1 -Tags 'P1','OuterLoop' { - # Not executing these tests on MacOS as + # Not executing these tests on MacOS as # the total execution time is exceeding allowed 50 min in TravisCI daily builds. if($IsMacOS) { return @@ -789,7 +603,7 @@ Describe PowerShell.PSGet.FindModule.ModuleSourceTests.P1 -Tags 'P1','OuterLoop' Describe PowerShell.PSGet.InstallModule.ModuleSourceTests.P1 -Tags 'P1','OuterLoop' { - # Not executing these tests on MacOS as + # Not executing these tests on MacOS as # the total execution time is exceeding allowed 50 min in TravisCI daily builds. if($IsMacOS) { return diff --git a/src/PowerShellGet/private/functions/Check-PSGalleryApiAvailability.ps1 b/src/PowerShellGet/private/functions/Check-PSGalleryApiAvailability.ps1 deleted file mode 100644 index 064e91e4..00000000 --- a/src/PowerShellGet/private/functions/Check-PSGalleryApiAvailability.ps1 +++ /dev/null @@ -1,90 +0,0 @@ -function Check-PSGalleryApiAvailability -{ - param - ( - [Parameter()] - [ValidateNotNullOrEmpty()] - [string] - $PSGalleryV2ApiUri, - - [Parameter()] - [ValidateNotNullOrEmpty()] - [string] - $PSGalleryV3ApiUri - ) - - # check internet availability first - $connected = $false - $microsoftDomain = 'www.microsoft.com' - if((-not $script:IsCoreCLR) -and (Get-Command Microsoft.PowerShell.Management\Test-Connection -ErrorAction Ignore)) - { - try - { - $connected = Microsoft.PowerShell.Management\Test-Connection -ComputerName $microsoftDomain -Count 1 -Quiet - } - catch - { - # Test-Connection throws an exception even with -EA SilentlyIgnore, we must use try catch to suppress it - } - } - if(( -not $connected) -and (Get-Command NetTCPIP\Test-Connection -ErrorAction Ignore)) - { - try - { - $connected = NetTCPIP\Test-NetConnection -ComputerName $microsoftDomain -InformationLevel Quiet - } - catch - { - # $connected is already set to $false, this applies on all three empty catch blocks - } - } - if ( -not $connected) - { - try - { - $connected = [System.Net.NetworkInformation.NetworkInterface]::GetIsNetworkAvailable() - } - catch - { - # there is no -ErrorAction on method call, we must use empty catch block to suppress error - } - } - - if ( -not $connected) - { - return - } - - $statusCode_v2 = $null - $resolvedUri_v2 = $null - $statusCode_v3 = $null - $resolvedUri_v3 = $null - - # ping V2 - $res_v2 = Ping-Endpoint -Endpoint $PSGalleryV2ApiUri - if ($res_v2.ContainsKey($Script:ResponseUri)) - { - $resolvedUri_v2 = $res_v2[$Script:ResponseUri] - } - if ($res_v2.ContainsKey($Script:StatusCode)) - { - $statusCode_v2 = $res_v2[$Script:StatusCode] - } - - - # ping V3 - $res_v3 = Ping-Endpoint -Endpoint $PSGalleryV3ApiUri - if ($res_v3.ContainsKey($Script:ResponseUri)) - { - $resolvedUri_v3 = $res_v3[$Script:ResponseUri] - } - if ($res_v3.ContainsKey($Script:StatusCode)) - { - $statusCode_v3 = $res_v3[$Script:StatusCode] - } - - - $Script:PSGalleryV2ApiAvailable = (($statusCode_v2 -eq 200) -and ($resolvedUri_v2)) - $Script:PSGalleryV3ApiAvailable = (($statusCode_v3 -eq 200) -and ($resolvedUri_v3)) - $Script:PSGalleryApiChecked = $true -} \ No newline at end of file diff --git a/src/PowerShellGet/private/functions/Get-PSGalleryApiAvailability.ps1 b/src/PowerShellGet/private/functions/Get-PSGalleryApiAvailability.ps1 deleted file mode 100644 index f2099d6b..00000000 --- a/src/PowerShellGet/private/functions/Get-PSGalleryApiAvailability.ps1 +++ /dev/null @@ -1,58 +0,0 @@ -function Get-PSGalleryApiAvailability -{ - param - ( - [Parameter()] - [string[]] - $Repository - ) - - # skip if repository is null or not PSGallery - if ( -not $Repository) - { - return - } - - if ($Repository -notcontains $Script:PSGalleryModuleSource ) - { - return - } - - # run check only once - if( -not $Script:PSGalleryApiChecked) - { - $null = Check-PSGalleryApiAvailability -PSGalleryV2ApiUri $Script:PSGallerySourceUri -PSGalleryV3ApiUri $Script:PSGalleryV3SourceUri - } - - if ( -not $Script:PSGalleryV2ApiAvailable ) - { - if ($Script:PSGalleryV3ApiAvailable) - { - ThrowError -ExceptionName "System.InvalidOperationException" ` - -ExceptionMessage $LocalizedData.PSGalleryApiV2Discontinued ` - -ErrorId "PSGalleryApiV2Discontinued" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidOperation - } - else - { - # both APIs are down, throw error - ThrowError -ExceptionName "System.InvalidOperationException" ` - -ExceptionMessage $LocalizedData.PowerShellGalleryUnavailable ` - -ErrorId "PowerShellGalleryUnavailable" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidOperation - } - - } - else - { - if ($Script:PSGalleryV3ApiAvailable) - { - Write-Warning -Message $LocalizedData.PSGalleryApiV2Deprecated - return - } - } - - # if V2 is available and V3 is not available, do nothing -} diff --git a/src/PowerShellGet/private/modulefile/PartOne.ps1 b/src/PowerShellGet/private/modulefile/PartOne.ps1 index a903d083..8f4ac695 100644 --- a/src/PowerShellGet/private/modulefile/PartOne.ps1 +++ b/src/PowerShellGet/private/modulefile/PartOne.ps1 @@ -17,29 +17,25 @@ $script:IsLinux = (Get-Variable -Name IsLinux -ErrorAction Ignore) -and $IsLinux $script:IsMacOS = (Get-Variable -Name IsMacOS -ErrorAction Ignore) -and $IsMacOS $script:IsCoreCLR = $PSVersionTable.ContainsKey('PSEdition') -and $PSVersionTable.PSEdition -eq 'Core' $script:IsNanoServer = & { - if (!$script:IsWindows) - { + if (!$script:IsWindows) { return $false } $serverLevelsPath = 'HKLM:\SOFTWARE\Microsoft\Windows NT\CurrentVersion\Server\ServerLevels\' - if (Test-Path -Path $serverLevelsPath) - { + if (Test-Path -Path $serverLevelsPath) { $NanoItem = Get-ItemProperty -Name NanoServer -Path $serverLevelsPath -ErrorAction Ignore - if ($NanoItem -and ($NanoItem.NanoServer -eq 1)) - { + if ($NanoItem -and ($NanoItem.NanoServer -eq 1)) { return $true } } return $false } -if($script:IsInbox) -{ +if ($script:IsInbox) { $script:ProgramFilesPSPath = Microsoft.PowerShell.Management\Join-Path -Path $env:ProgramFiles -ChildPath "WindowsPowerShell" } -elseif($script:IsCoreCLR){ - if($script:IsWindows) { +elseif ($script:IsCoreCLR) { + if ($script:IsWindows) { $script:ProgramFilesPSPath = Microsoft.PowerShell.Management\Join-Path -Path $env:ProgramFiles -ChildPath 'PowerShell' } else { @@ -47,40 +43,31 @@ elseif($script:IsCoreCLR){ } } -try -{ +try { $script:MyDocumentsFolderPath = [Environment]::GetFolderPath("MyDocuments") } -catch -{ +catch { $script:MyDocumentsFolderPath = $null } -if($script:IsInbox) -{ - $script:MyDocumentsPSPath = if($script:MyDocumentsFolderPath) - { - Microsoft.PowerShell.Management\Join-Path -Path $script:MyDocumentsFolderPath -ChildPath "WindowsPowerShell" - } - else - { - Microsoft.PowerShell.Management\Join-Path -Path $env:USERPROFILE -ChildPath "Documents\WindowsPowerShell" - } +if ($script:IsInbox) { + $script:MyDocumentsPSPath = if ($script:MyDocumentsFolderPath) { + Microsoft.PowerShell.Management\Join-Path -Path $script:MyDocumentsFolderPath -ChildPath "WindowsPowerShell" + } + else { + Microsoft.PowerShell.Management\Join-Path -Path $env:USERPROFILE -ChildPath "Documents\WindowsPowerShell" + } } -elseif($script:IsCoreCLR) { - if($script:IsWindows) - { - $script:MyDocumentsPSPath = if($script:MyDocumentsFolderPath) - { +elseif ($script:IsCoreCLR) { + if ($script:IsWindows) { + $script:MyDocumentsPSPath = if ($script:MyDocumentsFolderPath) { Microsoft.PowerShell.Management\Join-Path -Path $script:MyDocumentsFolderPath -ChildPath 'PowerShell' } - else - { + else { Microsoft.PowerShell.Management\Join-Path -Path $HOME -ChildPath "Documents\PowerShell" } } - else - { + else { $script:MyDocumentsPSPath = Microsoft.PowerShell.Management\Split-Path -Path ([System.Management.Automation.Platform]::SelectProductNameForDirectory('USER_MODULES')) -Parent } } @@ -94,13 +81,11 @@ $script:MyDocumentsScriptsPath = Microsoft.PowerShell.Management\Join-Path -Path $script:TempPath = [System.IO.Path]::GetTempPath() $script:PSGetItemInfoFileName = "PSGetModuleInfo.xml" -if($script:IsWindows) -{ +if ($script:IsWindows) { $script:PSGetProgramDataPath = Microsoft.PowerShell.Management\Join-Path -Path $env:ProgramData -ChildPath 'Microsoft\Windows\PowerShell\PowerShellGet\' $script:PSGetAppLocalPath = Microsoft.PowerShell.Management\Join-Path -Path $env:LOCALAPPDATA -ChildPath 'Microsoft\Windows\PowerShell\PowerShellGet\' } -else -{ +else { $script:PSGetProgramDataPath = Microsoft.PowerShell.Management\Join-Path -Path ([System.Management.Automation.Platform]::SelectProductNameForDirectory('CONFIG')) -ChildPath 'PowerShellGet' $script:PSGetAppLocalPath = Microsoft.PowerShell.Management\Join-Path -Path ([System.Management.Automation.Platform]::SelectProductNameForDirectory('CACHE')) -ChildPath 'PowerShellGet' } @@ -121,24 +106,20 @@ $script:InstalledScriptInfoFileName = 'InstalledScriptInfo.xml' $script:PSGetInstalledScripts = $null # Public PSGallery module source name and location -$Script:PSGalleryModuleSource="PSGallery" -$Script:PSGallerySourceUri = 'https://www.powershellgallery.com/api/v2' +$Script:PSGalleryModuleSource = "PSGallery" +$Script:PSGallerySourceUri = 'https://www.powershellgallery.com/api/v2' $Script:PSGalleryPublishUri = 'https://www.powershellgallery.com/api/v2/package/' $Script:PSGalleryScriptSourceUri = 'https://www.powershellgallery.com/api/v2/items/psscript' # PSGallery V3 Source $Script:PSGalleryV3SourceUri = 'https://www.powershellgallery.com/api/v3' -$Script:PSGalleryV2ApiAvailable = $true -$Script:PSGalleryV3ApiAvailable = $false -$Script:PSGalleryApiChecked = $false - $Script:ResponseUri = "ResponseUri" $Script:StatusCode = "StatusCode" $Script:Exception = "Exception" $script:PSModuleProviderName = 'PowerShellGet' -$script:PackageManagementProviderParam = "PackageManagementProvider" +$script:PackageManagementProviderParam = "PackageManagementProvider" $script:PublishLocation = "PublishLocation" $script:ScriptSourceLocation = 'ScriptSourceLocation' $script:ScriptPublishLocation = 'ScriptPublishLocation' @@ -149,12 +130,12 @@ $script:VSTSAuthenticatedFeedsDocUrl = 'https://go.microsoft.com/fwlink/?LinkID= $script:Prerelease = "Prerelease" $script:NuGetProviderName = "NuGet" -$script:NuGetProviderVersion = [Version]'2.8.5.201' +$script:NuGetProviderVersion = [Version]'2.8.5.201' -$script:SupportsPSModulesFeatureName="supports-powershell-modules" +$script:SupportsPSModulesFeatureName = "supports-powershell-modules" $script:FastPackRefHashtable = @{} -$script:NuGetBinaryProgramDataPath=if($script:IsWindows) {"$env:ProgramFiles\PackageManagement\ProviderAssemblies"} -$script:NuGetBinaryLocalAppDataPath=if($script:IsWindows) {"$env:LOCALAPPDATA\PackageManagement\ProviderAssemblies"} +$script:NuGetBinaryProgramDataPath = if ($script:IsWindows) {"$env:ProgramFiles\PackageManagement\ProviderAssemblies"} +$script:NuGetBinaryLocalAppDataPath = if ($script:IsWindows) {"$env:LOCALAPPDATA\PackageManagement\ProviderAssemblies"} # go fwlink for 'https://dist.nuget.org/win-x86-commandline/latest/nuget.exe' $script:NuGetClientSourceURL = 'https://aka.ms/psget-nugetexe' $script:NuGetExeMinRequiredVersion = [Version]'4.1.0' @@ -173,21 +154,21 @@ $script:DotnetCommandPath = $null $script:PSGetRequireLicenseAcceptanceFormatVersion = [Version]'2.0' $script:CurrentPSGetFormatVersion = $script:PSGetRequireLicenseAcceptanceFormatVersion $script:PSGetFormatVersion = "PowerShellGetFormatVersion" -$script:SupportedPSGetFormatVersionMajors = @("1","2") +$script:SupportedPSGetFormatVersionMajors = @("1", "2") $script:ModuleReferences = 'Module References' $script:AllVersions = "AllVersions" $script:AllowPrereleaseVersions = "AllowPrereleaseVersions" -$script:Filter = "Filter" -$script:IncludeValidSet = @('DscResource','Cmdlet','Function','Workflow','RoleCapability') +$script:Filter = "Filter" +$script:IncludeValidSet = @('DscResource', 'Cmdlet', 'Function', 'Workflow', 'RoleCapability') $script:DscResource = "PSDscResource" -$script:Command = "PSCommand" -$script:Cmdlet = "PSCmdlet" -$script:Function = "PSFunction" -$script:Workflow = "PSWorkflow" +$script:Command = "PSCommand" +$script:Cmdlet = "PSCmdlet" +$script:Function = "PSFunction" +$script:Workflow = "PSWorkflow" $script:RoleCapability = 'PSRoleCapability' -$script:Includes = "PSIncludes" -$script:Tag = "Tag" -$script:NotSpecified= '_NotSpecified_' +$script:Includes = "PSIncludes" +$script:Tag = "Tag" +$script:NotSpecified = '_NotSpecified_' $script:PSGetModuleName = 'PowerShellGet' $script:FindByCanonicalId = 'FindByCanonicalId' $script:InstalledLocation = 'InstalledLocation' @@ -214,35 +195,35 @@ $script:ExternalModuleDependencies = 'ExternalModuleDependencies' $script:ReleaseNotes = 'ReleaseNotes' $script:RequiredScripts = 'RequiredScripts' $script:ExternalScriptDependencies = 'ExternalScriptDependencies' -$script:DefinedCommands = 'DefinedCommands' +$script:DefinedCommands = 'DefinedCommands' $script:DefinedFunctions = 'DefinedFunctions' $script:DefinedWorkflows = 'DefinedWorkflows' $script:TextInfo = (Get-Culture).TextInfo $script:PrivateData = 'PrivateData' $script:PSScriptInfoProperties = @($script:Name - $script:Version, - $script:Guid, - $script:Path, - $script:ScriptBase, - $script:Description, - $script:Author, - $script:CompanyName, - $script:Copyright, - $script:Tags, - $script:ReleaseNotes, - $script:RequiredModules, - $script:ExternalModuleDependencies, - $script:RequiredScripts, - $script:ExternalScriptDependencies, - $script:LicenseUri, - $script:ProjectUri, - $script:IconUri, - $script:DefinedCommands, - $script:DefinedFunctions, - $script:DefinedWorkflows, - $script:PrivateData - ) + $script:Version, + $script:Guid, + $script:Path, + $script:ScriptBase, + $script:Description, + $script:Author, + $script:CompanyName, + $script:Copyright, + $script:Tags, + $script:ReleaseNotes, + $script:RequiredModules, + $script:ExternalModuleDependencies, + $script:RequiredScripts, + $script:ExternalScriptDependencies, + $script:LicenseUri, + $script:ProjectUri, + $script:IconUri, + $script:DefinedCommands, + $script:DefinedFunctions, + $script:DefinedWorkflows, + $script:PrivateData +) $script:SystemEnvironmentKey = 'HKLM:\System\CurrentControlSet\Control\Session Manager\Environment' $script:UserEnvironmentKey = 'HKCU:\Environment' @@ -252,84 +233,80 @@ $script:EnvironmentVariableTarget = @{ Process = 0; User = 1; Machine = 2 } # Wildcard pattern matching configuration. $script:wildcardOptions = [System.Management.Automation.WildcardOptions]::CultureInvariant -bor ` - [System.Management.Automation.WildcardOptions]::IgnoreCase + [System.Management.Automation.WildcardOptions]::IgnoreCase $script:DynamicOptionTypeMap = @{ - 0 = [string]; # String - 1 = [string[]]; # StringArray - 2 = [int]; # Int - 3 = [switch]; # Switch - 4 = [string]; # Folder - 5 = [string]; # File - 6 = [string]; # Path - 7 = [Uri]; # Uri - 8 = [SecureString]; #SecureString - } + 0 = [string]; # String + 1 = [string[]]; # StringArray + 2 = [int]; # Int + 3 = [switch]; # Switch + 4 = [string]; # Folder + 5 = [string]; # File + 6 = [string]; # Path + 7 = [Uri]; # Uri + 8 = [SecureString]; #SecureString +} #endregion script variables #region Module message resolvers -$script:PackageManagementMessageResolverScriptBlock = { - param($i, $Message) - return (PackageManagementMessageResolver -MsgId $i, -Message $Message) - } - -$script:PackageManagementSaveModuleMessageResolverScriptBlock = { - param($i, $Message) - $PackageTarget = $LocalizedData.InstallModulewhatIfMessage - $QuerySaveUntrustedPackage = $LocalizedData.QuerySaveUntrustedPackage - - switch ($i) - { - 'ActionInstallPackage' { return "Save-Module" } - 'QueryInstallUntrustedPackage' {return $QuerySaveUntrustedPackage} - 'TargetPackage' { return $PackageTarget } - Default { - $Message = $Message -creplace "Install", "Download" - $Message = $Message -creplace "install", "download" - return (PackageManagementMessageResolver -MsgId $i, -Message $Message) - } - } - } - -$script:PackageManagementInstallModuleMessageResolverScriptBlock = { - param($i, $Message) - $PackageTarget = $LocalizedData.InstallModulewhatIfMessage - - switch ($i) - { - 'ActionInstallPackage' { return "Install-Module" } - 'TargetPackage' { return $PackageTarget } - Default { - return (PackageManagementMessageResolver -MsgId $i, -Message $Message) - } - } - } - -$script:PackageManagementUnInstallModuleMessageResolverScriptBlock = { - param($i, $Message) - $PackageTarget = $LocalizedData.InstallModulewhatIfMessage - switch ($i) - { - 'ActionUninstallPackage' { return "Uninstall-Module" } - 'TargetPackageVersion' { return $PackageTarget } - Default { - return (PackageManagementMessageResolver -MsgId $i, -Message $Message) - } - } - } - -$script:PackageManagementUpdateModuleMessageResolverScriptBlock = { - param($i, $Message) - $PackageTarget = ($LocalizedData.UpdateModulewhatIfMessage -replace "__OLDVERSION__",$($psgetItemInfo.Version)) - switch ($i) - { - 'ActionInstallPackage' { return "Update-Module" } - 'TargetPackage' { return $PackageTarget } - Default { - return (PackageManagementMessageResolver -MsgId $i, -Message $Message) - } - } - } +$script:PackageManagementMessageResolverScriptBlock = { + param($i, $Message) + return (PackageManagementMessageResolver -MsgId $i, -Message $Message) +} + +$script:PackageManagementSaveModuleMessageResolverScriptBlock = { + param($i, $Message) + $PackageTarget = $LocalizedData.InstallModulewhatIfMessage + $QuerySaveUntrustedPackage = $LocalizedData.QuerySaveUntrustedPackage + + switch ($i) { + 'ActionInstallPackage' { return "Save-Module" } + 'QueryInstallUntrustedPackage' {return $QuerySaveUntrustedPackage} + 'TargetPackage' { return $PackageTarget } + Default { + $Message = $Message -creplace "Install", "Download" + $Message = $Message -creplace "install", "download" + return (PackageManagementMessageResolver -MsgId $i, -Message $Message) + } + } +} + +$script:PackageManagementInstallModuleMessageResolverScriptBlock = { + param($i, $Message) + $PackageTarget = $LocalizedData.InstallModulewhatIfMessage + + switch ($i) { + 'ActionInstallPackage' { return "Install-Module" } + 'TargetPackage' { return $PackageTarget } + Default { + return (PackageManagementMessageResolver -MsgId $i, -Message $Message) + } + } +} + +$script:PackageManagementUnInstallModuleMessageResolverScriptBlock = { + param($i, $Message) + $PackageTarget = $LocalizedData.InstallModulewhatIfMessage + switch ($i) { + 'ActionUninstallPackage' { return "Uninstall-Module" } + 'TargetPackageVersion' { return $PackageTarget } + Default { + return (PackageManagementMessageResolver -MsgId $i, -Message $Message) + } + } +} + +$script:PackageManagementUpdateModuleMessageResolverScriptBlock = { + param($i, $Message) + $PackageTarget = ($LocalizedData.UpdateModulewhatIfMessage -replace "__OLDVERSION__", $($psgetItemInfo.Version)) + switch ($i) { + 'ActionInstallPackage' { return "Update-Module" } + 'TargetPackage' { return $PackageTarget } + Default { + return (PackageManagementMessageResolver -MsgId $i, -Message $Message) + } + } +} # Modules allowed to install non-Microsoft signed modules over Microsoft signed modules $script:WhitelistedModules = @{ @@ -338,133 +315,125 @@ $script:WhitelistedModules = @{ } function PackageManagementMessageResolver($MsgID, $Message) { - $NoMatchFound = $LocalizedData.NoMatchFound - $SourceNotFound = $LocalizedData.SourceNotFound - $ModuleIsNotTrusted = $LocalizedData.ModuleIsNotTrusted - $RepositoryIsNotTrusted = $LocalizedData.RepositoryIsNotTrusted - $QueryInstallUntrustedPackage = $LocalizedData.QueryInstallUntrustedPackage - - switch ($MsgID) - { - 'NoMatchFound' { return $NoMatchFound } - 'SourceNotFound' { return $SourceNotFound } - 'CaptionPackageNotTrusted' { return $ModuleIsNotTrusted } - 'CaptionSourceNotTrusted' { return $RepositoryIsNotTrusted } - 'QueryInstallUntrustedPackage' {return $QueryInstallUntrustedPackage} - Default { - if($Message) - { - $tempMessage = $Message -creplace "PackageSource", "PSRepository" - $tempMessage = $tempMessage -creplace "packagesource", "psrepository" - $tempMessage = $tempMessage -creplace "Package", "Module" - $tempMessage = $tempMessage -creplace "package", "module" - $tempMessage = $tempMessage -creplace "Sources", "Repositories" - $tempMessage = $tempMessage -creplace "sources", "repositories" - $tempMessage = $tempMessage -creplace "Source", "Repository" - $tempMessage = $tempMessage -creplace "source", "repository" - - return $tempMessage - } - } - } + $NoMatchFound = $LocalizedData.NoMatchFound + $SourceNotFound = $LocalizedData.SourceNotFound + $ModuleIsNotTrusted = $LocalizedData.ModuleIsNotTrusted + $RepositoryIsNotTrusted = $LocalizedData.RepositoryIsNotTrusted + $QueryInstallUntrustedPackage = $LocalizedData.QueryInstallUntrustedPackage + + switch ($MsgID) { + 'NoMatchFound' { return $NoMatchFound } + 'SourceNotFound' { return $SourceNotFound } + 'CaptionPackageNotTrusted' { return $ModuleIsNotTrusted } + 'CaptionSourceNotTrusted' { return $RepositoryIsNotTrusted } + 'QueryInstallUntrustedPackage' {return $QueryInstallUntrustedPackage} + Default { + if ($Message) { + $tempMessage = $Message -creplace "PackageSource", "PSRepository" + $tempMessage = $tempMessage -creplace "packagesource", "psrepository" + $tempMessage = $tempMessage -creplace "Package", "Module" + $tempMessage = $tempMessage -creplace "package", "module" + $tempMessage = $tempMessage -creplace "Sources", "Repositories" + $tempMessage = $tempMessage -creplace "sources", "repositories" + $tempMessage = $tempMessage -creplace "Source", "Repository" + $tempMessage = $tempMessage -creplace "source", "repository" + + return $tempMessage + } + } + } } #endregion Module message resolvers #region Script message resolvers -$script:PackageManagementMessageResolverScriptBlockForScriptCmdlets = { - param($i, $Message) - return (PackageManagementMessageResolverForScripts -MsgId $i, -Message $Message) - } - -$script:PackageManagementSaveScriptMessageResolverScriptBlock = { - param($i, $Message) - $PackageTarget = $LocalizedData.InstallScriptwhatIfMessage - $QuerySaveUntrustedPackage = $LocalizedData.QuerySaveUntrustedScriptPackage - - switch ($i) - { - 'ActionInstallPackage' { return "Save-Script" } - 'QueryInstallUntrustedPackage' {return $QuerySaveUntrustedPackage} - 'TargetPackage' { return $PackageTarget } - Default { - $Message = $Message -creplace "Install", "Download" - $Message = $Message -creplace "install", "download" - return (PackageManagementMessageResolverForScripts -MsgId $i, -Message $Message) - } - } - } - -$script:PackageManagementInstallScriptMessageResolverScriptBlock = { - param($i, $Message) - $PackageTarget = $LocalizedData.InstallScriptwhatIfMessage - - switch ($i) - { - 'ActionInstallPackage' { return "Install-Script" } - 'TargetPackage' { return $PackageTarget } - Default { - return (PackageManagementMessageResolverForScripts -MsgId $i, -Message $Message) - } - } - } - -$script:PackageManagementUnInstallScriptMessageResolverScriptBlock = { - param($i, $Message) - $PackageTarget = $LocalizedData.InstallScriptwhatIfMessage - switch ($i) - { - 'ActionUninstallPackage' { return "Uninstall-Script" } - 'TargetPackageVersion' { return $PackageTarget } - Default { - return (PackageManagementMessageResolverForScripts -MsgId $i, -Message $Message) - } - } - } - -$script:PackageManagementUpdateScriptMessageResolverScriptBlock = { - param($i, $Message) - $PackageTarget = ($LocalizedData.UpdateScriptwhatIfMessage -replace "__OLDVERSION__",$($psgetItemInfo.Version)) - switch ($i) - { - 'ActionInstallPackage' { return "Update-Script" } - 'TargetPackage' { return $PackageTarget } - Default { - return (PackageManagementMessageResolverForScripts -MsgId $i, -Message $Message) - } - } - } +$script:PackageManagementMessageResolverScriptBlockForScriptCmdlets = { + param($i, $Message) + return (PackageManagementMessageResolverForScripts -MsgId $i, -Message $Message) +} -function PackageManagementMessageResolverForScripts($MsgID, $Message) { - $NoMatchFound = $LocalizedData.NoMatchFoundForScriptName - $SourceNotFound = $LocalizedData.SourceNotFound - $ScriptIsNotTrusted = $LocalizedData.ScriptIsNotTrusted - $RepositoryIsNotTrusted = $LocalizedData.RepositoryIsNotTrusted - $QueryInstallUntrustedPackage = $LocalizedData.QueryInstallUntrustedScriptPackage +$script:PackageManagementSaveScriptMessageResolverScriptBlock = { + param($i, $Message) + $PackageTarget = $LocalizedData.InstallScriptwhatIfMessage + $QuerySaveUntrustedPackage = $LocalizedData.QuerySaveUntrustedScriptPackage + + switch ($i) { + 'ActionInstallPackage' { return "Save-Script" } + 'QueryInstallUntrustedPackage' {return $QuerySaveUntrustedPackage} + 'TargetPackage' { return $PackageTarget } + Default { + $Message = $Message -creplace "Install", "Download" + $Message = $Message -creplace "install", "download" + return (PackageManagementMessageResolverForScripts -MsgId $i, -Message $Message) + } + } +} - switch ($MsgID) - { - 'NoMatchFound' { return $NoMatchFound } - 'SourceNotFound' { return $SourceNotFound } - 'CaptionPackageNotTrusted' { return $ScriptIsNotTrusted } - 'CaptionSourceNotTrusted' { return $RepositoryIsNotTrusted } - 'QueryInstallUntrustedPackage' {return $QueryInstallUntrustedPackage} - Default { - if($Message) - { - $tempMessage = $Message -creplace "PackageSource", "PSRepository" - $tempMessage = $tempMessage -creplace "packagesource", "psrepository" - $tempMessage = $tempMessage -creplace "Package", "Script" - $tempMessage = $tempMessage -creplace "package", "script" - $tempMessage = $tempMessage -creplace "Sources", "Repositories" - $tempMessage = $tempMessage -creplace "sources", "repositories" - $tempMessage = $tempMessage -creplace "Source", "Repository" - $tempMessage = $tempMessage -creplace "source", "repository" - - return $tempMessage - } - } - } +$script:PackageManagementInstallScriptMessageResolverScriptBlock = { + param($i, $Message) + $PackageTarget = $LocalizedData.InstallScriptwhatIfMessage + + switch ($i) { + 'ActionInstallPackage' { return "Install-Script" } + 'TargetPackage' { return $PackageTarget } + Default { + return (PackageManagementMessageResolverForScripts -MsgId $i, -Message $Message) + } + } +} + +$script:PackageManagementUnInstallScriptMessageResolverScriptBlock = { + param($i, $Message) + $PackageTarget = $LocalizedData.InstallScriptwhatIfMessage + switch ($i) { + 'ActionUninstallPackage' { return "Uninstall-Script" } + 'TargetPackageVersion' { return $PackageTarget } + Default { + return (PackageManagementMessageResolverForScripts -MsgId $i, -Message $Message) + } + } +} + +$script:PackageManagementUpdateScriptMessageResolverScriptBlock = { + param($i, $Message) + $PackageTarget = ($LocalizedData.UpdateScriptwhatIfMessage -replace "__OLDVERSION__", $($psgetItemInfo.Version)) + switch ($i) { + 'ActionInstallPackage' { return "Update-Script" } + 'TargetPackage' { return $PackageTarget } + Default { + return (PackageManagementMessageResolverForScripts -MsgId $i, -Message $Message) + } + } +} + +function PackageManagementMessageResolverForScripts($MsgID, $Message) { + $NoMatchFound = $LocalizedData.NoMatchFoundForScriptName + $SourceNotFound = $LocalizedData.SourceNotFound + $ScriptIsNotTrusted = $LocalizedData.ScriptIsNotTrusted + $RepositoryIsNotTrusted = $LocalizedData.RepositoryIsNotTrusted + $QueryInstallUntrustedPackage = $LocalizedData.QueryInstallUntrustedScriptPackage + + switch ($MsgID) { + 'NoMatchFound' { return $NoMatchFound } + 'SourceNotFound' { return $SourceNotFound } + 'CaptionPackageNotTrusted' { return $ScriptIsNotTrusted } + 'CaptionSourceNotTrusted' { return $RepositoryIsNotTrusted } + 'QueryInstallUntrustedPackage' {return $QueryInstallUntrustedPackage} + Default { + if ($Message) { + $tempMessage = $Message -creplace "PackageSource", "PSRepository" + $tempMessage = $tempMessage -creplace "packagesource", "psrepository" + $tempMessage = $tempMessage -creplace "Package", "Script" + $tempMessage = $tempMessage -creplace "package", "script" + $tempMessage = $tempMessage -creplace "Sources", "Repositories" + $tempMessage = $tempMessage -creplace "sources", "repositories" + $tempMessage = $tempMessage -creplace "Source", "Repository" + $tempMessage = $tempMessage -creplace "source", "repository" + + return $tempMessage + } + } + } } #endregion Script message resolvers @@ -472,8 +441,7 @@ function PackageManagementMessageResolverForScripts($MsgID, $Message) { #region Add .Net type for Telemetry APIs and WebProxy # Check and add InternalWebProxy type -if( -not ('Microsoft.PowerShell.Commands.PowerShellGet.InternalWebProxy' -as [Type])) -{ +if ( -not ('Microsoft.PowerShell.Commands.PowerShellGet.InternalWebProxy' -as [Type])) { $RequiredAssembliesForInternalWebProxy = @( [System.Net.IWebProxy].Assembly.FullName, [System.Uri].Assembly.FullName @@ -528,29 +496,25 @@ namespace Microsoft.PowerShell.Commands.PowerShellGet } '@ - try - { + try { $AddType_prams = @{ TypeDefinition = $InternalWebProxySource - Language = 'CSharp' - ErrorAction = 'SilentlyContinue' + Language = 'CSharp' + ErrorAction = 'SilentlyContinue' } - if (-not $script:IsCoreCLR -or $script:IsNanoServer) - { + if (-not $script:IsCoreCLR -or $script:IsNanoServer) { $AddType_prams['ReferencedAssemblies'] = $RequiredAssembliesForInternalWebProxy } Add-Type @AddType_prams } - catch - { + catch { Write-Warning -Message "InternalWebProxy: $_" } } # Check and add Telemetry type -if(('Microsoft.PowerShell.Telemetry.Internal.TelemetryAPI' -as [Type]) -and - -not ('Microsoft.PowerShell.Commands.PowerShellGet.Telemetry' -as [Type])) -{ +if (('Microsoft.PowerShell.Telemetry.Internal.TelemetryAPI' -as [Type]) -and + -not ('Microsoft.PowerShell.Commands.PowerShellGet.Telemetry' -as [Type])) { $RequiredAssembliesForTelemetry = @( [System.Management.Automation.PSCmdlet].Assembly.FullName ) @@ -576,39 +540,33 @@ namespace Microsoft.PowerShell.Commands.PowerShellGet } '@ - try - { + try { $AddType_prams = @{ TypeDefinition = $TelemetrySource - Language = 'CSharp' - ErrorAction = 'SilentlyContinue' + Language = 'CSharp' + ErrorAction = 'SilentlyContinue' } $AddType_prams['ReferencedAssemblies'] = $RequiredAssembliesForTelemetry Add-Type @AddType_prams } - catch - { + catch { Write-Warning -Message "Telemetry: $_" } } # Turn ON Telemetry if the infrastructure is present on the machine $script:TelemetryEnabled = $false -if('Microsoft.PowerShell.Commands.PowerShellGet.Telemetry' -as [Type]) -{ +if ('Microsoft.PowerShell.Commands.PowerShellGet.Telemetry' -as [Type]) { $telemetryMethods = ([Microsoft.PowerShell.Commands.PowerShellGet.Telemetry] | Get-Member -Static).Name - if ($telemetryMethods.Contains("TraceMessageArtifactsNotFound") -and $telemetryMethods.Contains("TraceMessageNonPSGalleryRegistration")) - { + if ($telemetryMethods.Contains("TraceMessageArtifactsNotFound") -and $telemetryMethods.Contains("TraceMessageNonPSGalleryRegistration")) { $script:TelemetryEnabled = $true } } # Check and add Win32Helpers type $script:IsSafeX509ChainHandleAvailable = ($null -ne ('Microsoft.Win32.SafeHandles.SafeX509ChainHandle' -as [Type])) -if($script:IsWindows -and -not ('Microsoft.PowerShell.Commands.PowerShellGet.Win32Helpers' -as [Type])) -{ +if ($script:IsWindows -and -not ('Microsoft.PowerShell.Commands.PowerShellGet.Win32Helpers' -as [Type])) { $RequiredAssembliesForWin32Helpers = @() - if($script:IsSafeX509ChainHandleAvailable) - { + if ($script:IsSafeX509ChainHandleAvailable) { # It is not possible to define a single internal SafeHandle class in PowerShellGet namespace for all the supported versions of .Net Framework including .Net Core. # SafeHandleZeroOrMinusOneIsInvalid is not a public class on .Net Core, # therefore SafeX509ChainHandle will be used if it is available otherwise InternalSafeX509ChainHandle is defined below. @@ -618,8 +576,7 @@ if($script:IsWindows -and -not ('Microsoft.PowerShell.Commands.PowerShellGet.Win $SafeX509ChainHandleClassName = 'SafeX509ChainHandle' $RequiredAssembliesForWin32Helpers += [Microsoft.Win32.SafeHandles.SafeX509ChainHandle].Assembly.FullName } - else - { + else { # SafeX509ChainHandle is not available on .Net Framework 4.5 or older versions, # therefore InternalSafeX509ChainHandle is defined below. # @@ -818,21 +775,18 @@ $(if($script:IsSafeX509ChainHandleAvailable) } "@ - try - { + try { $AddType_prams = @{ TypeDefinition = $Win32HelpersSource - Language = 'CSharp' - ErrorAction = 'SilentlyContinue' + Language = 'CSharp' + ErrorAction = 'SilentlyContinue' } - if ((-not $script:IsCoreCLR -or $script:IsNanoServer) -and $RequiredAssembliesForWin32Helpers) - { + if ((-not $script:IsCoreCLR -or $script:IsNanoServer) -and $RequiredAssembliesForWin32Helpers) { $AddType_prams['ReferencedAssemblies'] = $RequiredAssembliesForWin32Helpers } Add-Type @AddType_prams } - catch - { + catch { Write-Warning -Message "Win32Helpers: $_" } } diff --git a/src/PowerShellGet/public/psgetfunctions/Find-Module.ps1 b/src/PowerShellGet/public/psgetfunctions/Find-Module.ps1 index 33fa55b0..b67821f7 100644 --- a/src/PowerShellGet/public/psgetfunctions/Find-Module.ps1 +++ b/src/PowerShellGet/public/psgetfunctions/Find-Module.ps1 @@ -1,29 +1,28 @@ -function Find-Module -{ +function Find-Module { <# .ExternalHelp PSModule-help.xml #> - [CmdletBinding(HelpUri='https://go.microsoft.com/fwlink/?LinkID=398574')] + [CmdletBinding(HelpUri = 'https://go.microsoft.com/fwlink/?LinkID=398574')] [outputtype("PSCustomObject[]")] Param ( - [Parameter(ValueFromPipelineByPropertyName=$true, - Position=0)] + [Parameter(ValueFromPipelineByPropertyName = $true, + Position = 0)] [ValidateNotNullOrEmpty()] [string[]] $Name, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [ValidateNotNull()] [string] $MinimumVersion, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [ValidateNotNull()] [string] $MaximumVersion, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [ValidateNotNull()] [string] $RequiredVersion, @@ -48,7 +47,7 @@ function Find-Module [Parameter()] [ValidateNotNull()] - [ValidateSet('DscResource','Cmdlet','Function','RoleCapability')] + [ValidateSet('DscResource', 'Cmdlet', 'Function', 'RoleCapability')] [string[]] $Includes, @@ -67,12 +66,12 @@ function Find-Module [string[]] $Command, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [Uri] $Proxy, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [PSCredential] $ProxyCredential, @@ -81,7 +80,7 @@ function Find-Module [string[]] $Repository, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [PSCredential] $Credential, @@ -90,25 +89,20 @@ function Find-Module $AllowPrerelease ) - Begin - { - Get-PSGalleryApiAvailability -Repository $Repository - + Begin { Install-NuGetClientBinaries -CallerPSCmdlet $PSCmdlet -Proxy $Proxy -ProxyCredential $ProxyCredential } - Process - { + Process { $ValidationResult = Validate-VersionParameters -CallerPSCmdlet $PSCmdlet ` - -Name $Name ` - -MinimumVersion $MinimumVersion ` - -MaximumVersion $MaximumVersion ` - -RequiredVersion $RequiredVersion ` - -AllVersions:$AllVersions ` - -AllowPrerelease:$AllowPrerelease - - if(-not $ValidationResult) - { + -Name $Name ` + -MinimumVersion $MinimumVersion ` + -MaximumVersion $MaximumVersion ` + -RequiredVersion $RequiredVersion ` + -AllVersions:$AllVersions ` + -AllowPrerelease:$AllowPrerelease + + if (-not $ValidationResult) { # Validate-VersionParameters throws the error. # returning to avoid further execution when different values are specified for -ErrorAction parameter return @@ -116,19 +110,18 @@ function Find-Module $PSBoundParameters["Provider"] = $script:PSModuleProviderName $PSBoundParameters[$script:PSArtifactType] = $script:PSArtifactTypeModule - if($AllowPrerelease) { + if ($AllowPrerelease) { $PSBoundParameters[$script:AllowPrereleaseVersions] = $true } $null = $PSBoundParameters.Remove("AllowPrerelease") - if($PSBoundParameters.ContainsKey("Repository")) - { + if ($PSBoundParameters.ContainsKey("Repository")) { $PSBoundParameters["Source"] = $Repository $null = $PSBoundParameters.Remove("Repository") $ev = $null $null = Get-PSRepository -Name $Repository -ErrorVariable ev -verbose:$false - if($ev) { return } + if ($ev) { return } } $PSBoundParameters["MessageResolver"] = $script:PackageManagementMessageResolverScriptBlock @@ -137,32 +130,27 @@ function Find-Module # No Telemetry must be performed if PSGallery is not in the supplied list of Repositories $isRepositoryNullOrPSGallerySpecified = $false - if ($Repository -and ($Repository -Contains $Script:PSGalleryModuleSource)) - { + if ($Repository -and ($Repository -Contains $Script:PSGalleryModuleSource)) { $isRepositoryNullOrPSGallerySpecified = $true } - elseif(-not $Repository) - { + elseif (-not $Repository) { $psgalleryRepo = Get-PSRepository -Name $Script:PSGalleryModuleSource ` - -ErrorAction SilentlyContinue ` - -WarningAction SilentlyContinue - if($psgalleryRepo) - { + -ErrorAction SilentlyContinue ` + -WarningAction SilentlyContinue + if ($psgalleryRepo) { $isRepositoryNullOrPSGallerySpecified = $true } } - PackageManagement\Find-Package @PSBoundParameters | Microsoft.PowerShell.Core\ForEach-Object { + PackageManagement\Find-Package @PSBoundParameters | Microsoft.PowerShell.Core\ForEach-Object { $psgetItemInfo = New-PSGetItemInfo -SoftwareIdentity $_ -Type $script:PSArtifactTypeModule - if ($AllVersions -and -not $AllowPrerelease) - { + if ($AllVersions -and -not $AllowPrerelease) { # If AllVersions is specified but not AllowPrerelease, we should only return stable release versions. # PackageManagement returns ALL versions (including prerelease) when AllVersions is specified, regardless of the value of AllowPrerelease. # Filtering results returned from PackageManagement based on flags. - if ($psgetItemInfo.AdditionalMetadata -and $psgetItemInfo.AdditionalMetadata.IsPrerelease -eq 'false') - { + if ($psgetItemInfo.AdditionalMetadata -and $psgetItemInfo.AdditionalMetadata.IsPrerelease -eq 'false') { $psgetItemInfo } } @@ -173,8 +161,7 @@ function Find-Module if ($psgetItemInfo -and $isRepositoryNullOrPSGallerySpecified -and $script:TelemetryEnabled -and - ($psgetItemInfo.Repository -eq $Script:PSGalleryModuleSource)) - { + ($psgetItemInfo.Repository -eq $Script:PSGalleryModuleSource)) { $modulesFoundInPSGallery += $psgetItemInfo.Name } } @@ -182,9 +169,8 @@ function Find-Module # Perform Telemetry if Repository is not supplied or Repository contains PSGallery # We are only interested in finding modules not in PSGallery - if ($isRepositoryNullOrPSGallerySpecified) - { + if ($isRepositoryNullOrPSGallerySpecified) { Log-ArtifactNotFoundInPSGallery -SearchedName $Name -FoundName $modulesFoundInPSGallery -operationName 'PSGET_FIND_MODULE' } } -} \ No newline at end of file +} diff --git a/src/PowerShellGet/public/psgetfunctions/Find-Script.ps1 b/src/PowerShellGet/public/psgetfunctions/Find-Script.ps1 index cfd09cdc..84597f6b 100644 --- a/src/PowerShellGet/public/psgetfunctions/Find-Script.ps1 +++ b/src/PowerShellGet/public/psgetfunctions/Find-Script.ps1 @@ -1,29 +1,28 @@ -function Find-Script -{ +function Find-Script { <# .ExternalHelp PSModule-help.xml #> - [CmdletBinding(HelpUri='https://go.microsoft.com/fwlink/?LinkId=619785')] + [CmdletBinding(HelpUri = 'https://go.microsoft.com/fwlink/?LinkId=619785')] [outputtype("PSCustomObject[]")] Param ( - [Parameter(ValueFromPipelineByPropertyName=$true, - Position=0)] + [Parameter(ValueFromPipelineByPropertyName = $true, + Position = 0)] [ValidateNotNullOrEmpty()] [string[]] $Name, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [ValidateNotNull()] [string] $MinimumVersion, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [ValidateNotNull()] [string] $MaximumVersion, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [ValidateNotNull()] [string] $RequiredVersion, @@ -48,7 +47,7 @@ function Find-Script [Parameter()] [ValidateNotNull()] - [ValidateSet('Function','Workflow')] + [ValidateSet('Function', 'Workflow')] [string[]] $Includes, @@ -57,12 +56,12 @@ function Find-Script [string[]] $Command, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [Uri] $Proxy, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [PSCredential] $ProxyCredential, @@ -71,7 +70,7 @@ function Find-Script [string[]] $Repository, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [PSCredential] $Credential, @@ -80,25 +79,20 @@ function Find-Script $AllowPrerelease ) - Begin - { - Get-PSGalleryApiAvailability -Repository $Repository - + Begin { Install-NuGetClientBinaries -CallerPSCmdlet $PSCmdlet -Proxy $Proxy -ProxyCredential $ProxyCredential } - Process - { + Process { $ValidationResult = Validate-VersionParameters -CallerPSCmdlet $PSCmdlet ` - -Name $Name ` - -MinimumVersion $MinimumVersion ` - -MaximumVersion $MaximumVersion ` - -RequiredVersion $RequiredVersion ` - -AllVersions:$AllVersions ` - -AllowPrerelease:$AllowPrerelease - - if(-not $ValidationResult) - { + -Name $Name ` + -MinimumVersion $MinimumVersion ` + -MaximumVersion $MaximumVersion ` + -RequiredVersion $RequiredVersion ` + -AllVersions:$AllVersions ` + -AllowPrerelease:$AllowPrerelease + + if (-not $ValidationResult) { # Validate-VersionParameters throws the error. # returning to avoid further execution when different values are specified for -ErrorAction parameter return @@ -106,38 +100,34 @@ function Find-Script $PSBoundParameters['Provider'] = $script:PSModuleProviderName $PSBoundParameters[$script:PSArtifactType] = $script:PSArtifactTypeScript - if($AllowPrerelease) { + if ($AllowPrerelease) { $PSBoundParameters[$script:AllowPrereleaseVersions] = $true } $null = $PSBoundParameters.Remove("AllowPrerelease") - if($PSBoundParameters.ContainsKey("Repository")) - { + if ($PSBoundParameters.ContainsKey("Repository")) { $PSBoundParameters["Source"] = $Repository $null = $PSBoundParameters.Remove("Repository") $ev = $null $repositories = Get-PSRepository -Name $Repository -ErrorVariable ev -verbose:$false - if($ev) { return } + if ($ev) { return } $RepositoriesWithoutScriptSourceLocation = $false - foreach($repo in $repositories) - { - if(-not $repo.ScriptSourceLocation) - { + foreach ($repo in $repositories) { + if (-not $repo.ScriptSourceLocation) { $message = $LocalizedData.ScriptSourceLocationIsMissing -f ($repo.Name) Write-Error -Message $message ` - -ErrorId 'ScriptSourceLocationIsMissing' ` - -Category InvalidArgument ` - -TargetObject $repo.Name ` - -Exception 'System.ArgumentException' + -ErrorId 'ScriptSourceLocationIsMissing' ` + -Category InvalidArgument ` + -TargetObject $repo.Name ` + -Exception 'System.ArgumentException' $RepositoriesWithoutScriptSourceLocation = $true } } - if($RepositoriesWithoutScriptSourceLocation) - { + if ($RepositoriesWithoutScriptSourceLocation) { return } } @@ -148,52 +138,45 @@ function Find-Script # No Telemetry must be performed if PSGallery is not in the supplied list of Repositories $isRepositoryNullOrPSGallerySpecified = $false - if ($Repository -and ($Repository -Contains $Script:PSGalleryModuleSource)) - { + if ($Repository -and ($Repository -Contains $Script:PSGalleryModuleSource)) { $isRepositoryNullOrPSGallerySpecified = $true } - elseif(-not $Repository) - { + elseif (-not $Repository) { $psgalleryRepo = Get-PSRepository -Name $Script:PSGalleryModuleSource ` - -ErrorAction SilentlyContinue ` - -WarningAction SilentlyContinue + -ErrorAction SilentlyContinue ` + -WarningAction SilentlyContinue # And check for IsDefault? - if($psgalleryRepo) - { + if ($psgalleryRepo) { $isRepositoryNullOrPSGallerySpecified = $true } } PackageManagement\Find-Package @PSBoundParameters | Microsoft.PowerShell.Core\ForEach-Object { - $psgetItemInfo = New-PSGetItemInfo -SoftwareIdentity $_ -Type $script:PSArtifactTypeScript - - if ($AllVersions -and -not $AllowPrerelease) - { - # If AllVersions is specified but not AllowPrerelease, we should only return stable release versions. - # PackageManagement returns ALL versions (including prerelease) when AllVersions is specified, regardless of the value of AllowPrerelease. - # Filtering results returned from PackageManagement based on flags. - if ($psgetItemInfo.AdditionalMetadata -and $psgetItemInfo.AdditionalMetadata.IsPrerelease -eq $false) - { - $psgetItemInfo - } - } - else { + $psgetItemInfo = New-PSGetItemInfo -SoftwareIdentity $_ -Type $script:PSArtifactTypeScript + + if ($AllVersions -and -not $AllowPrerelease) { + # If AllVersions is specified but not AllowPrerelease, we should only return stable release versions. + # PackageManagement returns ALL versions (including prerelease) when AllVersions is specified, regardless of the value of AllowPrerelease. + # Filtering results returned from PackageManagement based on flags. + if ($psgetItemInfo.AdditionalMetadata -and $psgetItemInfo.AdditionalMetadata.IsPrerelease -eq $false) { $psgetItemInfo } + } + else { + $psgetItemInfo + } - if ($psgetItemInfo -and - $isRepositoryNullOrPSGallerySpecified -and - $script:TelemetryEnabled -and - ($psgetItemInfo.Repository -eq $Script:PSGalleryModuleSource)) - { - $scriptsFoundInPSGallery += $psgetItemInfo.Name - } + if ($psgetItemInfo -and + $isRepositoryNullOrPSGallerySpecified -and + $script:TelemetryEnabled -and + ($psgetItemInfo.Repository -eq $Script:PSGalleryModuleSource)) { + $scriptsFoundInPSGallery += $psgetItemInfo.Name } + } # Perform Telemetry if Repository is not supplied or Repository contains PSGallery # We are only interested in finding artifacts not in PSGallery - if ($isRepositoryNullOrPSGallerySpecified) - { + if ($isRepositoryNullOrPSGallerySpecified) { Log-ArtifactNotFoundInPSGallery -SearchedName $Name -FoundName $scriptsFoundInPSGallery -operationName PSGET_FIND_SCRIPT } } diff --git a/src/PowerShellGet/public/psgetfunctions/Get-PSRepository.ps1 b/src/PowerShellGet/public/psgetfunctions/Get-PSRepository.ps1 index 2d47bec6..9151030b 100644 --- a/src/PowerShellGet/public/psgetfunctions/Get-PSRepository.ps1 +++ b/src/PowerShellGet/public/psgetfunctions/Get-PSRepository.ps1 @@ -1,31 +1,25 @@ -function Get-PSRepository -{ +function Get-PSRepository { <# .ExternalHelp PSModule-help.xml #> - [CmdletBinding(HelpUri='https://go.microsoft.com/fwlink/?LinkID=517127')] + [CmdletBinding(HelpUri = 'https://go.microsoft.com/fwlink/?LinkID=517127')] Param ( - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [string[]] $Name ) - Begin - { - Get-PSGalleryApiAvailability -Repository $Name + Begin { } - Process - { + Process { $PSBoundParameters["Provider"] = $script:PSModuleProviderName $PSBoundParameters["MessageResolver"] = $script:PackageManagementMessageResolverScriptBlock - if($Name) - { - foreach($sourceName in $Name) - { + if ($Name) { + foreach ($sourceName in $Name) { $PSBoundParameters["Name"] = $sourceName $packageSources = PackageManagement\Get-PackageSource @PSBoundParameters @@ -33,11 +27,10 @@ function Get-PSRepository $packageSources | Microsoft.PowerShell.Core\ForEach-Object { New-ModuleSourceFromPackageSource -PackageSource $_ } } } - else - { + else { $packageSources = PackageManagement\Get-PackageSource @PSBoundParameters $packageSources | Microsoft.PowerShell.Core\ForEach-Object { New-ModuleSourceFromPackageSource -PackageSource $_ } } } -} \ No newline at end of file +} diff --git a/src/PowerShellGet/public/psgetfunctions/Install-Module.ps1 b/src/PowerShellGet/public/psgetfunctions/Install-Module.ps1 index bbb7ff72..4246f182 100644 --- a/src/PowerShellGet/public/psgetfunctions/Install-Module.ps1 +++ b/src/PowerShellGet/public/psgetfunctions/Install-Module.ps1 @@ -1,68 +1,67 @@ -function Install-Module -{ +function Install-Module { <# .ExternalHelp PSModule-help.xml #> - [CmdletBinding(DefaultParameterSetName='NameParameterSet', - HelpUri='https://go.microsoft.com/fwlink/?LinkID=398573', - SupportsShouldProcess=$true)] + [CmdletBinding(DefaultParameterSetName = 'NameParameterSet', + HelpUri = 'https://go.microsoft.com/fwlink/?LinkID=398573', + SupportsShouldProcess = $true)] Param ( - [Parameter(Mandatory=$true, - ValueFromPipelineByPropertyName=$true, - Position=0, - ParameterSetName='NameParameterSet')] + [Parameter(Mandatory = $true, + ValueFromPipelineByPropertyName = $true, + Position = 0, + ParameterSetName = 'NameParameterSet')] [ValidateNotNullOrEmpty()] [string[]] $Name, - [Parameter(Mandatory=$true, - ValueFromPipeline=$true, - ValueFromPipelineByPropertyName=$true, - Position=0, - ParameterSetName='InputObject')] + [Parameter(Mandatory = $true, + ValueFromPipeline = $true, + ValueFromPipelineByPropertyName = $true, + Position = 0, + ParameterSetName = 'InputObject')] [ValidateNotNull()] [PSCustomObject[]] $InputObject, - [Parameter(ValueFromPipelineByPropertyName=$true, - ParameterSetName='NameParameterSet')] + [Parameter(ValueFromPipelineByPropertyName = $true, + ParameterSetName = 'NameParameterSet')] [ValidateNotNull()] [string] $MinimumVersion, - [Parameter(ValueFromPipelineByPropertyName=$true, - ParameterSetName='NameParameterSet')] + [Parameter(ValueFromPipelineByPropertyName = $true, + ParameterSetName = 'NameParameterSet')] [ValidateNotNull()] [string] $MaximumVersion, - [Parameter(ValueFromPipelineByPropertyName=$true, - ParameterSetName='NameParameterSet')] + [Parameter(ValueFromPipelineByPropertyName = $true, + ParameterSetName = 'NameParameterSet')] [ValidateNotNull()] [string] $RequiredVersion, - [Parameter(ParameterSetName='NameParameterSet')] + [Parameter(ParameterSetName = 'NameParameterSet')] [ValidateNotNullOrEmpty()] [string[]] $Repository, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [PSCredential] $Credential, [Parameter()] - [ValidateSet("CurrentUser","AllUsers")] + [ValidateSet("CurrentUser", "AllUsers")] [string] $Scope, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [Uri] $Proxy, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [PSCredential] $ProxyCredential, @@ -78,7 +77,7 @@ function Install-Module [switch] $Force, - [Parameter(ParameterSetName='NameParameterSet')] + [Parameter(ParameterSetName = 'NameParameterSet')] [switch] $AllowPrerelease, @@ -87,29 +86,23 @@ function Install-Module $AcceptLicense ) - Begin - { - Get-PSGalleryApiAvailability -Repository $Repository - - if($Scope -eq "AllUsers" -and -not (Test-RunningAsElevated)) - { + Begin { + if ($Scope -eq "AllUsers" -and -not (Test-RunningAsElevated)) { # Throw an error when Install-Module is used as a non-admin user and '-Scope AllUsers' $message = $LocalizedData.InstallModuleAdminPrivilegeRequiredForAllUsersScope -f @($script:programFilesModulesPath, $script:MyDocumentsModulesPath) ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $message ` - -ErrorId "InstallModuleAdminPrivilegeRequiredForAllUsersScope" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidArgument + -ExceptionMessage $message ` + -ErrorId "InstallModuleAdminPrivilegeRequiredForAllUsersScope" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidArgument } - # If no scope is specified, default installation will be to AllUsers only + # If no scope is specified, default installation will be to AllUsers only # If running admin on Windows with PowerShell less than v6. - if (-not $Scope) - { + if (-not $Scope) { $Scope = "CurrentUser" - if(-not $script:IsCoreCLR -and (Test-RunningAsElevated)) - { + if (-not $script:IsCoreCLR -and (Test-RunningAsElevated)) { $Scope = "AllUsers" } } @@ -124,8 +117,7 @@ function Install-Module $SourcesDeniedTrust = @() } - Process - { + Process { $RepositoryIsNotTrusted = $LocalizedData.RepositoryIsNotTrusted $QueryInstallUntrustedPackage = $LocalizedData.QueryInstallUntrustedPackage $PackageTarget = $LocalizedData.InstallModulewhatIfMessage @@ -134,46 +126,41 @@ function Install-Module $PSBoundParameters["MessageResolver"] = $script:PackageManagementInstallModuleMessageResolverScriptBlock $PSBoundParameters[$script:PSArtifactType] = $script:PSArtifactTypeModule $PSBoundParameters['Scope'] = $Scope - if($AllowPrerelease) { + if ($AllowPrerelease) { $PSBoundParameters[$script:AllowPrereleaseVersions] = $true } $null = $PSBoundParameters.Remove("AllowPrerelease") - if($PSCmdlet.ParameterSetName -eq "NameParameterSet") - { + if ($PSCmdlet.ParameterSetName -eq "NameParameterSet") { $ValidationResult = Validate-VersionParameters -CallerPSCmdlet $PSCmdlet ` - -Name $Name ` - -TestWildcardsInName ` - -MinimumVersion $MinimumVersion ` - -MaximumVersion $MaximumVersion ` - -RequiredVersion $RequiredVersion ` - -AllowPrerelease:$AllowPrerelease - - if(-not $ValidationResult) - { + -Name $Name ` + -TestWildcardsInName ` + -MinimumVersion $MinimumVersion ` + -MaximumVersion $MaximumVersion ` + -RequiredVersion $RequiredVersion ` + -AllowPrerelease:$AllowPrerelease + + if (-not $ValidationResult) { # Validate-VersionParameters throws the error. # returning to avoid further execution when different values are specified for -ErrorAction parameter return } - if($PSBoundParameters.ContainsKey("Repository")) - { + if ($PSBoundParameters.ContainsKey("Repository")) { $PSBoundParameters["Source"] = $Repository $null = $PSBoundParameters.Remove("Repository") $ev = $null $null = Get-PSRepository -Name $Repository -ErrorVariable ev -verbose:$false - if($ev) { return } + if ($ev) { return } } $null = PackageManagement\Install-Package @PSBoundParameters } - elseif($PSCmdlet.ParameterSetName -eq "InputObject") - { + elseif ($PSCmdlet.ParameterSetName -eq "InputObject") { $null = $PSBoundParameters.Remove("InputObject") - foreach($inputValue in $InputObject) - { + foreach ($inputValue in $InputObject) { if (($inputValue.PSTypeNames -notcontains "Microsoft.PowerShell.Commands.PSRepositoryItemInfo") -and ($inputValue.PSTypeNames -notcontains "Deserialized.Microsoft.PowerShell.Commands.PSRepositoryItemInfo") -and ($inputValue.PSTypeNames -notcontains "Microsoft.PowerShell.Commands.PSGetCommandInfo") -and @@ -181,41 +168,36 @@ function Install-Module ($inputValue.PSTypeNames -notcontains "Microsoft.PowerShell.Commands.PSGetDscResourceInfo") -and ($inputValue.PSTypeNames -notcontains "Deserialized.Microsoft.PowerShell.Commands.PSGetDscResourceInfo") -and ($inputValue.PSTypeNames -notcontains "Microsoft.PowerShell.Commands.PSGetRoleCapabilityInfo") -and - ($inputValue.PSTypeNames -notcontains "Deserialized.Microsoft.PowerShell.Commands.PSGetRoleCapabilityInfo")) - { + ($inputValue.PSTypeNames -notcontains "Deserialized.Microsoft.PowerShell.Commands.PSGetRoleCapabilityInfo")) { ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $LocalizedData.InvalidInputObjectValue ` - -ErrorId "InvalidInputObjectValue" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidArgument ` - -ExceptionObject $inputValue + -ExceptionMessage $LocalizedData.InvalidInputObjectValue ` + -ErrorId "InvalidInputObjectValue" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidArgument ` + -ExceptionObject $inputValue } - if( ($inputValue.PSTypeNames -contains "Microsoft.PowerShell.Commands.PSGetDscResourceInfo") -or + if ( ($inputValue.PSTypeNames -contains "Microsoft.PowerShell.Commands.PSGetDscResourceInfo") -or ($inputValue.PSTypeNames -contains "Deserialized.Microsoft.PowerShell.Commands.PSGetDscResourceInfo") -or ($inputValue.PSTypeNames -contains "Microsoft.PowerShell.Commands.PSGetCommandInfo") -or ($inputValue.PSTypeNames -contains "Deserialized.Microsoft.PowerShell.Commands.PSGetCommandInfo") -or ($inputValue.PSTypeNames -contains "Microsoft.PowerShell.Commands.PSGetRoleCapabilityInfo") -or - ($inputValue.PSTypeNames -contains "Deserialized.Microsoft.PowerShell.Commands.PSGetRoleCapabilityInfo")) - { + ($inputValue.PSTypeNames -contains "Deserialized.Microsoft.PowerShell.Commands.PSGetRoleCapabilityInfo")) { $psgetModuleInfo = $inputValue.PSGetModuleInfo } - else - { + else { $psgetModuleInfo = $inputValue } # Skip the module name if it is already tried in the current pipeline - if($moduleNamesInPipeline -contains $psgetModuleInfo.Name) - { + if ($moduleNamesInPipeline -contains $psgetModuleInfo.Name) { continue } $moduleNamesInPipeline += $psgetModuleInfo.Name if ($psgetModuleInfo.PowerShellGetFormatVersion -and - ($script:SupportedPSGetFormatVersionMajors -notcontains $psgetModuleInfo.PowerShellGetFormatVersion.Major)) - { + ($script:SupportedPSGetFormatVersionMajors -notcontains $psgetModuleInfo.PowerShellGetFormatVersion.Major)) { $message = $LocalizedData.NotSupportedPowerShellGetFormatVersion -f ($psgetModuleInfo.Name, $psgetModuleInfo.PowerShellGetFormatVersion, $psgetModuleInfo.Name) Write-Error -Message $message -ErrorId "NotSupportedPowerShellGetFormatVersion" -Category InvalidOperation continue @@ -236,52 +218,42 @@ function Install-Module #Check if module is already installed $InstalledModuleInfo = Test-ModuleInstalled -Name $psgetModuleInfo.Name -RequiredVersion $psgetModuleInfo.Version - if(-not $Force -and $InstalledModuleInfo -ne $null) - { + if (-not $Force -and $InstalledModuleInfo -ne $null) { $message = $LocalizedData.ModuleAlreadyInstalledVerbose -f ($InstalledModuleInfo.Version, $InstalledModuleInfo.Name, $InstalledModuleInfo.ModuleBase) Write-Verbose -Message $message } - else - { - $source = $psgetModuleInfo.Repository + else { + $source = $psgetModuleInfo.Repository $installationPolicy = (Get-PSRepository -Name $source).InstallationPolicy $ShouldProcessMessage = $PackageTarget -f ($psgetModuleInfo.Name, $psgetModuleInfo.Version) - if($psCmdlet.ShouldProcess($ShouldProcessMessage)) - { - if($installationPolicy.Equals("Untrusted", [StringComparison]::OrdinalIgnoreCase)) - { - if(-not($YesToAll -or $NoToAll -or $SourceSGrantedTrust.Contains($source) -or $sourcesDeniedTrust.Contains($source) -or $Force)) - { - $message = $QueryInstallUntrustedPackage -f ($psgetModuleInfo.Name, $psgetModuleInfo.RepositorySourceLocation) - if($PSVersionTable.PSVersion -ge '5.0.0') - { - $sourceTrusted = $psCmdlet.ShouldContinue("$message", "$RepositoryIsNotTrusted",$true, [ref]$YesToAll, [ref]$NoToAll) + if ($psCmdlet.ShouldProcess($ShouldProcessMessage)) { + if ($installationPolicy.Equals("Untrusted", [StringComparison]::OrdinalIgnoreCase)) { + if (-not($YesToAll -or $NoToAll -or $SourceSGrantedTrust.Contains($source) -or $sourcesDeniedTrust.Contains($source) -or $Force)) { + $message = $QueryInstallUntrustedPackage -f ($psgetModuleInfo.Name, $psgetModuleInfo.RepositorySourceLocation) + if ($PSVersionTable.PSVersion -ge '5.0.0') { + $sourceTrusted = $psCmdlet.ShouldContinue("$message", "$RepositoryIsNotTrusted", $true, [ref]$YesToAll, [ref]$NoToAll) } - else - { - $sourceTrusted = $psCmdlet.ShouldContinue("$message", "$RepositoryIsNotTrusted", [ref]$YesToAll, [ref]$NoToAll) + else { + $sourceTrusted = $psCmdlet.ShouldContinue("$message", "$RepositoryIsNotTrusted", [ref]$YesToAll, [ref]$NoToAll) } - if($sourceTrusted) - { - $SourceSGrantedTrust+=$source + if ($sourceTrusted) { + $SourceSGrantedTrust += $source } - else - { - $SourcesDeniedTrust+=$source + else { + $SourcesDeniedTrust += $source } } } - if($installationPolicy.Equals("trusted", [StringComparison]::OrdinalIgnoreCase) -or $SourceSGrantedTrust.Contains($source) -or $YesToAll -or $Force) - { + if ($installationPolicy.Equals("trusted", [StringComparison]::OrdinalIgnoreCase) -or $SourceSGrantedTrust.Contains($source) -or $YesToAll -or $Force) { $PSBoundParameters["Force"] = $true - $null = PackageManagement\Install-Package @PSBoundParameters + $null = PackageManagement\Install-Package @PSBoundParameters } } } } } } -} \ No newline at end of file +} diff --git a/src/PowerShellGet/public/psgetfunctions/Install-Script.ps1 b/src/PowerShellGet/public/psgetfunctions/Install-Script.ps1 index 917eed37..4a5be9fb 100644 --- a/src/PowerShellGet/public/psgetfunctions/Install-Script.ps1 +++ b/src/PowerShellGet/public/psgetfunctions/Install-Script.ps1 @@ -85,8 +85,6 @@ function Install-Script Begin { - Get-PSGalleryApiAvailability -Repository $Repository - if($Scope -eq "AllUsers" -and -not (Test-RunningAsElevated)) { # Throw an error when Install-Script is used as a non-admin user and '-Scope AllUsers' @@ -99,9 +97,9 @@ function Install-Script -ErrorCategory InvalidArgument } - # If no scope is specified, default installation will be to AllUsers only + # If no scope is specified, default installation will be to AllUsers only # If running admin on Windows with PowerShell less than v6. - if (-not $Scope) + if (-not $Scope) { $Scope = "CurrentUser" if(-not $script:IsCoreCLR -and (Test-RunningAsElevated)) diff --git a/src/PowerShellGet/public/psgetfunctions/Publish-Module.ps1 b/src/PowerShellGet/public/psgetfunctions/Publish-Module.ps1 index daaeeaa5..1a8ec5d3 100644 --- a/src/PowerShellGet/public/psgetfunctions/Publish-Module.ps1 +++ b/src/PowerShellGet/public/psgetfunctions/Publish-Module.ps1 @@ -1,29 +1,28 @@ -function Publish-Module -{ +function Publish-Module { <# .ExternalHelp PSModule-help.xml #> - [CmdletBinding(SupportsShouldProcess=$true, - PositionalBinding=$false, - HelpUri='https://go.microsoft.com/fwlink/?LinkID=398575', - DefaultParameterSetName="ModuleNameParameterSet")] + [CmdletBinding(SupportsShouldProcess = $true, + PositionalBinding = $false, + HelpUri = 'https://go.microsoft.com/fwlink/?LinkID=398575', + DefaultParameterSetName = "ModuleNameParameterSet")] Param ( - [Parameter(Mandatory=$true, - ParameterSetName="ModuleNameParameterSet", - ValueFromPipelineByPropertyName=$true)] + [Parameter(Mandatory = $true, + ParameterSetName = "ModuleNameParameterSet", + ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [string] $Name, - [Parameter(Mandatory=$true, - ParameterSetName="ModulePathParameterSet", - ValueFromPipelineByPropertyName=$true)] + [Parameter(Mandatory = $true, + ParameterSetName = "ModulePathParameterSet", + ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [string] $Path, - [Parameter(ParameterSetName="ModuleNameParameterSet")] + [Parameter(ParameterSetName = "ModuleNameParameterSet")] [ValidateNotNullOrEmpty()] [string] $RequiredVersion, @@ -38,7 +37,7 @@ function Publish-Module [string] $Repository = $Script:PSGalleryModuleSource, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [PSCredential] $Credential, @@ -75,143 +74,124 @@ function Publish-Module [switch] $Force, - [Parameter(ParameterSetName="ModuleNameParameterSet")] + [Parameter(ParameterSetName = "ModuleNameParameterSet")] [switch] $AllowPrerelease ) - Begin - { - Get-PSGalleryApiAvailability -Repository $Repository - - if($LicenseUri -and -not (Test-WebUri -uri $LicenseUri)) - { + Begin { + if ($LicenseUri -and -not (Test-WebUri -uri $LicenseUri)) { $message = $LocalizedData.InvalidWebUri -f ($LicenseUri, "LicenseUri") ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $message ` - -ErrorId "InvalidWebUri" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidArgument ` - -ExceptionObject $LicenseUri + -ExceptionMessage $message ` + -ErrorId "InvalidWebUri" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidArgument ` + -ExceptionObject $LicenseUri } - if($IconUri -and -not (Test-WebUri -uri $IconUri)) - { + if ($IconUri -and -not (Test-WebUri -uri $IconUri)) { $message = $LocalizedData.InvalidWebUri -f ($IconUri, "IconUri") ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $message ` - -ErrorId "InvalidWebUri" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidArgument ` - -ExceptionObject $IconUri + -ExceptionMessage $message ` + -ErrorId "InvalidWebUri" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidArgument ` + -ExceptionObject $IconUri } - if($ProjectUri -and -not (Test-WebUri -uri $ProjectUri)) - { + if ($ProjectUri -and -not (Test-WebUri -uri $ProjectUri)) { $message = $LocalizedData.InvalidWebUri -f ($ProjectUri, "ProjectUri") ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $message ` - -ErrorId "InvalidWebUri" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidArgument ` - -ExceptionObject $ProjectUri + -ExceptionMessage $message ` + -ErrorId "InvalidWebUri" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidArgument ` + -ExceptionObject $ProjectUri } Install-NuGetClientBinaries -CallerPSCmdlet $PSCmdlet -BootstrapNuGetExe -Force:$Force } - Process - { - if($Repository -eq $Script:PSGalleryModuleSource) - { + Process { + if ($Repository -eq $Script:PSGalleryModuleSource) { $moduleSource = Get-PSRepository -Name $Repository -ErrorAction SilentlyContinue -WarningAction SilentlyContinue - if(-not $moduleSource) - { + if (-not $moduleSource) { $message = $LocalizedData.PSGalleryNotFound -f ($Repository) ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $message ` - -ErrorId 'PSGalleryNotFound' ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidArgument ` - -ExceptionObject $Repository + -ExceptionMessage $message ` + -ErrorId 'PSGalleryNotFound' ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidArgument ` + -ExceptionObject $Repository return } } - else - { + else { $ev = $null $moduleSource = Get-PSRepository -Name $Repository -ErrorVariable ev - if($ev) { return } + if ($ev) { return } } $DestinationLocation = $moduleSource.PublishLocation - if(-not $DestinationLocation -or - (-not (Microsoft.PowerShell.Management\Test-Path $DestinationLocation) -and - -not (Test-WebUri -uri $DestinationLocation))) - + if (-not $DestinationLocation -or + (-not (Microsoft.PowerShell.Management\Test-Path $DestinationLocation) -and + -not (Test-WebUri -uri $DestinationLocation))) { $message = $LocalizedData.PSGalleryPublishLocationIsMissing -f ($Repository, $Repository) ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $message ` - -ErrorId "PSGalleryPublishLocationIsMissing" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidArgument ` - -ExceptionObject $Repository + -ExceptionMessage $message ` + -ErrorId "PSGalleryPublishLocationIsMissing" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidArgument ` + -ExceptionObject $Repository } $message = $LocalizedData.PublishLocation -f ($DestinationLocation) Write-Verbose -Message $message - if(-not $NuGetApiKey.Trim()) - { - if(Microsoft.PowerShell.Management\Test-Path -Path $DestinationLocation) - { + if (-not $NuGetApiKey.Trim()) { + if (Microsoft.PowerShell.Management\Test-Path -Path $DestinationLocation) { $NuGetApiKey = "$(Get-Random)" } - else - { + else { $message = $LocalizedData.NuGetApiKeyIsRequiredForNuGetBasedGalleryService -f ($Repository, $DestinationLocation) ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $message ` - -ErrorId "NuGetApiKeyIsRequiredForNuGetBasedGalleryService" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidArgument + -ExceptionMessage $message ` + -ErrorId "NuGetApiKeyIsRequiredForNuGetBasedGalleryService" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidArgument } } $providerName = Get-ProviderName -PSCustomObject $moduleSource - if($providerName -ne $script:NuGetProviderName) - { + if ($providerName -ne $script:NuGetProviderName) { $message = $LocalizedData.PublishModuleSupportsOnlyNuGetBasedPublishLocations -f ($moduleSource.PublishLocation, $Repository, $Repository) ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $message ` - -ErrorId "PublishModuleSupportsOnlyNuGetBasedPublishLocations" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidArgument ` - -ExceptionObject $Repository + -ExceptionMessage $message ` + -ErrorId "PublishModuleSupportsOnlyNuGetBasedPublishLocations" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidArgument ` + -ExceptionObject $Repository } $moduleName = $null - if($Name) - { - if ($RequiredVersion) - { + if ($Name) { + if ($RequiredVersion) { $ValidationResult = Validate-VersionParameters -CallerPSCmdlet $PSCmdlet ` - -Name $Name ` - -RequiredVersion $RequiredVersion ` - -AllowPrerelease:$AllowPrerelease - if(-not $ValidationResult) - { + -Name $Name ` + -RequiredVersion $RequiredVersion ` + -AllowPrerelease:$AllowPrerelease + if (-not $ValidationResult) { # Validate-VersionParameters throws the error. # returning to avoid further execution when different values are specified for -ErrorAction parameter return } $reqResult = ValidateAndGet-VersionPrereleaseStrings -Version $RequiredVersion -CallerPSCmdlet $PSCmdlet - if (-not $reqResult) - { + if (-not $reqResult) { # ValidateAndGet-VersionPrereleaseStrings throws the error. # returning to avoid further execution when different values are specified for -ErrorAction parameter return @@ -219,73 +199,65 @@ function Publish-Module $reqVersion = $reqResult["Version"] $reqPrerelease = $reqResult["Prerelease"] } - else - { + else { $reqVersion = $null $reqPrerelease = $null } # Find the module to be published locally, search by name and RequiredVersion $module = Microsoft.PowerShell.Core\Get-Module -ListAvailable -Name $Name -Verbose:$false | - Microsoft.PowerShell.Core\Where-Object { - $modInfoPrerelease = $null - if ($_.PrivateData -and - $_.PrivateData.GetType().ToString() -eq "System.Collections.Hashtable" -and - $_.PrivateData["PSData"] -and - $_.PrivateData.PSData.GetType().ToString() -eq "System.Collections.Hashtable" -and - $_.PrivateData.PSData["Prerelease"]) - { - $modInfoPrerelease = $_.PrivateData.PSData.Prerelease - } - (-not $RequiredVersion) -or ( ($reqVersion -eq $_.Version) -and ($reqPrerelease -match $modInfoPrerelease) ) - } - - if(-not $module) - { - if($RequiredVersion) - { + Microsoft.PowerShell.Core\Where-Object { + $modInfoPrerelease = $null + if ($_.PrivateData -and + $_.PrivateData.GetType().ToString() -eq "System.Collections.Hashtable" -and + $_.PrivateData["PSData"] -and + $_.PrivateData.PSData.GetType().ToString() -eq "System.Collections.Hashtable" -and + $_.PrivateData.PSData["Prerelease"]) { + $modInfoPrerelease = $_.PrivateData.PSData.Prerelease + } + (-not $RequiredVersion) -or ( ($reqVersion -eq $_.Version) -and ($reqPrerelease -match $modInfoPrerelease) ) + } + + if (-not $module) { + if ($RequiredVersion) { $message = $LocalizedData.ModuleWithRequiredVersionNotAvailableLocally -f ($Name, $RequiredVersion) } - else - { + else { $message = $LocalizedData.ModuleNotAvailableLocally -f ($Name) } ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $message ` - -ErrorId "ModuleNotAvailableLocallyToPublish" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidArgument ` - -ExceptionObject $Name + -ExceptionMessage $message ` + -ErrorId "ModuleNotAvailableLocallyToPublish" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidArgument ` + -ExceptionObject $Name } - elseif($module.GetType().ToString() -ne "System.Management.Automation.PSModuleInfo") - { + elseif ($module.GetType().ToString() -ne "System.Management.Automation.PSModuleInfo") { $message = $LocalizedData.AmbiguousModuleName -f ($Name) ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $message ` - -ErrorId "AmbiguousModuleNameToPublish" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidArgument ` - -ExceptionObject $Name + -ExceptionMessage $message ` + -ErrorId "AmbiguousModuleNameToPublish" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidArgument ` + -ExceptionObject $Name } $moduleName = $module.Name $Path = $module.ModuleBase } - else - { + else { $resolvedPath = Resolve-PathHelper -Path $Path -CallerPSCmdlet $PSCmdlet | Microsoft.PowerShell.Utility\Select-Object -First 1 -ErrorAction Ignore - if(-not $resolvedPath -or - -not (Microsoft.PowerShell.Management\Test-Path -Path $resolvedPath -PathType Container)) - { + if (-not $resolvedPath -or + -not (Microsoft.PowerShell.Management\Test-Path -Path $resolvedPath -PathType Container)) { ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage ($LocalizedData.PathIsNotADirectory -f ($Path)) ` - -ErrorId "PathIsNotADirectory" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidArgument ` - -ExceptionObject $Path + -ExceptionMessage ($LocalizedData.PathIsNotADirectory -f ($Path)) ` + -ErrorId "PathIsNotADirectory" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidArgument ` + -ExceptionObject $Path return } @@ -294,8 +266,7 @@ function Publish-Module # if the Leaf of the $resolvedPath is a version, use its parent folder name as the module name [Version]$ModuleVersion = $null - if([System.Version]::TryParse($moduleName, ([ref]$ModuleVersion))) - { + if ([System.Version]::TryParse($moduleName, ([ref]$ModuleVersion))) { $moduleName = Microsoft.PowerShell.Management\Split-Path -Path (Microsoft.PowerShell.Management\Split-Path $resolvedPath -Parent) -Leaf $modulePathWithVersion = $true } @@ -303,54 +274,48 @@ function Publish-Module $manifestPath = Join-PathUtility -Path $resolvedPath -ChildPath "$moduleName.psd1" -PathType File $module = $null - if(Microsoft.PowerShell.Management\Test-Path -Path $manifestPath -PathType Leaf) - { + if (Microsoft.PowerShell.Management\Test-Path -Path $manifestPath -PathType Leaf) { $ev = $null $module = Microsoft.PowerShell.Core\Test-ModuleManifest -Path $manifestPath ` - -ErrorVariable ev ` - -Verbose:$VerbosePreference - if($ev) - { + -ErrorVariable ev ` + -Verbose:$VerbosePreference + if ($ev) { # Above Test-ModuleManifest cmdlet should write an errors to the Errors stream and Console. return } } - elseif(-not $modulePathWithVersion -and ($PSVersionTable.PSVersion -ge '5.0.0')) - { + elseif (-not $modulePathWithVersion -and ($PSVersionTable.PSVersion -ge '5.0.0')) { $module = Microsoft.PowerShell.Core\Get-Module -Name $resolvedPath -ListAvailable -ErrorAction SilentlyContinue -Verbose:$false } - if(-not $module) - { + if (-not $module) { $message = $LocalizedData.InvalidModulePathToPublish -f ($Path) ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $message ` - -ErrorId 'InvalidModulePathToPublish' ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidArgument ` - -ExceptionObject $Path + -ExceptionMessage $message ` + -ErrorId 'InvalidModulePathToPublish' ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidArgument ` + -ExceptionObject $Path } - elseif($module.GetType().ToString() -ne "System.Management.Automation.PSModuleInfo") - { + elseif ($module.GetType().ToString() -ne "System.Management.Automation.PSModuleInfo") { $message = $LocalizedData.AmbiguousModulePath -f ($Path) ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $message ` - -ErrorId 'AmbiguousModulePathToPublish' ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidArgument ` - -ExceptionObject $Path + -ExceptionMessage $message ` + -ErrorId 'AmbiguousModulePathToPublish' ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidArgument ` + -ExceptionObject $Path } - if($module -and (-not $module.Path.EndsWith('.psd1', [System.StringComparison]::OrdinalIgnoreCase))) - { + if ($module -and (-not $module.Path.EndsWith('.psd1', [System.StringComparison]::OrdinalIgnoreCase))) { $message = $LocalizedData.InvalidModuleToPublish -f ($module.Name) ThrowError -ExceptionName "System.InvalidOperationException" ` - -ExceptionMessage $message ` - -ErrorId "InvalidModuleToPublish" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidOperation ` - -ExceptionObject $module.Name + -ExceptionMessage $message ` + -ErrorId "InvalidModuleToPublish" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidOperation ` + -ExceptionObject $module.Name } $moduleName = $module.Name @@ -361,32 +326,27 @@ function Publish-Module Write-Verbose -Message $message #If users are providing tags using -Tags while running PS 5.0, will show warning messages - if($Tags) - { + if ($Tags) { $message = $LocalizedData.TagsShouldBeIncludedInManifestFile -f ($moduleName, $Path) Write-Warning $message } - if($ReleaseNotes) - { + if ($ReleaseNotes) { $message = $LocalizedData.ReleaseNotesShouldBeIncludedInManifestFile -f ($moduleName, $Path) Write-Warning $message } - if($LicenseUri) - { + if ($LicenseUri) { $message = $LocalizedData.LicenseUriShouldBeIncludedInManifestFile -f ($moduleName, $Path) Write-Warning $message } - if($IconUri) - { + if ($IconUri) { $message = $LocalizedData.IconUriShouldBeIncludedInManifestFile -f ($moduleName, $Path) Write-Warning $message } - if($ProjectUri) - { + if ($ProjectUri) { $message = $LocalizedData.ProjectUriShouldBeIncludedInManifestFile -f ($moduleName, $Path) Write-Warning $message } @@ -394,57 +354,51 @@ function Publish-Module # Copy the source module to temp location to publish $tempModulePath = Microsoft.PowerShell.Management\Join-Path -Path $script:TempPath ` - -ChildPath "$(Microsoft.PowerShell.Utility\Get-Random)\$moduleName" + -ChildPath "$(Microsoft.PowerShell.Utility\Get-Random)\$moduleName" - if ($FormatVersion -eq "1.0") - { + if ($FormatVersion -eq "1.0") { $tempModulePathForFormatVersion = Microsoft.PowerShell.Management\Join-Path $tempModulePath "Content\Deployment\$script:ModuleReferences\$moduleName" } - else - { + else { $tempModulePathForFormatVersion = $tempModulePath } $null = Microsoft.PowerShell.Management\New-Item -Path $tempModulePathForFormatVersion -ItemType Directory -Force -ErrorAction SilentlyContinue -WarningAction SilentlyContinue -Confirm:$false -WhatIf:$false Microsoft.PowerShell.Management\Copy-Item -Path "$Path\*" -Destination $tempModulePathForFormatVersion -Force -Recurse -Confirm:$false -WhatIf:$false - try - { + try { $manifestPath = Join-PathUtility -Path $tempModulePathForFormatVersion -ChildPath "$moduleName.psd1" -PathType File - if(-not (Microsoft.PowerShell.Management\Test-Path $manifestPath)) - { + if (-not (Microsoft.PowerShell.Management\Test-Path $manifestPath)) { $message = $LocalizedData.InvalidModuleToPublish -f ($moduleName) ThrowError -ExceptionName "System.InvalidOperationException" ` - -ExceptionMessage $message ` - -ErrorId "InvalidModuleToPublish" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidOperation ` - -ExceptionObject $moduleName + -ExceptionMessage $message ` + -ErrorId "InvalidModuleToPublish" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidOperation ` + -ExceptionObject $moduleName } $ev = $null $moduleInfo = Microsoft.PowerShell.Core\Test-ModuleManifest -Path $manifestPath ` - -ErrorVariable ev ` - -Verbose:$VerbosePreference - if($ev) - { + -ErrorVariable ev ` + -Verbose:$VerbosePreference + if ($ev) { # Above Test-ModuleManifest cmdlet should write an errors to the Errors stream and Console. return } - if(-not $moduleInfo -or - -not $moduleInfo.Author -or - -not $moduleInfo.Description) - { + if (-not $moduleInfo -or + -not $moduleInfo.Author -or + -not $moduleInfo.Description) { $message = $LocalizedData.MissingRequiredManifestKeys -f ($moduleName) ThrowError -ExceptionName "System.InvalidOperationException" ` - -ExceptionMessage $message ` - -ErrorId "MissingRequiredModuleManifestKeys" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidOperation ` - -ExceptionObject $moduleName + -ExceptionMessage $message ` + -ErrorId "MissingRequiredModuleManifestKeys" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidOperation ` + -ExceptionObject $moduleName } # Validate Prerelease string @@ -453,14 +407,12 @@ function Publish-Module $moduleInfo.PrivateData.GetType().ToString() -eq "System.Collections.Hashtable" -and $moduleInfo.PrivateData["PSData"] -and $moduleInfo.PrivateData.PSData.GetType().ToString() -eq "System.Collections.Hashtable" -and - $moduleInfo.PrivateData.PSData["Prerelease"]) - { + $moduleInfo.PrivateData.PSData["Prerelease"]) { $moduleInfoPrerelease = $moduleInfo.PrivateData.PSData.Prerelease } $result = ValidateAndGet-VersionPrereleaseStrings -Version $moduleInfo.Version -Prerelease $moduleInfoPrerelease -CallerPSCmdlet $PSCmdlet - if (-not $result) - { + if (-not $result) { # ValidateAndGet-VersionPrereleaseStrings throws the error. # returning to avoid further execution when different values are specified for -ErrorAction parameter return @@ -470,47 +422,43 @@ function Publish-Module $moduleInfoFullVersion = $result["FullVersion"] $FindParameters = @{ - Name = $moduleName - Repository = $Repository - Tag = 'PSScript' + Name = $moduleName + Repository = $Repository + Tag = 'PSScript' AllowPrerelease = $true - Verbose = $VerbosePreference - ErrorAction = 'SilentlyContinue' - WarningAction = 'SilentlyContinue' - Debug = $DebugPreference + Verbose = $VerbosePreference + ErrorAction = 'SilentlyContinue' + WarningAction = 'SilentlyContinue' + Debug = $DebugPreference } - if($Credential) - { + if ($Credential) { $FindParameters[$script:Credential] = $Credential } # Check if the specified module name is already used for a script on the specified repository # Use Find-Script to check if that name is already used as scriptname $scriptPSGetItemInfo = Find-Script @FindParameters | - Microsoft.PowerShell.Core\Where-Object {$_.Name -eq $moduleName} | - Microsoft.PowerShell.Utility\Select-Object -Last 1 -ErrorAction Ignore - if($scriptPSGetItemInfo) - { + Microsoft.PowerShell.Core\Where-Object {$_.Name -eq $moduleName} | + Microsoft.PowerShell.Utility\Select-Object -Last 1 -ErrorAction Ignore + if ($scriptPSGetItemInfo) { $message = $LocalizedData.SpecifiedNameIsAlearyUsed -f ($moduleName, $Repository, 'Find-Script') ThrowError -ExceptionName "System.InvalidOperationException" ` - -ExceptionMessage $message ` - -ErrorId "SpecifiedNameIsAlearyUsed" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidOperation ` - -ExceptionObject $moduleName + -ExceptionMessage $message ` + -ErrorId "SpecifiedNameIsAlearyUsed" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidOperation ` + -ExceptionObject $moduleName } $null = $FindParameters.Remove('Tag') $currentPSGetItemInfo = Find-Module @FindParameters | - Microsoft.PowerShell.Core\Where-Object {$_.Name -eq $moduleInfo.Name} | - Microsoft.PowerShell.Utility\Select-Object -Last 1 -ErrorAction Ignore + Microsoft.PowerShell.Core\Where-Object {$_.Name -eq $moduleInfo.Name} | + Microsoft.PowerShell.Utility\Select-Object -Last 1 -ErrorAction Ignore - if($currentPSGetItemInfo) - { + if ($currentPSGetItemInfo) { $result = ValidateAndGet-VersionPrereleaseStrings -Version $currentPSGetItemInfo.Version -CallerPSCmdlet $PSCmdlet - if (-not $result) - { + if (-not $result) { # ValidateAndGet-VersionPrereleaseStrings throws the error. # returning to avoid further execution when different values are specified for -ErrorAction parameter return @@ -519,104 +467,94 @@ function Publish-Module $currentPSGetItemPrereleaseString = $result["Prerelease"] $currentPSGetItemFullVersion = $result["FullVersion"] - if($currentPSGetItemVersion -eq $moduleInfoVersion) - { + if ($currentPSGetItemVersion -eq $moduleInfoVersion) { # Compare Prerelease strings - if (-not $currentPSGetItemPrereleaseString -and -not $moduleInfoPrerelease) - { + if (-not $currentPSGetItemPrereleaseString -and -not $moduleInfoPrerelease) { $message = $LocalizedData.ModuleVersionIsAlreadyAvailableInTheGallery -f ($moduleInfo.Name, $moduleInfoFullVersion, $currentPSGetItemFullVersion, $currentPSGetItemInfo.RepositorySourceLocation) ThrowError -ExceptionName 'System.InvalidOperationException' ` - -ExceptionMessage $message ` - -ErrorId 'ModuleVersionIsAlreadyAvailableInTheGallery' ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidOperation + -ExceptionMessage $message ` + -ErrorId 'ModuleVersionIsAlreadyAvailableInTheGallery' ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidOperation } - elseif (-not $Force -and (-not $currentPSGetItemPrereleaseString -and $moduleInfoPrerelease)) - { + elseif (-not $Force -and (-not $currentPSGetItemPrereleaseString -and $moduleInfoPrerelease)) { # User is trying to publish a new Prerelease version AFTER publishing the stable version. $message = $LocalizedData.ModuleVersionShouldBeGreaterThanGalleryVersion -f ($moduleInfo.Name, $moduleInfoFullVersion, $currentPSGetItemFullVersion, $currentPSGetItemInfo.RepositorySourceLocation) ThrowError -ExceptionName "System.InvalidOperationException" ` - -ExceptionMessage $message ` - -ErrorId "ModuleVersionShouldBeGreaterThanGalleryVersion" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidOperation + -ExceptionMessage $message ` + -ErrorId "ModuleVersionShouldBeGreaterThanGalleryVersion" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidOperation } # elseif ($currentPSGetItemPrereleaseString -and -not $moduleInfoPrerelease) --> allow publish # User is attempting to publish a stable version after publishing a Prerelease version (allowed). - elseif ($currentPSGetItemPrereleaseString -and $moduleInfoPrerelease) - { - if ($currentPSGetItemPrereleaseString -eq $moduleInfoPrerelease) - { + elseif ($currentPSGetItemPrereleaseString -and $moduleInfoPrerelease) { + if ($currentPSGetItemPrereleaseString -eq $moduleInfoPrerelease) { $message = $LocalizedData.ModuleVersionIsAlreadyAvailableInTheGallery -f ($moduleInfo.Name, $moduleInfoFullVersion, $currentPSGetItemFullVersion, $currentPSGetItemInfo.RepositorySourceLocation) ThrowError -ExceptionName 'System.InvalidOperationException' ` - -ExceptionMessage $message ` - -ErrorId 'ModuleVersionIsAlreadyAvailableInTheGallery' ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidOperation + -ExceptionMessage $message ` + -ErrorId 'ModuleVersionIsAlreadyAvailableInTheGallery' ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidOperation } - elseif (-not $Force -and ($currentPSGetItemPrereleaseString -gt $moduleInfoPrerelease)) - { + elseif (-not $Force -and ($currentPSGetItemPrereleaseString -gt $moduleInfoPrerelease)) { $message = $LocalizedData.ModuleVersionShouldBeGreaterThanGalleryVersion -f ($moduleInfo.Name, $moduleInfoFullVersion, $currentPSGetItemFullVersion, $currentPSGetItemInfo.RepositorySourceLocation) ThrowError -ExceptionName "System.InvalidOperationException" ` - -ExceptionMessage $message ` - -ErrorId "ModuleVersionShouldBeGreaterThanGalleryVersion" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidOperation + -ExceptionMessage $message ` + -ErrorId "ModuleVersionShouldBeGreaterThanGalleryVersion" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidOperation } # elseif ($currentPSGetItemPrereleaseString -lt $moduleInfoPrerelease) --> allow publish } } - elseif(-not $Force -and (Compare-PrereleaseVersions -FirstItemVersion $moduleInfoVersion ` - -FirstItemPrerelease $moduleInfoPrerelease ` - -SecondItemVersion $currentPSGetItemVersion ` - -SecondItemPrerelease $currentPSGetItemPrereleaseString)) - { + elseif (-not $Force -and (Compare-PrereleaseVersions -FirstItemVersion $moduleInfoVersion ` + -FirstItemPrerelease $moduleInfoPrerelease ` + -SecondItemVersion $currentPSGetItemVersion ` + -SecondItemPrerelease $currentPSGetItemPrereleaseString)) { $message = $LocalizedData.ModuleVersionShouldBeGreaterThanGalleryVersion -f ($moduleInfo.Name, $moduleInfoVersion, $currentPSGetItemFullVersion, $currentPSGetItemInfo.RepositorySourceLocation) ThrowError -ExceptionName "System.InvalidOperationException" ` - -ExceptionMessage $message ` - -ErrorId "ModuleVersionShouldBeGreaterThanGalleryVersion" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidOperation + -ExceptionMessage $message ` + -ErrorId "ModuleVersionShouldBeGreaterThanGalleryVersion" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidOperation } # else ($currentPSGetItemVersion -lt $moduleInfoVersion) --> allow publish } $shouldProcessMessage = $LocalizedData.PublishModulewhatIfMessage -f ($moduleInfo.Version, $moduleInfo.Name) - if($Force -or $PSCmdlet.ShouldProcess($shouldProcessMessage, "Publish-Module")) - { + if ($Force -or $PSCmdlet.ShouldProcess($shouldProcessMessage, "Publish-Module")) { $PublishPSArtifactUtility_Params = @{ - PSModuleInfo=$moduleInfo - ManifestPath=$manifestPath - NugetApiKey=$NuGetApiKey - Destination=$DestinationLocation - Repository=$Repository - NugetPackageRoot=$tempModulePath - FormatVersion=$FormatVersion - ReleaseNotes=$($ReleaseNotes -join "`r`n") - Tags=$Tags - LicenseUri=$LicenseUri - IconUri=$IconUri - ProjectUri=$ProjectUri - Verbose=$VerbosePreference - WarningAction=$WarningPreference - ErrorAction=$ErrorActionPreference - Debug=$DebugPreference + PSModuleInfo = $moduleInfo + ManifestPath = $manifestPath + NugetApiKey = $NuGetApiKey + Destination = $DestinationLocation + Repository = $Repository + NugetPackageRoot = $tempModulePath + FormatVersion = $FormatVersion + ReleaseNotes = $($ReleaseNotes -join "`r`n") + Tags = $Tags + LicenseUri = $LicenseUri + IconUri = $IconUri + ProjectUri = $ProjectUri + Verbose = $VerbosePreference + WarningAction = $WarningPreference + ErrorAction = $ErrorActionPreference + Debug = $DebugPreference } - if ($PSBoundParameters.Containskey('Credential')) - { - $PublishPSArtifactUtility_Params.Add('Credential',$Credential) + if ($PSBoundParameters.Containskey('Credential')) { + $PublishPSArtifactUtility_Params.Add('Credential', $Credential) } Publish-PSArtifactUtility @PublishPSArtifactUtility_Params } } - finally - { + finally { Microsoft.PowerShell.Management\Remove-Item $tempModulePath -Force -Recurse -ErrorAction Ignore -WarningAction SilentlyContinue -Confirm:$false -WhatIf:$false } } -} \ No newline at end of file +} diff --git a/src/PowerShellGet/public/psgetfunctions/Publish-Script.ps1 b/src/PowerShellGet/public/psgetfunctions/Publish-Script.ps1 index 7216e2e3..3a2ac7ad 100644 --- a/src/PowerShellGet/public/psgetfunctions/Publish-Script.ps1 +++ b/src/PowerShellGet/public/psgetfunctions/Publish-Script.ps1 @@ -1,24 +1,23 @@ -function Publish-Script -{ +function Publish-Script { <# .ExternalHelp PSModule-help.xml #> - [CmdletBinding(SupportsShouldProcess=$true, - PositionalBinding=$false, - DefaultParameterSetName='PathParameterSet', - HelpUri='https://go.microsoft.com/fwlink/?LinkId=619788')] + [CmdletBinding(SupportsShouldProcess = $true, + PositionalBinding = $false, + DefaultParameterSetName = 'PathParameterSet', + HelpUri = 'https://go.microsoft.com/fwlink/?LinkId=619788')] Param ( - [Parameter(Mandatory=$true, - ValueFromPipelineByPropertyName=$true, - ParameterSetName='PathParameterSet')] + [Parameter(Mandatory = $true, + ValueFromPipelineByPropertyName = $true, + ParameterSetName = 'PathParameterSet')] [ValidateNotNullOrEmpty()] [string] $Path, - [Parameter(Mandatory=$true, - ValueFromPipelineByPropertyName=$true, - ParameterSetName='LiteralPathParameterSet')] + [Parameter(Mandatory = $true, + ValueFromPipelineByPropertyName = $true, + ParameterSetName = 'LiteralPathParameterSet')] [ValidateNotNullOrEmpty()] [string] $LiteralPath, @@ -33,7 +32,7 @@ function Publish-Script [string] $Repository = $Script:PSGalleryModuleSource, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [PSCredential] $Credential, @@ -42,150 +41,129 @@ function Publish-Script $Force ) - Begin - { - Get-PSGalleryApiAvailability -Repository $Repository - + Begin { Install-NuGetClientBinaries -CallerPSCmdlet $PSCmdlet -BootstrapNuGetExe -Force:$Force } - Process - { + Process { $scriptFilePath = $null - if($Path) - { + if ($Path) { $scriptFilePath = Resolve-PathHelper -Path $Path -CallerPSCmdlet $PSCmdlet | - Microsoft.PowerShell.Utility\Select-Object -First 1 -ErrorAction Ignore + Microsoft.PowerShell.Utility\Select-Object -First 1 -ErrorAction Ignore - if(-not $scriptFilePath -or - -not (Microsoft.PowerShell.Management\Test-Path -Path $scriptFilePath -PathType Leaf)) - { + if (-not $scriptFilePath -or + -not (Microsoft.PowerShell.Management\Test-Path -Path $scriptFilePath -PathType Leaf)) { $errorMessage = ($LocalizedData.PathNotFound -f $Path) ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $errorMessage ` - -ErrorId "PathNotFound" ` - -CallerPSCmdlet $PSCmdlet ` - -ExceptionObject $Path ` - -ErrorCategory InvalidArgument + -ExceptionMessage $errorMessage ` + -ErrorId "PathNotFound" ` + -CallerPSCmdlet $PSCmdlet ` + -ExceptionObject $Path ` + -ErrorCategory InvalidArgument } } - else - { + else { $scriptFilePath = Resolve-PathHelper -Path $LiteralPath -IsLiteralPath -CallerPSCmdlet $PSCmdlet | - Microsoft.PowerShell.Utility\Select-Object -First 1 -ErrorAction Ignore + Microsoft.PowerShell.Utility\Select-Object -First 1 -ErrorAction Ignore - if(-not $scriptFilePath -or - -not (Microsoft.PowerShell.Management\Test-Path -LiteralPath $scriptFilePath -PathType Leaf)) - { + if (-not $scriptFilePath -or + -not (Microsoft.PowerShell.Management\Test-Path -LiteralPath $scriptFilePath -PathType Leaf)) { $errorMessage = ($LocalizedData.PathNotFound -f $LiteralPath) ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $errorMessage ` - -ErrorId "PathNotFound" ` - -CallerPSCmdlet $PSCmdlet ` - -ExceptionObject $LiteralPath ` - -ErrorCategory InvalidArgument + -ExceptionMessage $errorMessage ` + -ErrorId "PathNotFound" ` + -CallerPSCmdlet $PSCmdlet ` + -ExceptionObject $LiteralPath ` + -ErrorCategory InvalidArgument } } - if(-not $scriptFilePath.EndsWith('.ps1', [System.StringComparison]::OrdinalIgnoreCase)) - { + if (-not $scriptFilePath.EndsWith('.ps1', [System.StringComparison]::OrdinalIgnoreCase)) { $errorMessage = ($LocalizedData.InvalidScriptFilePath -f $scriptFilePath) ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $errorMessage ` - -ErrorId "InvalidScriptFilePath" ` - -CallerPSCmdlet $PSCmdlet ` - -ExceptionObject $scriptFilePath ` - -ErrorCategory InvalidArgument + -ExceptionMessage $errorMessage ` + -ErrorId "InvalidScriptFilePath" ` + -CallerPSCmdlet $PSCmdlet ` + -ExceptionObject $scriptFilePath ` + -ErrorCategory InvalidArgument return } - if($Repository -eq $Script:PSGalleryModuleSource) - { + if ($Repository -eq $Script:PSGalleryModuleSource) { $repo = Get-PSRepository -Name $Repository -ErrorAction SilentlyContinue -WarningAction SilentlyContinue - if(-not $repo) - { + if (-not $repo) { $message = $LocalizedData.PSGalleryNotFound -f ($Repository) ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $message ` - -ErrorId 'PSGalleryNotFound' ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidArgument ` - -ExceptionObject $Repository + -ExceptionMessage $message ` + -ErrorId 'PSGalleryNotFound' ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidArgument ` + -ExceptionObject $Repository return } } - else - { + else { $ev = $null $repo = Get-PSRepository -Name $Repository -ErrorVariable ev # Checking for the $repo object as well as terminating errors are not captured into ev on downlevel PowerShell versions. - if($ev -or (-not $repo)) { return } + if ($ev -or (-not $repo)) { return } } $DestinationLocation = $null - if(Get-Member -InputObject $repo -Name $script:ScriptPublishLocation) - { + if (Get-Member -InputObject $repo -Name $script:ScriptPublishLocation) { $DestinationLocation = $repo.ScriptPublishLocation } - if(-not $DestinationLocation -or - (-not (Microsoft.PowerShell.Management\Test-Path -Path $DestinationLocation) -and - -not (Test-WebUri -uri $DestinationLocation))) - + if (-not $DestinationLocation -or + (-not (Microsoft.PowerShell.Management\Test-Path -Path $DestinationLocation) -and + -not (Test-WebUri -uri $DestinationLocation))) { $message = $LocalizedData.PSRepositoryScriptPublishLocationIsMissing -f ($Repository, $Repository) ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $message ` - -ErrorId "PSRepositoryScriptPublishLocationIsMissing" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidArgument ` - -ExceptionObject $Repository + -ExceptionMessage $message ` + -ErrorId "PSRepositoryScriptPublishLocationIsMissing" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidArgument ` + -ExceptionObject $Repository } $message = $LocalizedData.PublishLocation -f ($DestinationLocation) Write-Verbose -Message $message - if(-not $NuGetApiKey.Trim()) - { - if(Microsoft.PowerShell.Management\Test-Path -Path $DestinationLocation) - { + if (-not $NuGetApiKey.Trim()) { + if (Microsoft.PowerShell.Management\Test-Path -Path $DestinationLocation) { $NuGetApiKey = "$(Get-Random)" } - else - { + else { $message = $LocalizedData.NuGetApiKeyIsRequiredForNuGetBasedGalleryService -f ($Repository, $DestinationLocation) ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $message ` - -ErrorId "NuGetApiKeyIsRequiredForNuGetBasedGalleryService" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidArgument + -ExceptionMessage $message ` + -ErrorId "NuGetApiKeyIsRequiredForNuGetBasedGalleryService" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidArgument } } $providerName = Get-ProviderName -PSCustomObject $repo - if($providerName -ne $script:NuGetProviderName) - { + if ($providerName -ne $script:NuGetProviderName) { $message = $LocalizedData.PublishScriptSupportsOnlyNuGetBasedPublishLocations -f ($DestinationLocation, $Repository, $Repository) ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $message ` - -ErrorId "PublishScriptSupportsOnlyNuGetBasedPublishLocations" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidArgument ` - -ExceptionObject $Repository + -ExceptionMessage $message ` + -ErrorId "PublishScriptSupportsOnlyNuGetBasedPublishLocations" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidArgument ` + -ExceptionObject $Repository } - if($Path) - { + if ($Path) { $PSScriptInfo = Test-ScriptFileInfo -Path $scriptFilePath } - else - { + else { $PSScriptInfo = Test-ScriptFileInfo -LiteralPath $scriptFilePath } - if(-not $PSScriptInfo) - { + if (-not $PSScriptInfo) { # Test-ScriptFileInfo throws the actual error return } @@ -193,8 +171,7 @@ function Publish-Script $scriptName = $PSScriptInfo.Name $result = ValidateAndGet-VersionPrereleaseStrings -Version $PSScriptInfo.Version -CallerPSCmdlet $PSCmdlet - if (-not $result) - { + if (-not $result) { # ValidateAndGet-VersionPrereleaseStrings throws the error. # returning to avoid further execution when different values are specified for -ErrorAction parameter return @@ -208,61 +185,54 @@ function Publish-Script Microsoft.PowerShell.Management\Join-Path -ChildPath $scriptName $null = Microsoft.PowerShell.Management\New-Item -Path $tempScriptPath -ItemType Directory -Force -ErrorAction SilentlyContinue -WarningAction SilentlyContinue -Confirm:$false -WhatIf:$false - if($Path) - { + if ($Path) { Microsoft.PowerShell.Management\Copy-Item -Path $scriptFilePath -Destination $tempScriptPath -Force -Recurse -Confirm:$false -WhatIf:$false } - else - { + else { Microsoft.PowerShell.Management\Copy-Item -LiteralPath $scriptFilePath -Destination $tempScriptPath -Force -Recurse -Confirm:$false -WhatIf:$false } - try - { + try { $FindParameters = @{ - Name = $scriptName - Repository = $Repository - Tag = 'PSModule' + Name = $scriptName + Repository = $Repository + Tag = 'PSModule' AllowPrerelease = $true - Verbose = $VerbosePreference - ErrorAction = 'SilentlyContinue' - WarningAction = 'SilentlyContinue' - Debug = $DebugPreference + Verbose = $VerbosePreference + ErrorAction = 'SilentlyContinue' + WarningAction = 'SilentlyContinue' + Debug = $DebugPreference } - if($Credential) - { + if ($Credential) { $FindParameters[$script:Credential] = $Credential } # Check if the specified script name is already used for a module on the specified repository # Use Find-Module to check if that name is already used as module name $modulePSGetItemInfo = Find-Module @FindParameters | - Microsoft.PowerShell.Core\Where-Object {$_.Name -eq $scriptName} | - Microsoft.PowerShell.Utility\Select-Object -Last 1 -ErrorAction Ignore - if($modulePSGetItemInfo) - { + Microsoft.PowerShell.Core\Where-Object {$_.Name -eq $scriptName} | + Microsoft.PowerShell.Utility\Select-Object -Last 1 -ErrorAction Ignore + if ($modulePSGetItemInfo) { $message = $LocalizedData.SpecifiedNameIsAlearyUsed -f ($scriptName, $Repository, 'Find-Module') ThrowError -ExceptionName "System.InvalidOperationException" ` - -ExceptionMessage $message ` - -ErrorId "SpecifiedNameIsAlearyUsed" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidOperation ` - -ExceptionObject $scriptName + -ExceptionMessage $message ` + -ErrorId "SpecifiedNameIsAlearyUsed" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidOperation ` + -ExceptionObject $scriptName } $null = $FindParameters.Remove('Tag') $currentPSGetItemInfo = $null $currentPSGetItemInfo = Find-Script @FindParameters | - Microsoft.PowerShell.Core\Where-Object {$_.Name -eq $scriptName} | - Microsoft.PowerShell.Utility\Select-Object -Last 1 -ErrorAction Ignore + Microsoft.PowerShell.Core\Where-Object {$_.Name -eq $scriptName} | + Microsoft.PowerShell.Utility\Select-Object -Last 1 -ErrorAction Ignore - if($currentPSGetItemInfo) - { + if ($currentPSGetItemInfo) { $result = ValidateAndGet-VersionPrereleaseStrings -Version $currentPSGetItemInfo.Version -CallerPSCmdlet $PSCmdlet - if (-not $result) - { + if (-not $result) { # ValidateAndGet-VersionPrereleaseStrings throws the error. # returning to avoid further execution when different values are specified for -ErrorAction parameter return @@ -271,58 +241,53 @@ function Publish-Script $galleryScriptPrerelease = $result["Prerelease"] $galleryScriptFullVersion = $result["FullVersion"] - if($galleryScriptFullVersion -eq $scriptFullVersion) - { + if ($galleryScriptFullVersion -eq $scriptFullVersion) { $message = $LocalizedData.ScriptVersionIsAlreadyAvailableInTheGallery -f ($scriptName, - $scriptFullVersion, - $galleryScriptFullVersion, - $currentPSGetItemInfo.RepositorySourceLocation) + $scriptFullVersion, + $galleryScriptFullVersion, + $currentPSGetItemInfo.RepositorySourceLocation) ThrowError -ExceptionName "System.InvalidOperationException" ` - -ExceptionMessage $message ` - -ErrorId 'ScriptVersionIsAlreadyAvailableInTheGallery' ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidOperation + -ExceptionMessage $message ` + -ErrorId 'ScriptVersionIsAlreadyAvailableInTheGallery' ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidOperation } - if ($galleryScriptVersion -eq $scriptVersion -and -not $Force) - { + if ($galleryScriptVersion -eq $scriptVersion -and -not $Force) { # Prerelease strings will not both be null, otherwise would have terminated already above - if (-not $Force -and (-not $galleryScriptPrerelease -and $scriptPrerelease)) - { + if (-not $Force -and (-not $galleryScriptPrerelease -and $scriptPrerelease)) { # User is trying to publish a new Prerelease version AFTER publishing the stable version. $message = $LocalizedData.ScriptPrereleaseStringShouldBeGreaterThanGalleryPrereleaseString -f ($scriptName, - $scriptVersion, - $scriptPrerelease, - $galleryScriptPrerelease, - $currentPSGetItemInfo.RepositorySourceLocation) + $scriptVersion, + $scriptPrerelease, + $galleryScriptPrerelease, + $currentPSGetItemInfo.RepositorySourceLocation) ThrowError -ExceptionName "System.InvalidOperationException" ` - -ExceptionMessage $message ` - -ErrorId "ScriptPrereleaseStringShouldBeGreaterThanGalleryPrereleaseString" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidOperation + -ExceptionMessage $message ` + -ErrorId "ScriptPrereleaseStringShouldBeGreaterThanGalleryPrereleaseString" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidOperation } # elseif ($galleryScriptPrerelease -and -not $scriptPrerelease) --> allow publish # User is attempting to publish a stable version after publishing a prerelease version (allowed). - elseif($galleryScriptPrerelease -and $scriptPrerelease) - { + elseif ($galleryScriptPrerelease -and $scriptPrerelease) { # if ($galleryScriptPrerelease -eq $scriptPrerelease) --> not reachable, would have terminated already above. - if (-not $Force -and ($galleryScriptPrerelease -gt $scriptPrerelease)) - { + if (-not $Force -and ($galleryScriptPrerelease -gt $scriptPrerelease)) { # User is trying to publish a lower prerelease version. $message = $LocalizedData.ScriptPrereleaseStringShouldBeGreaterThanGalleryPrereleaseString -f ($scriptName, - $scriptVersion, - $scriptPrerelease, - $galleryScriptPrerelease, - $currentPSGetItemInfo.RepositorySourceLocation) + $scriptVersion, + $scriptPrerelease, + $galleryScriptPrerelease, + $currentPSGetItemInfo.RepositorySourceLocation) ThrowError -ExceptionName "System.InvalidOperationException" ` - -ExceptionMessage $message ` - -ErrorId "ScriptPrereleaseStringShouldBeGreaterThanGalleryPrereleaseString" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidOperation + -ExceptionMessage $message ` + -ErrorId "ScriptPrereleaseStringShouldBeGreaterThanGalleryPrereleaseString" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidOperation } # elseif ($galleryScriptPrerelease -lt $scriptPrerelease) --> allow publish @@ -330,19 +295,18 @@ function Publish-Script } } elseif (-not $Force -and (Compare-PrereleaseVersions -FirstItemVersion $scriptVersion ` - -FirstItemPrerelease $scriptPrerelease ` - -SecondItemVersion $galleryScriptVersion ` - -SecondItemPrerelease $galleryScriptPrerelease)) - { + -FirstItemPrerelease $scriptPrerelease ` + -SecondItemVersion $galleryScriptVersion ` + -SecondItemPrerelease $galleryScriptPrerelease)) { $message = $LocalizedData.ScriptVersionShouldBeGreaterThanGalleryVersion -f ($scriptName, - $scriptVersion, - $galleryScriptVersion, - $currentPSGetItemInfo.RepositorySourceLocation) + $scriptVersion, + $galleryScriptVersion, + $currentPSGetItemInfo.RepositorySourceLocation) ThrowError -ExceptionName "System.InvalidOperationException" ` - -ExceptionMessage $message ` - -ErrorId "ScriptVersionShouldBeGreaterThanGalleryVersion" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidOperation + -ExceptionMessage $message ` + -ErrorId "ScriptVersionShouldBeGreaterThanGalleryVersion" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidOperation } # else ($galleryScriptVersion -lt $scriptVersion) --> allow publish @@ -350,29 +314,26 @@ function Publish-Script } $shouldProcessMessage = $LocalizedData.PublishScriptwhatIfMessage -f ($PSScriptInfo.Version, $scriptName) - if($Force -or $PSCmdlet.ShouldProcess($shouldProcessMessage, "Publish-Script")) - { + if ($Force -or $PSCmdlet.ShouldProcess($shouldProcessMessage, "Publish-Script")) { $PublishPSArtifactUtility_Params = @{ - PSScriptInfo=$PSScriptInfo - NugetApiKey=$NuGetApiKey - Destination=$DestinationLocation - Repository=$Repository - NugetPackageRoot=$tempScriptPath - Verbose=$VerbosePreference - WarningAction=$WarningPreference - ErrorAction=$ErrorActionPreference - Debug=$DebugPreference + PSScriptInfo = $PSScriptInfo + NugetApiKey = $NuGetApiKey + Destination = $DestinationLocation + Repository = $Repository + NugetPackageRoot = $tempScriptPath + Verbose = $VerbosePreference + WarningAction = $WarningPreference + ErrorAction = $ErrorActionPreference + Debug = $DebugPreference } - if ($PSBoundParameters.ContainsKey('Credential')) - { - $PublishPSArtifactUtility_Params.Add('Credential',$Credential) + if ($PSBoundParameters.ContainsKey('Credential')) { + $PublishPSArtifactUtility_Params.Add('Credential', $Credential) } Publish-PSArtifactUtility @PublishPSArtifactUtility_Params } } - finally - { + finally { Microsoft.PowerShell.Management\Remove-Item $tempScriptPath -Force -Recurse -ErrorAction Ignore -WarningAction SilentlyContinue -Confirm:$false -WhatIf:$false } } -} \ No newline at end of file +} diff --git a/src/PowerShellGet/public/psgetfunctions/Register-PSRepository.ps1 b/src/PowerShellGet/public/psgetfunctions/Register-PSRepository.ps1 index 8437e054..8aeaecf0 100644 --- a/src/PowerShellGet/public/psgetfunctions/Register-PSRepository.ps1 +++ b/src/PowerShellGet/public/psgetfunctions/Register-PSRepository.ps1 @@ -1,84 +1,79 @@ -function Register-PSRepository -{ +function Register-PSRepository { <# .ExternalHelp PSModule-help.xml #> - [CmdletBinding(DefaultParameterSetName='NameParameterSet', - HelpUri='https://go.microsoft.com/fwlink/?LinkID=517129')] + [CmdletBinding(DefaultParameterSetName = 'NameParameterSet', + HelpUri = 'https://go.microsoft.com/fwlink/?LinkID=517129')] Param ( - [Parameter(Mandatory=$true, - Position=0, - ParameterSetName='NameParameterSet')] + [Parameter(Mandatory = $true, + Position = 0, + ParameterSetName = 'NameParameterSet')] [ValidateNotNullOrEmpty()] [string] $Name, - [Parameter(Mandatory=$true, - Position=1, - ParameterSetName='NameParameterSet')] + [Parameter(Mandatory = $true, + Position = 1, + ParameterSetName = 'NameParameterSet')] [ValidateNotNullOrEmpty()] [Uri] $SourceLocation, - [Parameter(ParameterSetName='NameParameterSet')] + [Parameter(ParameterSetName = 'NameParameterSet')] [ValidateNotNullOrEmpty()] [Uri] $PublishLocation, - [Parameter(ParameterSetName='NameParameterSet')] + [Parameter(ParameterSetName = 'NameParameterSet')] [ValidateNotNullOrEmpty()] [Uri] $ScriptSourceLocation, - [Parameter(ParameterSetName='NameParameterSet')] + [Parameter(ParameterSetName = 'NameParameterSet')] [ValidateNotNullOrEmpty()] [Uri] $ScriptPublishLocation, - [Parameter(ValueFromPipelineByPropertyName=$true, - ParameterSetName='NameParameterSet')] + [Parameter(ValueFromPipelineByPropertyName = $true, + ParameterSetName = 'NameParameterSet')] [PSCredential] $Credential, - [Parameter(Mandatory=$true, - ParameterSetName='PSGalleryParameterSet')] + [Parameter(Mandatory = $true, + ParameterSetName = 'PSGalleryParameterSet')] [Switch] $Default, [Parameter()] - [ValidateSet('Trusted','Untrusted')] + [ValidateSet('Trusted', 'Untrusted')] [string] $InstallationPolicy = 'Untrusted', - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [Uri] $Proxy, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [PSCredential] $ProxyCredential, - [Parameter(ParameterSetName='NameParameterSet')] + [Parameter(ParameterSetName = 'NameParameterSet')] [ValidateNotNullOrEmpty()] [string] $PackageManagementProvider ) - DynamicParam - { - if (Get-Variable -Name SourceLocation -ErrorAction SilentlyContinue) - { + DynamicParam { + if (Get-Variable -Name SourceLocation -ErrorAction SilentlyContinue) { Set-Variable -Name selectedProviderName -value $null -Scope 1 - if(Get-Variable -Name PackageManagementProvider -ErrorAction SilentlyContinue) - { + if (Get-Variable -Name PackageManagementProvider -ErrorAction SilentlyContinue) { $selectedProviderName = $PackageManagementProvider $null = Get-DynamicParameters -Location $SourceLocation -PackageManagementProvider ([REF]$selectedProviderName) } - else - { + else { $dynamicParameters = Get-DynamicParameters -Location $SourceLocation -PackageManagementProvider ([REF]$selectedProviderName) Set-Variable -Name PackageManagementProvider -Value $selectedProviderName -Scope 1 $null = $dynamicParameters @@ -86,108 +81,89 @@ function Register-PSRepository } } - Begin - { - Get-PSGalleryApiAvailability -Repository $Name - + Begin { Install-NuGetClientBinaries -CallerPSCmdlet $PSCmdlet -Proxy $Proxy -ProxyCredential $ProxyCredential - if($PackageManagementProvider) - { + if ($PackageManagementProvider) { $providers = PackageManagement\Get-PackageProvider | Where-Object { $_.Name -ne $script:PSModuleProviderName -and $_.Features.ContainsKey($script:SupportsPSModulesFeatureName) } - if (-not $providers -or $providers.Name -notcontains $PackageManagementProvider) - { + if (-not $providers -or $providers.Name -notcontains $PackageManagementProvider) { $possibleProviderNames = $script:NuGetProviderName - if($providers) - { + if ($providers) { $possibleProviderNames = ($providers.Name -join ',') } $message = $LocalizedData.InvalidPackageManagementProviderValue -f ($PackageManagementProvider, $possibleProviderNames, $script:NuGetProviderName) ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $message ` - -ErrorId "InvalidPackageManagementProviderValue" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidArgument ` - -ExceptionObject $PackageManagementProvider + -ExceptionMessage $message ` + -ErrorId "InvalidPackageManagementProviderValue" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidArgument ` + -ExceptionObject $PackageManagementProvider return } } } - Process - { - if($PSCmdlet.ParameterSetName -eq 'PSGalleryParameterSet') - { - if(-not $Default) - { + Process { + if ($PSCmdlet.ParameterSetName -eq 'PSGalleryParameterSet') { + if (-not $Default) { return } $PSBoundParameters['Name'] = $Script:PSGalleryModuleSource $null = $PSBoundParameters.Remove('Default') } - else - { - if($Name -eq $Script:PSGalleryModuleSource) - { + else { + if ($Name -eq $Script:PSGalleryModuleSource) { $message = $LocalizedData.UseDefaultParameterSetOnRegisterPSRepository ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $message ` - -ErrorId 'UseDefaultParameterSetOnRegisterPSRepository' ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidArgument ` - -ExceptionObject $Name + -ExceptionMessage $message ` + -ErrorId 'UseDefaultParameterSetOnRegisterPSRepository' ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidArgument ` + -ExceptionObject $Name return } # Ping and resolve the specified location $SourceLocation = Resolve-Location -Location (Get-LocationString -LocationUri $SourceLocation) ` - -LocationParameterName 'SourceLocation' ` - -Credential $Credential ` - -Proxy $Proxy ` - -ProxyCredential $ProxyCredential ` - -CallerPSCmdlet $PSCmdlet - if(-not $SourceLocation) - { + -LocationParameterName 'SourceLocation' ` + -Credential $Credential ` + -Proxy $Proxy ` + -ProxyCredential $ProxyCredential ` + -CallerPSCmdlet $PSCmdlet + if (-not $SourceLocation) { # Above Resolve-Location function throws an error when it is not able to resolve a location return } $providerName = $null - if($PackageManagementProvider) - { + if ($PackageManagementProvider) { $providerName = $PackageManagementProvider } - elseif($selectedProviderName) - { + elseif ($selectedProviderName) { $providerName = $selectedProviderName } - else - { + else { $providerName = Get-PackageManagementProviderName -Location $SourceLocation } - if($providerName) - { + if ($providerName) { $PSBoundParameters[$script:PackageManagementProviderParam] = $providerName } - if($PublishLocation) - { + if ($PublishLocation) { $PSBoundParameters[$script:PublishLocation] = Get-LocationString -LocationUri $PublishLocation } - if($ScriptPublishLocation) - { + if ($ScriptPublishLocation) { $PSBoundParameters[$script:ScriptPublishLocation] = Get-LocationString -LocationUri $ScriptPublishLocation } - if($ScriptSourceLocation) - { + if ($ScriptSourceLocation) { $PSBoundParameters[$script:ScriptSourceLocation] = Get-LocationString -LocationUri $ScriptSourceLocation } @@ -195,8 +171,7 @@ function Register-PSRepository $null = $PSBoundParameters.Remove("SourceLocation") } - if($InstallationPolicy -eq "Trusted") - { + if ($InstallationPolicy -eq "Trusted") { $PSBoundParameters['Trusted'] = $true } $null = $PSBoundParameters.Remove("InstallationPolicy") @@ -206,4 +181,4 @@ function Register-PSRepository $null = PackageManagement\Register-PackageSource @PSBoundParameters } -} \ No newline at end of file +} diff --git a/src/PowerShellGet/public/psgetfunctions/Save-Module.ps1 b/src/PowerShellGet/public/psgetfunctions/Save-Module.ps1 index db32a990..4055b1b5 100644 --- a/src/PowerShellGet/public/psgetfunctions/Save-Module.ps1 +++ b/src/PowerShellGet/public/psgetfunctions/Save-Module.ps1 @@ -1,91 +1,90 @@ -function Save-Module -{ +function Save-Module { <# .ExternalHelp PSModule-help.xml #> - [CmdletBinding(DefaultParameterSetName='NameAndPathParameterSet', - HelpUri='https://go.microsoft.com/fwlink/?LinkId=531351', - SupportsShouldProcess=$true)] + [CmdletBinding(DefaultParameterSetName = 'NameAndPathParameterSet', + HelpUri = 'https://go.microsoft.com/fwlink/?LinkId=531351', + SupportsShouldProcess = $true)] Param ( - [Parameter(Mandatory=$true, - ValueFromPipelineByPropertyName=$true, - Position=0, - ParameterSetName='NameAndPathParameterSet')] - [Parameter(Mandatory=$true, - ValueFromPipelineByPropertyName=$true, - Position=0, - ParameterSetName='NameAndLiteralPathParameterSet')] + [Parameter(Mandatory = $true, + ValueFromPipelineByPropertyName = $true, + Position = 0, + ParameterSetName = 'NameAndPathParameterSet')] + [Parameter(Mandatory = $true, + ValueFromPipelineByPropertyName = $true, + Position = 0, + ParameterSetName = 'NameAndLiteralPathParameterSet')] [ValidateNotNullOrEmpty()] [string[]] $Name, - [Parameter(Mandatory=$true, - ValueFromPipeline=$true, - ValueFromPipelineByPropertyName=$true, - Position=0, - ParameterSetName='InputObjectAndPathParameterSet')] - [Parameter(Mandatory=$true, - ValueFromPipeline=$true, - ValueFromPipelineByPropertyName=$true, - Position=0, - ParameterSetName='InputObjectAndLiteralPathParameterSet')] + [Parameter(Mandatory = $true, + ValueFromPipeline = $true, + ValueFromPipelineByPropertyName = $true, + Position = 0, + ParameterSetName = 'InputObjectAndPathParameterSet')] + [Parameter(Mandatory = $true, + ValueFromPipeline = $true, + ValueFromPipelineByPropertyName = $true, + Position = 0, + ParameterSetName = 'InputObjectAndLiteralPathParameterSet')] [ValidateNotNull()] [PSCustomObject[]] $InputObject, - [Parameter(ValueFromPipelineByPropertyName=$true, - ParameterSetName='NameAndPathParameterSet')] - [Parameter(ValueFromPipelineByPropertyName=$true, - ParameterSetName='NameAndLiteralPathParameterSet')] + [Parameter(ValueFromPipelineByPropertyName = $true, + ParameterSetName = 'NameAndPathParameterSet')] + [Parameter(ValueFromPipelineByPropertyName = $true, + ParameterSetName = 'NameAndLiteralPathParameterSet')] [ValidateNotNull()] [string] $MinimumVersion, - [Parameter(ValueFromPipelineByPropertyName=$true, - ParameterSetName='NameAndPathParameterSet')] - [Parameter(ValueFromPipelineByPropertyName=$true, - ParameterSetName='NameAndLiteralPathParameterSet')] + [Parameter(ValueFromPipelineByPropertyName = $true, + ParameterSetName = 'NameAndPathParameterSet')] + [Parameter(ValueFromPipelineByPropertyName = $true, + ParameterSetName = 'NameAndLiteralPathParameterSet')] [ValidateNotNull()] [string] $MaximumVersion, - [Parameter(ValueFromPipelineByPropertyName=$true, - ParameterSetName='NameAndPathParameterSet')] - [Parameter(ValueFromPipelineByPropertyName=$true, - ParameterSetName='NameAndLiteralPathParameterSet')] + [Parameter(ValueFromPipelineByPropertyName = $true, + ParameterSetName = 'NameAndPathParameterSet')] + [Parameter(ValueFromPipelineByPropertyName = $true, + ParameterSetName = 'NameAndLiteralPathParameterSet')] [ValidateNotNull()] [string] $RequiredVersion, - [Parameter(ValueFromPipelineByPropertyName=$true, - ParameterSetName='NameAndPathParameterSet')] - [Parameter(ValueFromPipelineByPropertyName=$true, - ParameterSetName='NameAndLiteralPathParameterSet')] + [Parameter(ValueFromPipelineByPropertyName = $true, + ParameterSetName = 'NameAndPathParameterSet')] + [Parameter(ValueFromPipelineByPropertyName = $true, + ParameterSetName = 'NameAndLiteralPathParameterSet')] [ValidateNotNullOrEmpty()] [string[]] $Repository, - [Parameter(Mandatory=$true, Position=1, ParameterSetName='NameAndPathParameterSet')] - [Parameter(Mandatory=$true, Position=1, ParameterSetName='InputObjectAndPathParameterSet')] + [Parameter(Mandatory = $true, Position = 1, ParameterSetName = 'NameAndPathParameterSet')] + [Parameter(Mandatory = $true, Position = 1, ParameterSetName = 'InputObjectAndPathParameterSet')] [string] $Path, - [Parameter(Mandatory=$true, ParameterSetName='NameAndLiteralPathParameterSet')] - [Parameter(Mandatory=$true, ParameterSetName='InputObjectAndLiteralPathParameterSet')] + [Parameter(Mandatory = $true, ParameterSetName = 'NameAndLiteralPathParameterSet')] + [Parameter(Mandatory = $true, ParameterSetName = 'InputObjectAndLiteralPathParameterSet')] [string] $LiteralPath, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [Uri] $Proxy, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [PSCredential] $ProxyCredential, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [PSCredential] $Credential, @@ -93,8 +92,8 @@ function Save-Module [switch] $Force, - [Parameter(ParameterSetName='NameAndPathParameterSet')] - [Parameter(ParameterSetName='NameAndLiteralPathParameterSet')] + [Parameter(ParameterSetName = 'NameAndPathParameterSet')] + [Parameter(ParameterSetName = 'NameAndLiteralPathParameterSet')] [switch] $AllowPrerelease, @@ -103,100 +102,86 @@ function Save-Module $AcceptLicense ) - Begin - { - Get-PSGalleryApiAvailability -Repository $Repository - + Begin { Install-NuGetClientBinaries -CallerPSCmdlet $PSCmdlet -Proxy $Proxy -ProxyCredential $ProxyCredential # Module names already tried in the current pipeline for InputObject parameterset $moduleNamesInPipeline = @() } - Process - { + Process { $PSBoundParameters["Provider"] = $script:PSModuleProviderName $PSBoundParameters["MessageResolver"] = $script:PackageManagementSaveModuleMessageResolverScriptBlock $PSBoundParameters[$script:PSArtifactType] = $script:PSArtifactTypeModule - if($AllowPrerelease) { + if ($AllowPrerelease) { $PSBoundParameters[$script:AllowPrereleaseVersions] = $true } $null = $PSBoundParameters.Remove("AllowPrerelease") # When -Force is specified, Path will be created if not available. - if(-not $Force) - { - if($Path) - { + if (-not $Force) { + if ($Path) { $destinationPath = Resolve-PathHelper -Path $Path -CallerPSCmdlet $PSCmdlet | Microsoft.PowerShell.Utility\Select-Object -First 1 -ErrorAction Ignore - if(-not $destinationPath -or -not (Microsoft.PowerShell.Management\Test-path $destinationPath)) - { + if (-not $destinationPath -or -not (Microsoft.PowerShell.Management\Test-path $destinationPath)) { $errorMessage = ($LocalizedData.PathNotFound -f $Path) ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $errorMessage ` - -ErrorId "PathNotFound" ` - -CallerPSCmdlet $PSCmdlet ` - -ExceptionObject $Path ` - -ErrorCategory InvalidArgument + -ExceptionMessage $errorMessage ` + -ErrorId "PathNotFound" ` + -CallerPSCmdlet $PSCmdlet ` + -ExceptionObject $Path ` + -ErrorCategory InvalidArgument } $PSBoundParameters['Path'] = $destinationPath } - else - { + else { $destinationPath = Resolve-PathHelper -Path $LiteralPath -IsLiteralPath -CallerPSCmdlet $PSCmdlet | Microsoft.PowerShell.Utility\Select-Object -First 1 -ErrorAction Ignore - if(-not $destinationPath -or -not (Microsoft.PowerShell.Management\Test-Path -LiteralPath $destinationPath)) - { + if (-not $destinationPath -or -not (Microsoft.PowerShell.Management\Test-Path -LiteralPath $destinationPath)) { $errorMessage = ($LocalizedData.PathNotFound -f $LiteralPath) ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $errorMessage ` - -ErrorId "PathNotFound" ` - -CallerPSCmdlet $PSCmdlet ` - -ExceptionObject $LiteralPath ` - -ErrorCategory InvalidArgument + -ExceptionMessage $errorMessage ` + -ErrorId "PathNotFound" ` + -CallerPSCmdlet $PSCmdlet ` + -ExceptionObject $LiteralPath ` + -ErrorCategory InvalidArgument } $PSBoundParameters['LiteralPath'] = $destinationPath } } - if($Name) - { + if ($Name) { $ValidationResult = Validate-VersionParameters -CallerPSCmdlet $PSCmdlet ` - -Name $Name ` - -TestWildcardsInName ` - -MinimumVersion $MinimumVersion ` - -MaximumVersion $MaximumVersion ` - -RequiredVersion $RequiredVersion ` - -AllowPrerelease:$AllowPrerelease - - if(-not $ValidationResult) - { + -Name $Name ` + -TestWildcardsInName ` + -MinimumVersion $MinimumVersion ` + -MaximumVersion $MaximumVersion ` + -RequiredVersion $RequiredVersion ` + -AllowPrerelease:$AllowPrerelease + + if (-not $ValidationResult) { # Validate-VersionParameters throws the error. # returning to avoid further execution when different values are specified for -ErrorAction parameter return } - if($PSBoundParameters.ContainsKey("Repository")) - { + if ($PSBoundParameters.ContainsKey("Repository")) { $PSBoundParameters["Source"] = $Repository $null = $PSBoundParameters.Remove("Repository") $ev = $null $null = Get-PSRepository -Name $Repository -ErrorVariable ev -verbose:$false - if($ev) { return } + if ($ev) { return } } $null = PackageManagement\Save-Package @PSBoundParameters } - elseif($InputObject) - { + elseif ($InputObject) { $null = $PSBoundParameters.Remove("InputObject") - foreach($inputValue in $InputObject) - { + foreach ($inputValue in $InputObject) { if (($inputValue.PSTypeNames -notcontains "Microsoft.PowerShell.Commands.PSRepositoryItemInfo") -and ($inputValue.PSTypeNames -notcontains "Deserialized.Microsoft.PowerShell.Commands.PSRepositoryItemInfo") -and ($inputValue.PSTypeNames -notcontains "Microsoft.PowerShell.Commands.PSGetCommandInfo") -and @@ -205,41 +190,36 @@ function Save-Module ($inputValue.PSTypeNames -notcontains "Deserialized.Microsoft.PowerShell.Commands.PSGetDscResourceInfo") -and ($inputValue.PSTypeNames -notcontains "Microsoft.PowerShell.Commands.PSGetRoleCapabilityInfo") -and ($inputValue.PSTypeNames -notcontains "Deserialized.Microsoft.PowerShell.Commands.PSGetRoleCapabilityInfo")) - { ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $LocalizedData.InvalidInputObjectValue ` - -ErrorId "InvalidInputObjectValue" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidArgument ` - -ExceptionObject $inputValue + -ExceptionMessage $LocalizedData.InvalidInputObjectValue ` + -ErrorId "InvalidInputObjectValue" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidArgument ` + -ExceptionObject $inputValue } - if( ($inputValue.PSTypeNames -contains "Microsoft.PowerShell.Commands.PSGetDscResourceInfo") -or + if ( ($inputValue.PSTypeNames -contains "Microsoft.PowerShell.Commands.PSGetDscResourceInfo") -or ($inputValue.PSTypeNames -contains "Deserialized.Microsoft.PowerShell.Commands.PSGetDscResourceInfo") -or ($inputValue.PSTypeNames -contains "Microsoft.PowerShell.Commands.PSGetCommandInfo") -or ($inputValue.PSTypeNames -contains "Deserialized.Microsoft.PowerShell.Commands.PSGetCommandInfo") -or ($inputValue.PSTypeNames -contains "Microsoft.PowerShell.Commands.PSGetRoleCapabilityInfo") -or - ($inputValue.PSTypeNames -contains "Deserialized.Microsoft.PowerShell.Commands.PSGetRoleCapabilityInfo")) - { + ($inputValue.PSTypeNames -contains "Deserialized.Microsoft.PowerShell.Commands.PSGetRoleCapabilityInfo")) { $psgetModuleInfo = $inputValue.PSGetModuleInfo } - else - { + else { $psgetModuleInfo = $inputValue } # Skip the module name if it is already tried in the current pipeline - if($moduleNamesInPipeline -contains $psgetModuleInfo.Name) - { + if ($moduleNamesInPipeline -contains $psgetModuleInfo.Name) { continue } $moduleNamesInPipeline += $psgetModuleInfo.Name if ($psgetModuleInfo.PowerShellGetFormatVersion -and - ($script:SupportedPSGetFormatVersionMajors -notcontains $psgetModuleInfo.PowerShellGetFormatVersion.Major)) - { + ($script:SupportedPSGetFormatVersionMajors -notcontains $psgetModuleInfo.PowerShellGetFormatVersion.Major)) { $message = $LocalizedData.NotSupportedPowerShellGetFormatVersion -f ($psgetModuleInfo.Name, $psgetModuleInfo.PowerShellGetFormatVersion, $psgetModuleInfo.Name) Write-Error -Message $message -ErrorId "NotSupportedPowerShellGetFormatVersion" -Category InvalidOperation continue @@ -262,4 +242,4 @@ function Save-Module } } } -} \ No newline at end of file +} diff --git a/src/PowerShellGet/public/psgetfunctions/Save-Script.ps1 b/src/PowerShellGet/public/psgetfunctions/Save-Script.ps1 index 5a7b44d2..fbf0fb9b 100644 --- a/src/PowerShellGet/public/psgetfunctions/Save-Script.ps1 +++ b/src/PowerShellGet/public/psgetfunctions/Save-Script.ps1 @@ -1,103 +1,102 @@ -function Save-Script -{ +function Save-Script { <# .ExternalHelp PSModule-help.xml #> - [CmdletBinding(DefaultParameterSetName='NameAndPathParameterSet', - HelpUri='https://go.microsoft.com/fwlink/?LinkId=619786', - SupportsShouldProcess=$true)] + [CmdletBinding(DefaultParameterSetName = 'NameAndPathParameterSet', + HelpUri = 'https://go.microsoft.com/fwlink/?LinkId=619786', + SupportsShouldProcess = $true)] Param ( - [Parameter(Mandatory=$true, - ValueFromPipelineByPropertyName=$true, - Position=0, - ParameterSetName='NameAndPathParameterSet')] - [Parameter(Mandatory=$true, - ValueFromPipelineByPropertyName=$true, - Position=0, - ParameterSetName='NameAndLiteralPathParameterSet')] + [Parameter(Mandatory = $true, + ValueFromPipelineByPropertyName = $true, + Position = 0, + ParameterSetName = 'NameAndPathParameterSet')] + [Parameter(Mandatory = $true, + ValueFromPipelineByPropertyName = $true, + Position = 0, + ParameterSetName = 'NameAndLiteralPathParameterSet')] [ValidateNotNullOrEmpty()] [string[]] $Name, - [Parameter(Mandatory=$true, - ValueFromPipeline=$true, - ValueFromPipelineByPropertyName=$true, - Position=0, - ParameterSetName='InputObjectAndPathParameterSet')] - [Parameter(Mandatory=$true, - ValueFromPipeline=$true, - ValueFromPipelineByPropertyName=$true, - Position=0, - ParameterSetName='InputObjectAndLiteralPathParameterSet')] + [Parameter(Mandatory = $true, + ValueFromPipeline = $true, + ValueFromPipelineByPropertyName = $true, + Position = 0, + ParameterSetName = 'InputObjectAndPathParameterSet')] + [Parameter(Mandatory = $true, + ValueFromPipeline = $true, + ValueFromPipelineByPropertyName = $true, + Position = 0, + ParameterSetName = 'InputObjectAndLiteralPathParameterSet')] [ValidateNotNull()] [PSCustomObject[]] $InputObject, - [Parameter(ValueFromPipelineByPropertyName=$true, - ParameterSetName='NameAndPathParameterSet')] - [Parameter(ValueFromPipelineByPropertyName=$true, - ParameterSetName='NameAndLiteralPathParameterSet')] + [Parameter(ValueFromPipelineByPropertyName = $true, + ParameterSetName = 'NameAndPathParameterSet')] + [Parameter(ValueFromPipelineByPropertyName = $true, + ParameterSetName = 'NameAndLiteralPathParameterSet')] [ValidateNotNull()] [string] $MinimumVersion, - [Parameter(ValueFromPipelineByPropertyName=$true, - ParameterSetName='NameAndPathParameterSet')] - [Parameter(ValueFromPipelineByPropertyName=$true, - ParameterSetName='NameAndLiteralPathParameterSet')] + [Parameter(ValueFromPipelineByPropertyName = $true, + ParameterSetName = 'NameAndPathParameterSet')] + [Parameter(ValueFromPipelineByPropertyName = $true, + ParameterSetName = 'NameAndLiteralPathParameterSet')] [ValidateNotNull()] [string] $MaximumVersion, - [Parameter(ValueFromPipelineByPropertyName=$true, - ParameterSetName='NameAndPathParameterSet')] - [Parameter(ValueFromPipelineByPropertyName=$true, - ParameterSetName='NameAndLiteralPathParameterSet')] + [Parameter(ValueFromPipelineByPropertyName = $true, + ParameterSetName = 'NameAndPathParameterSet')] + [Parameter(ValueFromPipelineByPropertyName = $true, + ParameterSetName = 'NameAndLiteralPathParameterSet')] [ValidateNotNull()] [string] $RequiredVersion, - [Parameter(ValueFromPipelineByPropertyName=$true, - ParameterSetName='NameAndPathParameterSet')] - [Parameter(ValueFromPipelineByPropertyName=$true, - ParameterSetName='NameAndLiteralPathParameterSet')] + [Parameter(ValueFromPipelineByPropertyName = $true, + ParameterSetName = 'NameAndPathParameterSet')] + [Parameter(ValueFromPipelineByPropertyName = $true, + ParameterSetName = 'NameAndLiteralPathParameterSet')] [ValidateNotNullOrEmpty()] [string[]] $Repository, - [Parameter(Mandatory=$true, - ValueFromPipelineByPropertyName=$true, - Position=1, - ParameterSetName='NameAndPathParameterSet')] + [Parameter(Mandatory = $true, + ValueFromPipelineByPropertyName = $true, + Position = 1, + ParameterSetName = 'NameAndPathParameterSet')] - [Parameter(Mandatory=$true, - ValueFromPipelineByPropertyName=$true, - Position=1, - ParameterSetName='InputObjectAndPathParameterSet')] + [Parameter(Mandatory = $true, + ValueFromPipelineByPropertyName = $true, + Position = 1, + ParameterSetName = 'InputObjectAndPathParameterSet')] [string] $Path, - [Parameter(Mandatory=$true, - ValueFromPipelineByPropertyName=$true, - ParameterSetName='NameAndLiteralPathParameterSet')] + [Parameter(Mandatory = $true, + ValueFromPipelineByPropertyName = $true, + ParameterSetName = 'NameAndLiteralPathParameterSet')] - [Parameter(Mandatory=$true, - ValueFromPipelineByPropertyName=$true, - ParameterSetName='InputObjectAndLiteralPathParameterSet')] + [Parameter(Mandatory = $true, + ValueFromPipelineByPropertyName = $true, + ParameterSetName = 'InputObjectAndLiteralPathParameterSet')] [string] $LiteralPath, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [Uri] $Proxy, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [PSCredential] $ProxyCredential, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [PSCredential] $Credential, @@ -105,8 +104,8 @@ function Save-Script [switch] $Force, - [Parameter(ParameterSetName='NameAndPathParameterSet')] - [Parameter(ParameterSetName='NameAndLiteralPathParameterSet')] + [Parameter(ParameterSetName = 'NameAndPathParameterSet')] + [Parameter(ParameterSetName = 'NameAndLiteralPathParameterSet')] [switch] $AllowPrerelease, @@ -115,147 +114,127 @@ function Save-Script $AcceptLicense ) - Begin - { - Get-PSGalleryApiAvailability -Repository $Repository - + Begin { Install-NuGetClientBinaries -CallerPSCmdlet $PSCmdlet -Proxy $Proxy -ProxyCredential $ProxyCredential # Script names already tried in the current pipeline for InputObject parameterset $scriptNamesInPipeline = @() } - Process - { + Process { $PSBoundParameters["Provider"] = $script:PSModuleProviderName $PSBoundParameters["MessageResolver"] = $script:PackageManagementSaveScriptMessageResolverScriptBlock $PSBoundParameters[$script:PSArtifactType] = $script:PSArtifactTypeScript - if($AllowPrerelease) { + if ($AllowPrerelease) { $PSBoundParameters[$script:AllowPrereleaseVersions] = $true } $null = $PSBoundParameters.Remove("AllowPrerelease") # When -Force is specified, Path will be created if not available. - if(-not $Force) - { - if($Path) - { + if (-not $Force) { + if ($Path) { $destinationPath = Resolve-PathHelper -Path $Path -CallerPSCmdlet $PSCmdlet | - Microsoft.PowerShell.Utility\Select-Object -First 1 -ErrorAction Ignore + Microsoft.PowerShell.Utility\Select-Object -First 1 -ErrorAction Ignore - if(-not $destinationPath -or -not (Microsoft.PowerShell.Management\Test-path $destinationPath)) - { + if (-not $destinationPath -or -not (Microsoft.PowerShell.Management\Test-path $destinationPath)) { $errorMessage = ($LocalizedData.PathNotFound -f $Path) ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $errorMessage ` - -ErrorId "PathNotFound" ` - -CallerPSCmdlet $PSCmdlet ` - -ExceptionObject $Path ` - -ErrorCategory InvalidArgument + -ExceptionMessage $errorMessage ` + -ErrorId "PathNotFound" ` + -CallerPSCmdlet $PSCmdlet ` + -ExceptionObject $Path ` + -ErrorCategory InvalidArgument } $PSBoundParameters['Path'] = $destinationPath } - else - { + else { $destinationPath = Resolve-PathHelper -Path $LiteralPath -IsLiteralPath -CallerPSCmdlet $PSCmdlet | - Microsoft.PowerShell.Utility\Select-Object -First 1 -ErrorAction Ignore + Microsoft.PowerShell.Utility\Select-Object -First 1 -ErrorAction Ignore - if(-not $destinationPath -or -not (Microsoft.PowerShell.Management\Test-Path -LiteralPath $destinationPath)) - { + if (-not $destinationPath -or -not (Microsoft.PowerShell.Management\Test-Path -LiteralPath $destinationPath)) { $errorMessage = ($LocalizedData.PathNotFound -f $LiteralPath) ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $errorMessage ` - -ErrorId "PathNotFound" ` - -CallerPSCmdlet $PSCmdlet ` - -ExceptionObject $LiteralPath ` - -ErrorCategory InvalidArgument + -ExceptionMessage $errorMessage ` + -ErrorId "PathNotFound" ` + -CallerPSCmdlet $PSCmdlet ` + -ExceptionObject $LiteralPath ` + -ErrorCategory InvalidArgument } $PSBoundParameters['LiteralPath'] = $destinationPath } } - if($Name) - { + if ($Name) { $ValidationResult = Validate-VersionParameters -CallerPSCmdlet $PSCmdlet ` - -Name $Name ` - -TestWildcardsInName ` - -MinimumVersion $MinimumVersion ` - -MaximumVersion $MaximumVersion ` - -RequiredVersion $RequiredVersion ` - -AllowPrerelease:$AllowPrerelease - - if(-not $ValidationResult) - { + -Name $Name ` + -TestWildcardsInName ` + -MinimumVersion $MinimumVersion ` + -MaximumVersion $MaximumVersion ` + -RequiredVersion $RequiredVersion ` + -AllowPrerelease:$AllowPrerelease + + if (-not $ValidationResult) { # Validate-VersionParameters throws the error. # returning to avoid further execution when different values are specified for -ErrorAction parameter return } - if($PSBoundParameters.ContainsKey("Repository")) - { + if ($PSBoundParameters.ContainsKey("Repository")) { $PSBoundParameters["Source"] = $Repository $null = $PSBoundParameters.Remove("Repository") $ev = $null $repositories = Get-PSRepository -Name $Repository -ErrorVariable ev -verbose:$false - if($ev) { return } + if ($ev) { return } $RepositoriesWithoutScriptSourceLocation = $false - foreach($repo in $repositories) - { - if(-not $repo.ScriptSourceLocation) - { + foreach ($repo in $repositories) { + if (-not $repo.ScriptSourceLocation) { $message = $LocalizedData.ScriptSourceLocationIsMissing -f ($repo.Name) Write-Error -Message $message ` - -ErrorId 'ScriptSourceLocationIsMissing' ` - -Category InvalidArgument ` - -TargetObject $repo.Name ` - -Exception 'System.ArgumentException' + -ErrorId 'ScriptSourceLocationIsMissing' ` + -Category InvalidArgument ` + -TargetObject $repo.Name ` + -Exception 'System.ArgumentException' $RepositoriesWithoutScriptSourceLocation = $true } } - if($RepositoriesWithoutScriptSourceLocation) - { + if ($RepositoriesWithoutScriptSourceLocation) { return } } $null = PackageManagement\Save-Package @PSBoundParameters } - elseif($InputObject) - { + elseif ($InputObject) { $null = $PSBoundParameters.Remove("InputObject") - foreach($inputValue in $InputObject) - { + foreach ($inputValue in $InputObject) { if (($inputValue.PSTypeNames -notcontains "Microsoft.PowerShell.Commands.PSRepositoryItemInfo") -and - ($inputValue.PSTypeNames -notcontains "Deserialized.Microsoft.PowerShell.Commands.PSRepositoryItemInfo")) - { + ($inputValue.PSTypeNames -notcontains "Deserialized.Microsoft.PowerShell.Commands.PSRepositoryItemInfo")) { ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $LocalizedData.InvalidInputObjectValue ` - -ErrorId "InvalidInputObjectValue" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidArgument ` - -ExceptionObject $inputValue + -ExceptionMessage $LocalizedData.InvalidInputObjectValue ` + -ErrorId "InvalidInputObjectValue" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidArgument ` + -ExceptionObject $inputValue } $psRepositoryItemInfo = $inputValue # Skip the script name if it is already tried in the current pipeline - if($scriptNamesInPipeline -contains $psRepositoryItemInfo.Name) - { + if ($scriptNamesInPipeline -contains $psRepositoryItemInfo.Name) { continue } $scriptNamesInPipeline += $psRepositoryItemInfo.Name if ($psRepositoryItemInfo.PowerShellGetFormatVersion -and - ($script:SupportedPSGetFormatVersionMajors -notcontains $psRepositoryItemInfo.PowerShellGetFormatVersion.Major)) - { + ($script:SupportedPSGetFormatVersionMajors -notcontains $psRepositoryItemInfo.PowerShellGetFormatVersion.Major)) { $message = $LocalizedData.NotSupportedPowerShellGetFormatVersionScripts -f ($psRepositoryItemInfo.Name, $psRepositoryItemInfo.PowerShellGetFormatVersion, $psRepositoryItemInfo.Name) Write-Error -Message $message -ErrorId "NotSupportedPowerShellGetFormatVersion" -Category InvalidOperation continue @@ -278,4 +257,4 @@ function Save-Script } } } -} \ No newline at end of file +} diff --git a/src/PowerShellGet/public/psgetfunctions/Set-PSRepository.ps1 b/src/PowerShellGet/public/psgetfunctions/Set-PSRepository.ps1 index 5a2af63e..5e647316 100644 --- a/src/PowerShellGet/public/psgetfunctions/Set-PSRepository.ps1 +++ b/src/PowerShellGet/public/psgetfunctions/Set-PSRepository.ps1 @@ -1,18 +1,17 @@ -function Set-PSRepository -{ +function Set-PSRepository { <# .ExternalHelp PSModule-help.xml #> - [CmdletBinding(PositionalBinding=$false, - HelpUri='https://go.microsoft.com/fwlink/?LinkID=517128')] + [CmdletBinding(PositionalBinding = $false, + HelpUri = 'https://go.microsoft.com/fwlink/?LinkID=517128')] Param ( - [Parameter(Mandatory=$true, Position=0)] + [Parameter(Mandatory = $true, Position = 0)] [ValidateNotNullOrEmpty()] [string] $Name, - [Parameter(Position=1)] + [Parameter(Position = 1)] [ValidateNotNullOrEmpty()] [Uri] $SourceLocation, @@ -32,21 +31,21 @@ function Set-PSRepository [Uri] $ScriptPublishLocation, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [PSCredential] $Credential, [Parameter()] - [ValidateSet('Trusted','Untrusted')] + [ValidateSet('Trusted', 'Untrusted')] [string] $InstallationPolicy, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [Uri] $Proxy, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [PSCredential] $ProxyCredential, @@ -56,25 +55,20 @@ function Set-PSRepository $PackageManagementProvider ) - DynamicParam - { - if (Get-Variable -Name Name -ErrorAction SilentlyContinue) - { + DynamicParam { + if (Get-Variable -Name Name -ErrorAction SilentlyContinue) { $moduleSource = Get-PSRepository -Name $Name -ErrorAction SilentlyContinue -WarningAction SilentlyContinue - if($moduleSource) - { + if ($moduleSource) { $providerName = (Get-ProviderName -PSCustomObject $moduleSource) $loc = $moduleSource.SourceLocation - if(Get-Variable -Name SourceLocation -ErrorAction SilentlyContinue) - { + if (Get-Variable -Name SourceLocation -ErrorAction SilentlyContinue) { $loc = $SourceLocation } - if(Get-Variable -Name PackageManagementProvider -ErrorAction SilentlyContinue) - { + if (Get-Variable -Name PackageManagementProvider -ErrorAction SilentlyContinue) { $providerName = $PackageManagementProvider } @@ -83,51 +77,42 @@ function Set-PSRepository } } - Begin - { - Get-PSGalleryApiAvailability -Repository $Name - + Begin { Install-NuGetClientBinaries -CallerPSCmdlet $PSCmdlet -Proxy $Proxy -ProxyCredential $ProxyCredential - if($PackageManagementProvider) - { + if ($PackageManagementProvider) { $providers = PackageManagement\Get-PackageProvider | Where-Object { $_.Name -ne $script:PSModuleProviderName -and $_.Features.ContainsKey($script:SupportsPSModulesFeatureName) } - if (-not $providers -or $providers.Name -notcontains $PackageManagementProvider) - { + if (-not $providers -or $providers.Name -notcontains $PackageManagementProvider) { $possibleProviderNames = $script:NuGetProviderName - if($providers) - { + if ($providers) { $possibleProviderNames = ($providers.Name -join ',') } $message = $LocalizedData.InvalidPackageManagementProviderValue -f ($PackageManagementProvider, $possibleProviderNames, $script:NuGetProviderName) ThrowError -ExceptionName "System.ArgumentException" ` - -ExceptionMessage $message ` - -ErrorId "InvalidPackageManagementProviderValue" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidArgument ` - -ExceptionObject $PackageManagementProvider + -ExceptionMessage $message ` + -ErrorId "InvalidPackageManagementProviderValue" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidArgument ` + -ExceptionObject $PackageManagementProvider return } } } - Process - { + Process { # Ping and resolve the specified location - if($SourceLocation) - { + if ($SourceLocation) { # Ping and resolve the specified location $SourceLocation = Resolve-Location -Location (Get-LocationString -LocationUri $SourceLocation) ` - -LocationParameterName 'SourceLocation' ` - -Credential $Credential ` - -Proxy $Proxy ` - -ProxyCredential $ProxyCredential ` - -CallerPSCmdlet $PSCmdlet - if(-not $SourceLocation) - { + -LocationParameterName 'SourceLocation' ` + -Credential $Credential ` + -Proxy $Proxy ` + -ProxyCredential $ProxyCredential ` + -CallerPSCmdlet $PSCmdlet + if (-not $SourceLocation) { # Above Resolve-Location function throws an error when it is not able to resolve a location return } @@ -135,55 +120,46 @@ function Set-PSRepository $ModuleSource = Get-PSRepository -Name $Name -ErrorAction SilentlyContinue -WarningAction SilentlyContinue - if(-not $ModuleSource) - { + if (-not $ModuleSource) { $message = $LocalizedData.RepositoryNotFound -f ($Name) ThrowError -ExceptionName "System.InvalidOperationException" ` - -ExceptionMessage $message ` - -ErrorId "RepositoryNotFound" ` - -CallerPSCmdlet $PSCmdlet ` - -ErrorCategory InvalidOperation ` - -ExceptionObject $Name + -ExceptionMessage $message ` + -ErrorId "RepositoryNotFound" ` + -CallerPSCmdlet $PSCmdlet ` + -ErrorCategory InvalidOperation ` + -ExceptionObject $Name } - if (-not $PackageManagementProvider) - { + if (-not $PackageManagementProvider) { $PackageManagementProvider = (Get-ProviderName -PSCustomObject $ModuleSource) } $Trusted = $ModuleSource.Trusted - if($InstallationPolicy) - { - if($InstallationPolicy -eq "Trusted") - { + if ($InstallationPolicy) { + if ($InstallationPolicy -eq "Trusted") { $Trusted = $true } - else - { + else { $Trusted = $false } $null = $PSBoundParameters.Remove("InstallationPolicy") } - if($PublishLocation) - { + if ($PublishLocation) { $PSBoundParameters[$script:PublishLocation] = Get-LocationString -LocationUri $PublishLocation } - if($ScriptPublishLocation) - { + if ($ScriptPublishLocation) { $PSBoundParameters[$script:ScriptPublishLocation] = Get-LocationString -LocationUri $ScriptPublishLocation } - if($ScriptSourceLocation) - { + if ($ScriptSourceLocation) { $PSBoundParameters[$script:ScriptSourceLocation] = Get-LocationString -LocationUri $ScriptSourceLocation } - if($SourceLocation) - { + if ($SourceLocation) { $PSBoundParameters["NewLocation"] = Get-LocationString -LocationUri $SourceLocation $null = $PSBoundParameters.Remove("SourceLocation") @@ -196,4 +172,4 @@ function Set-PSRepository $null = PackageManagement\Set-PackageSource @PSBoundParameters } -} \ No newline at end of file +} diff --git a/src/PowerShellGet/public/psgetfunctions/Unregister-PSRepository.ps1 b/src/PowerShellGet/public/psgetfunctions/Unregister-PSRepository.ps1 index 20c52348..d45069a8 100644 --- a/src/PowerShellGet/public/psgetfunctions/Unregister-PSRepository.ps1 +++ b/src/PowerShellGet/public/psgetfunctions/Unregister-PSRepository.ps1 @@ -1,35 +1,29 @@ -function Unregister-PSRepository -{ +function Unregister-PSRepository { <# .ExternalHelp PSModule-help.xml #> - [CmdletBinding(HelpUri='https://go.microsoft.com/fwlink/?LinkID=517130')] + [CmdletBinding(HelpUri = 'https://go.microsoft.com/fwlink/?LinkID=517130')] Param ( - [Parameter(ValueFromPipelineByPropertyName=$true, - Mandatory=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true, + Mandatory = $true)] [ValidateNotNullOrEmpty()] [string[]] $Name ) - Begin - { - Get-PSGalleryApiAvailability -Repository $Name + Begin { } - Process - { + Process { $PSBoundParameters["Provider"] = $script:PSModuleProviderName $PSBoundParameters["MessageResolver"] = $script:PackageManagementMessageResolverScriptBlock $null = $PSBoundParameters.Remove("Name") - foreach ($moduleSourceName in $Name) - { + foreach ($moduleSourceName in $Name) { # Check if $moduleSourceName contains any wildcards - if(Test-WildcardPattern $moduleSourceName) - { + if (Test-WildcardPattern $moduleSourceName) { $message = $LocalizedData.RepositoryNameContainsWildCards -f ($moduleSourceName) Write-Error -Message $message -ErrorId "RepositoryNameContainsWildCards" -Category InvalidOperation continue @@ -40,4 +34,4 @@ function Unregister-PSRepository $null = PackageManagement\Unregister-PackageSource @PSBoundParameters } } -} \ No newline at end of file +} diff --git a/src/PowerShellGet/public/psgetfunctions/Update-Module.ps1 b/src/PowerShellGet/public/psgetfunctions/Update-Module.ps1 index f43f8b14..68447084 100644 --- a/src/PowerShellGet/public/psgetfunctions/Update-Module.ps1 +++ b/src/PowerShellGet/public/psgetfunctions/Update-Module.ps1 @@ -1,38 +1,37 @@ -function Update-Module -{ +function Update-Module { <# .ExternalHelp PSModule-help.xml #> - [CmdletBinding(SupportsShouldProcess=$true, - HelpUri='https://go.microsoft.com/fwlink/?LinkID=398576')] + [CmdletBinding(SupportsShouldProcess = $true, + HelpUri = 'https://go.microsoft.com/fwlink/?LinkID=398576')] Param ( - [Parameter(ValueFromPipelineByPropertyName=$true, - Position=0)] + [Parameter(ValueFromPipelineByPropertyName = $true, + Position = 0)] [ValidateNotNullOrEmpty()] [String[]] $Name, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [ValidateNotNull()] [string] $RequiredVersion, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [ValidateNotNull()] [string] $MaximumVersion, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [PSCredential] $Credential, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [Uri] $Proxy, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [PSCredential] $ProxyCredential, @@ -49,24 +48,21 @@ function Update-Module $AcceptLicense ) - Begin - { + Begin { Install-NuGetClientBinaries -CallerPSCmdlet $PSCmdlet -Proxy $Proxy -ProxyCredential $ProxyCredential # Module names already tried in the current pipeline $moduleNamesInPipeline = @() } - Process - { + Process { $ValidationResult = Validate-VersionParameters -CallerPSCmdlet $PSCmdlet ` - -Name $Name ` - -MaximumVersion $MaximumVersion ` - -RequiredVersion $RequiredVersion ` - -AllowPrerelease:$AllowPrerelease + -Name $Name ` + -MaximumVersion $MaximumVersion ` + -RequiredVersion $RequiredVersion ` + -AllowPrerelease:$AllowPrerelease - if(-not $ValidationResult) - { + if (-not $ValidationResult) { # Validate-VersionParameters throws the error. # returning to avoid further execution when different values are specified for -ErrorAction parameter return @@ -78,31 +74,26 @@ function Update-Module $GetPackageParameters["MessageResolver"] = $script:PackageManagementMessageResolverScriptBlock $GetPackageParameters['ErrorAction'] = 'SilentlyContinue' $GetPackageParameters['WarningAction'] = 'SilentlyContinue' - if($AllowPrerelease) { + if ($AllowPrerelease) { $PSBoundParameters[$script:AllowPrereleaseVersions] = $true } $null = $PSBoundParameters.Remove("AllowPrerelease") $PSGetItemInfos = @() - if($Name) - { - foreach($moduleName in $Name) - { + if ($Name) { + foreach ($moduleName in $Name) { $GetPackageParameters['Name'] = $moduleName $installedPackages = PackageManagement\Get-Package @GetPackageParameters - if(-not $installedPackages -and -not (Test-WildcardPattern -Name $moduleName)) - { + if (-not $installedPackages -and -not (Test-WildcardPattern -Name $moduleName)) { $availableModules = Get-Module -ListAvailable $moduleName -Verbose:$false | Microsoft.PowerShell.Utility\Select-Object -Unique -ErrorAction Ignore - if(-not $availableModules) - { + if (-not $availableModules) { $message = $LocalizedData.ModuleNotInstalledOnThisMachine -f ($moduleName) Write-Error -Message $message -ErrorId 'ModuleNotInstalledOnThisMachine' -Category InvalidOperation -TargetObject $moduleName } - else - { + else { $message = $LocalizedData.ModuleNotInstalledUsingPowerShellGet -f ($moduleName) Write-Error -Message $message -ErrorId 'ModuleNotInstalledUsingInstallModuleCmdlet' -Category InvalidOperation -TargetObject $moduleName } @@ -112,41 +103,36 @@ function Update-Module $installedPackages | Microsoft.PowerShell.Core\ForEach-Object {New-PSGetItemInfo -SoftwareIdentity $_ -Type $script:PSArtifactTypeModule} | - Microsoft.PowerShell.Core\ForEach-Object { - if(-not (Test-RunningAsElevated) -and $_.InstalledLocation.StartsWith($script:programFilesModulesPath, [System.StringComparison]::OrdinalIgnoreCase)) - { - if(-not (Test-WildcardPattern -Name $moduleName)) - { - $message = $LocalizedData.AdminPrivilegesRequiredForUpdate -f ($_.Name, $_.InstalledLocation) - Write-Error -Message $message -ErrorId "AdminPrivilegesAreRequiredForUpdate" -Category InvalidOperation -TargetObject $moduleName - } - continue - } - - $PSGetItemInfos += $_ + Microsoft.PowerShell.Core\ForEach-Object { + if (-not (Test-RunningAsElevated) -and $_.InstalledLocation.StartsWith($script:programFilesModulesPath, [System.StringComparison]::OrdinalIgnoreCase)) { + if (-not (Test-WildcardPattern -Name $moduleName)) { + $message = $LocalizedData.AdminPrivilegesRequiredForUpdate -f ($_.Name, $_.InstalledLocation) + Write-Error -Message $message -ErrorId "AdminPrivilegesAreRequiredForUpdate" -Category InvalidOperation -TargetObject $moduleName } + continue + } + + $PSGetItemInfos += $_ + } } } - else - { + else { $PSGetItemInfos = PackageManagement\Get-Package @GetPackageParameters | - Microsoft.PowerShell.Core\ForEach-Object {New-PSGetItemInfo -SoftwareIdentity $_ -Type $script:PSArtifactTypeModule} | - Microsoft.PowerShell.Core\Where-Object { - (Test-RunningAsElevated) -or - $_.InstalledLocation.StartsWith($script:MyDocumentsModulesPath, [System.StringComparison]::OrdinalIgnoreCase) - } + Microsoft.PowerShell.Core\ForEach-Object {New-PSGetItemInfo -SoftwareIdentity $_ -Type $script:PSArtifactTypeModule} | + Microsoft.PowerShell.Core\Where-Object { + (Test-RunningAsElevated) -or + $_.InstalledLocation.StartsWith($script:MyDocumentsModulesPath, [System.StringComparison]::OrdinalIgnoreCase) + } } $PSBoundParameters["Provider"] = $script:PSModuleProviderName $PSBoundParameters[$script:PSArtifactType] = $script:PSArtifactTypeModule - foreach($psgetItemInfo in $PSGetItemInfos) - { + foreach ($psgetItemInfo in $PSGetItemInfos) { # Skip the module name if it is already tried in the current pipeline - if($moduleNamesInPipeline -contains $psgetItemInfo.Name) - { + if ($moduleNamesInPipeline -contains $psgetItemInfo.Name) { continue } @@ -156,8 +142,7 @@ function Update-Module Write-Verbose -Message $message $providerName = Get-ProviderName -PSCustomObject $psgetItemInfo - if(-not $providerName) - { + if (-not $providerName) { $providerName = $script:NuGetProviderName } @@ -165,21 +150,17 @@ function Update-Module $PSBoundParameters["Name"] = $psgetItemInfo.Name $PSBoundParameters['Source'] = $psgetItemInfo.Repository - Get-PSGalleryApiAvailability -Repository (Get-SourceName -Location $psgetItemInfo.RepositorySourceLocation) - $PSBoundParameters["PackageManagementProvider"] = $providerName $PSBoundParameters["InstallUpdate"] = $true - if($psgetItemInfo.InstalledLocation.ToString().StartsWith($script:MyDocumentsModulesPath, [System.StringComparison]::OrdinalIgnoreCase)) - { + if ($psgetItemInfo.InstalledLocation.ToString().StartsWith($script:MyDocumentsModulesPath, [System.StringComparison]::OrdinalIgnoreCase)) { $PSBoundParameters["Scope"] = "CurrentUser" } - else - { + else { $PSBoundParameters['Scope'] = 'AllUsers' } $sid = PackageManagement\Install-Package @PSBoundParameters } } -} \ No newline at end of file +} diff --git a/src/PowerShellGet/public/psgetfunctions/Update-Script.ps1 b/src/PowerShellGet/public/psgetfunctions/Update-Script.ps1 index e06e002f..ceb2460f 100644 --- a/src/PowerShellGet/public/psgetfunctions/Update-Script.ps1 +++ b/src/PowerShellGet/public/psgetfunctions/Update-Script.ps1 @@ -1,38 +1,37 @@ -function Update-Script -{ +function Update-Script { <# .ExternalHelp PSModule-help.xml #> - [CmdletBinding(SupportsShouldProcess=$true, - HelpUri='https://go.microsoft.com/fwlink/?LinkId=619787')] + [CmdletBinding(SupportsShouldProcess = $true, + HelpUri = 'https://go.microsoft.com/fwlink/?LinkId=619787')] Param ( - [Parameter(ValueFromPipelineByPropertyName=$true, - Position=0)] + [Parameter(ValueFromPipelineByPropertyName = $true, + Position = 0)] [ValidateNotNullOrEmpty()] [String[]] $Name, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [ValidateNotNull()] [string] $RequiredVersion, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [ValidateNotNull()] [string] $MaximumVersion, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [ValidateNotNullOrEmpty()] [Uri] $Proxy, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [PSCredential] $ProxyCredential, - [Parameter(ValueFromPipelineByPropertyName=$true)] + [Parameter(ValueFromPipelineByPropertyName = $true)] [PSCredential] $Credential, @@ -49,56 +48,46 @@ function Update-Script $AcceptLicense ) - Begin - { + Begin { Install-NuGetClientBinaries -CallerPSCmdlet $PSCmdlet -Proxy $Proxy -ProxyCredential $ProxyCredential # Script names already tried in the current pipeline $scriptNamesInPipeline = @() } - Process - { + Process { $scriptFilePathsToUpdate = @() $ValidationResult = Validate-VersionParameters -CallerPSCmdlet $PSCmdlet ` - -Name $Name ` - -MaximumVersion $MaximumVersion ` - -RequiredVersion $RequiredVersion ` - -AllowPrerelease:$AllowPrerelease + -Name $Name ` + -MaximumVersion $MaximumVersion ` + -RequiredVersion $RequiredVersion ` + -AllowPrerelease:$AllowPrerelease - if(-not $ValidationResult) - { + if (-not $ValidationResult) { # Validate-VersionParameters throws the error. # returning to avoid further execution when different values are specified for -ErrorAction parameter return } - if($Name) - { - foreach($scriptName in $Name) - { + if ($Name) { + foreach ($scriptName in $Name) { $availableScriptPaths = Get-AvailableScriptFilePath -Name $scriptName -Verbose:$false - if(-not $availableScriptPaths -and -not (Test-WildcardPattern -Name $scriptName)) - { + if (-not $availableScriptPaths -and -not (Test-WildcardPattern -Name $scriptName)) { $message = $LocalizedData.ScriptNotInstalledOnThisMachine -f ($scriptName, $script:MyDocumentsScriptsPath, $script:ProgramFilesScriptsPath) Write-Error -Message $message -ErrorId "ScriptNotInstalledOnThisMachine" -Category InvalidOperation -TargetObject $scriptName continue } - foreach($scriptFilePath in $availableScriptPaths) - { + foreach ($scriptFilePath in $availableScriptPaths) { $installedScriptFilePath = Get-InstalledScriptFilePath -Name ([System.IO.Path]::GetFileNameWithoutExtension($scriptFilePath)) | - Microsoft.PowerShell.Core\Where-Object {$_ -eq $scriptFilePath } + Microsoft.PowerShell.Core\Where-Object {$_ -eq $scriptFilePath } # Check if this script got installed with PowerShellGet and user has required permissions - if ($installedScriptFilePath) - { - if(-not (Test-RunningAsElevated) -and $installedScriptFilePath.StartsWith($script:ProgramFilesScriptsPath, [System.StringComparison]::OrdinalIgnoreCase)) - { - if(-not (Test-WildcardPattern -Name $scriptName)) - { + if ($installedScriptFilePath) { + if (-not (Test-RunningAsElevated) -and $installedScriptFilePath.StartsWith($script:ProgramFilesScriptsPath, [System.StringComparison]::OrdinalIgnoreCase)) { + if (-not (Test-WildcardPattern -Name $scriptName)) { $message = $LocalizedData.AdminPrivilegesRequiredForScriptUpdate -f ($scriptName, $installedScriptFilePath) Write-Error -Message $message -ErrorId "AdminPrivilegesAreRequiredForUpdate" -Category InvalidOperation -TargetObject $scriptName } @@ -107,10 +96,8 @@ function Update-Script $scriptFilePathsToUpdate += $installedScriptFilePath } - else - { - if(-not (Test-WildcardPattern -Name $scriptName)) - { + else { + if (-not (Test-WildcardPattern -Name $scriptName)) { $message = $LocalizedData.ScriptNotInstalledUsingPowerShellGet -f ($scriptName) Write-Error -Message $message -ErrorId "ScriptNotInstalledUsingPowerShellGet" -Category InvalidOperation -TargetObject $scriptName } @@ -119,20 +106,17 @@ function Update-Script } } } - else - { + else { $isRunningAsElevated = Test-RunningAsElevated $installedScriptFilePaths = Get-InstalledScriptFilePath - if($isRunningAsElevated) - { + if ($isRunningAsElevated) { $scriptFilePathsToUpdate = $installedScriptFilePaths } - else - { + else { # Update the scripts installed under $scriptFilePathsToUpdate = $installedScriptFilePaths | Microsoft.PowerShell.Core\Where-Object { - $_.StartsWith($script:MyDocumentsScriptsPath, [System.StringComparison]::OrdinalIgnoreCase)} + $_.StartsWith($script:MyDocumentsScriptsPath, [System.StringComparison]::OrdinalIgnoreCase)} } } @@ -140,46 +124,40 @@ function Update-Script $PSBoundParameters[$script:PSArtifactType] = $script:PSArtifactTypeScript $PSBoundParameters["InstallUpdate"] = $true - foreach($scriptFilePath in $scriptFilePathsToUpdate) - { + foreach ($scriptFilePath in $scriptFilePathsToUpdate) { $scriptName = [System.IO.Path]::GetFileNameWithoutExtension($scriptFilePath) $installedScriptInfoFilePath = $null $installedScriptInfoFileName = "$($scriptName)_$script:InstalledScriptInfoFileName" - if($scriptFilePath.ToString().StartsWith($script:MyDocumentsScriptsPath, [System.StringComparison]::OrdinalIgnoreCase)) - { + if ($scriptFilePath.ToString().StartsWith($script:MyDocumentsScriptsPath, [System.StringComparison]::OrdinalIgnoreCase)) { $PSBoundParameters["Scope"] = "CurrentUser" $installedScriptInfoFilePath = Microsoft.PowerShell.Management\Join-Path -Path $script:MyDocumentsInstalledScriptInfosPath ` - -ChildPath $installedScriptInfoFileName + -ChildPath $installedScriptInfoFileName } - elseif($scriptFilePath.ToString().StartsWith($script:ProgramFilesScriptsPath, [System.StringComparison]::OrdinalIgnoreCase)) - { + elseif ($scriptFilePath.ToString().StartsWith($script:ProgramFilesScriptsPath, [System.StringComparison]::OrdinalIgnoreCase)) { $PSBoundParameters["Scope"] = "AllUsers" $installedScriptInfoFilePath = Microsoft.PowerShell.Management\Join-Path -Path $script:ProgramFilesInstalledScriptInfosPath ` - -ChildPath $installedScriptInfoFileName + -ChildPath $installedScriptInfoFileName } $psgetItemInfo = $null - if($installedScriptInfoFilePath -and (Microsoft.PowerShell.Management\Test-Path -Path $installedScriptInfoFilePath -PathType Leaf)) - { + if ($installedScriptInfoFilePath -and (Microsoft.PowerShell.Management\Test-Path -Path $installedScriptInfoFilePath -PathType Leaf)) { $psgetItemInfo = DeSerialize-PSObject -Path $installedScriptInfoFilePath } # Skip the script name if it is already tried in the current pipeline - if(-not $psgetItemInfo -or ($scriptNamesInPipeline -contains $psgetItemInfo.Name)) - { + if (-not $psgetItemInfo -or ($scriptNamesInPipeline -contains $psgetItemInfo.Name)) { continue } $scriptFilePath = Microsoft.PowerShell.Management\Join-Path -Path $psgetItemInfo.InstalledLocation ` - -ChildPath "$($psgetItemInfo.Name).ps1" + -ChildPath "$($psgetItemInfo.Name).ps1" # Remove the InstalledScriptInfo.xml file if the actual script file was manually uninstalled by the user - if(-not (Microsoft.PowerShell.Management\Test-Path -Path $scriptFilePath -PathType Leaf)) - { + if (-not (Microsoft.PowerShell.Management\Test-Path -Path $scriptFilePath -PathType Leaf)) { Microsoft.PowerShell.Management\Remove-Item -Path $installedScriptInfoFilePath -Force -ErrorAction SilentlyContinue continue @@ -191,8 +169,7 @@ function Update-Script Write-Verbose -Message $message $providerName = Get-ProviderName -PSCustomObject $psgetItemInfo - if(-not $providerName) - { + if (-not $providerName) { $providerName = $script:NuGetProviderName } @@ -200,14 +177,12 @@ function Update-Script $PSBoundParameters["PackageManagementProvider"] = $providerName $PSBoundParameters["Name"] = $psgetItemInfo.Name $PSBoundParameters['Source'] = $psgetItemInfo.Repository - if($AllowPrerelease) { + if ($AllowPrerelease) { $PSBoundParameters[$script:AllowPrereleaseVersions] = $true } $null = $PSBoundParameters.Remove("AllowPrerelease") - Get-PSGalleryApiAvailability -Repository (Get-SourceName -Location $psgetItemInfo.RepositorySourceLocation) - $sid = PackageManagement\Install-Package @PSBoundParameters } } -} \ No newline at end of file +} diff --git a/src/PowerShellGet/public/psgetfunctions/Update-ScriptFileInfo.ps1 b/src/PowerShellGet/public/psgetfunctions/Update-ScriptFileInfo.ps1 index 29e7ab8e..3851e3bb 100644 --- a/src/PowerShellGet/public/psgetfunctions/Update-ScriptFileInfo.ps1 +++ b/src/PowerShellGet/public/psgetfunctions/Update-ScriptFileInfo.ps1 @@ -295,6 +295,11 @@ function Update-ScriptFileInfo { $ReleaseNotes = $psscriptInfo.ReleaseNotes } + + if(-not $PrivateData -and $psscriptInfo.PrivateData) + { + $PrivateData = $psscriptInfo.PrivateData + } } $params = @{