Skip to content

Instantly share code, notes, and snippets.

@qbikez qbikez/PSGet.psm1
Last active Feb 19, 2016

Embed
What would you like to do?
psget with fixes for unattended use
@{
RootModule = 'PSGet.psm1'
ModuleVersion = '1.0.0.1'
GUID = '1d73a601-4a6c-43c5-ba3f-619b18bbb404'
Author = 'Microsoft Corporation'
CompanyName = 'Microsoft Corporation'
Copyright = '© Microsoft Corporation. All rights reserved.'
PowerShellVersion = '3.0'
FormatsToProcess = 'PSGet.Format.ps1xml'
FunctionsToExport = @('Install-Module',
'Find-Module',
'Save-Module',
'Update-Module',
'Publish-Module',
'Get-InstalledModule',
'Uninstall-Module',
'Get-PSRepository',
'Set-PSRepository',
'Register-PSRepository',
'Unregister-PSRepository',
'Install-NugetClientBinaries')
VariablesToExport = "*"
AliasesToExport = @('inmo',
'fimo',
'upmo',
'pumo')
FileList = @('PSGet.psm1',
'PSGet.Format.ps1xml',
'PSGet.Resource.psd1')
RequiredModules = @('PackageManagement')
PrivateData = @{
"PackageManagementProviders" = 'PSGet.psm1'
"SupportedPowerShellGetFormatVersions" = @('1.x')
}
HelpInfoURI = 'http://go.microsoft.com/fwlink/?LinkId=393271'
}
# SIG # Begin signature block
# MIIavwYJKoZIhvcNAQcCoIIasDCCGqwCAQExCzAJBgUrDgMCGgUAMGkGCisGAQQB
# gjcCAQSgWzBZMDQGCisGAQQBgjcCAR4wJgIDAQAABBAfzDtgWUsITrck0sYpfvNR
# AgEAAgEAAgEAAgEAAgEAMCEwCQYFKw4DAhoFAAQUmUZl/ETPT3/j8upaLTyoawvY
# aNagghWCMIIEwzCCA6ugAwIBAgITMwAAAHPGWcJSl4OjOgAAAAAAczANBgkqhkiG
# 9w0BAQUFADB3MQswCQYDVQQGEwJVUzETMBEGA1UECBMKV2FzaGluZ3RvbjEQMA4G
# A1UEBxMHUmVkbW9uZDEeMBwGA1UEChMVTWljcm9zb2Z0IENvcnBvcmF0aW9uMSEw
# HwYDVQQDExhNaWNyb3NvZnQgVGltZS1TdGFtcCBQ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dMBgGCSqGSIb3DQEJAzELBgkqhkiG9w0BBwEwHAYJKoZIhvcNAQkFMQ8XDTE1
# MDQwODIyNTIyM1owIwYJKoZIhvcNAQkEMRYEFDX52OzAamVEaYZI6znJ6cIfbYzE
# MA0GCSqGSIb3DQEBBQUABIIBAAAogPPsW0bRDMyTLvAj5gijvM+uTcKi9BfE6WWr
# Kp7GjYrXJq1exO63HjmES3FPz2SffCR4eDots2VVhKaJSkZvuiacGOdEyDpgfrni
# vCkr0333ZXZr4pOETegepGxLoZwiM6+qjBYjQ013F5grkBj+Pgyuiib3jmnkhLq5
# DeTZ/5iSK+fuZ5BI+tt4RtFdGLcFAa5yrFaD1UtkDOTpNv9PylUUP/Ncf/UWn3kZ
# EzRh45RyPi9poimQQRWCFtyQV9aIHuxSgddslT0OcbaDyKJbxUxxR0RgJeVWD6Yl
# AbkEYL6PIgkesKoV4L6WNkCbI1uNK1VUAs/TPLUslYM+QTI=
# SIG # End signature block
#########################################################################################
#
# Copyright (c) Microsoft Corporation. All rights reserved.
#
# PowerShellGet Module
#
#########################################################################################
Microsoft.PowerShell.Core\Set-StrictMode -Version Latest
$script:ProgramFilesModulesPath = Microsoft.PowerShell.Management\Join-Path -Path $env:ProgramFiles -ChildPath "WindowsPowerShell\Modules"
$script:MyDocumentsModulesPath = if([Environment]::GetFolderPath("MyDocuments"))
{
Microsoft.PowerShell.Management\Join-Path -Path ([Environment]::GetFolderPath("MyDocuments")) -ChildPath "WindowsPowerShell\Modules"
}
else
{
Microsoft.PowerShell.Management\Join-Path -Path $env:USERPROFILE -ChildPath "Documents\WindowsPowerShell\Modules"
}
$script:TempPath = ([System.IO.DirectoryInfo]$env:TEMP).FullName
$script:PSGetItemInfoFileName = "PSGetModuleInfo.xml"
$script:PSGetAppLocalPath="$env:LOCALAPPDATA\Microsoft\Windows\PowerShell\PowerShellGet"
$script:PSGetModuleSourcesFilePath = Microsoft.PowerShell.Management\Join-Path -Path $script:PSGetAppLocalPath -ChildPath "PSRepositories.xml"
$script:PSGetModuleSources = $null
$script:PSGetInstalledModules = $null
# Public PSGallery module source name and location
$Script:PSGalleryModuleSource="PSGallery"
$Script:PSGallerySourceUri = 'https://go.microsoft.com/fwlink/?LinkID=397631&clcid=0x409'
$Script:PSGalleryPublishUri = 'https://go.microsoft.com/fwlink/?LinkID=397527&clcid=0x409'
# PSGallery V3 Source
$Script:PSGalleryV3SourceUri = 'https://go.microsoft.com/fwlink/?LinkId=528403&clcid=0x409'
$Script:PSGalleryV2ApiAvailable = $true
$Script:PSGalleryV3ApiAvailable = $false
$Script:PSGalleryApiChecked = $false
$Script:ResponseUri = "ResponseUri"
$Script:StatusCode = "StatusCode"
$Script:Exception = "Exception"
$script:PSModuleProviderName = "PSModule"
$script:PackageManagementProviderParam = "PackageManagementProvider"
$script:PublishLocation = "PublishLocation"
$script:NuGetProviderName = "NuGet"
$script:SupportsPSModulesFeatureName="supports-powershell-modules"
$script:FastPackRefHastable = @{}
$script:NuGetBinaryProgramDataPath="$env:ProgramFiles\PackageManagement\ProviderAssemblies"
$script:NuGetBinaryLocalAppDataPath="$env:LOCALAPPDATA\PackageManagement\ProviderAssemblies"
$script:NuGetClient = $null
# PowerShellGetFormatVersion will be incremented when we change the .nupkg format structure.
# PowerShellGetFormatVersion is in the form of Major.Minor.
# Minor is incremented for the backward compatible format change.
# Major is incremented for the breaking change.
$script:CurrentPSGetFormatVersion = "1.0"
$script:PSGetFormatVersion = "PowerShellGetFormatVersion"
$script:SupportedPSGetFormatVersionMajors = @("1")
$script:ModuleReferences = 'Module References'
$script:AllVersions = "AllVersions"
$script:Filter = "Filter"
$script:IncludeValidSet = @("DscResource","Cmdlet","Function")
$script:DscResource = "PSDscResource"
$script:Command = "PSCommand"
$script:Cmdlet = "PSCmdlet"
$script:Function = "PSFunction"
$script:Includes = "PSIncludes"
$script:Tag = "Tag"
$script:NotSpecified= '_NotSpecified_'
$script:PSGetModuleName = 'PowerShellGet'
$script:FindByCanonicalId = 'FindByCanonicalId'
# Wildcard pattern matching configuration.
$script:wildcardOptions = [System.Management.Automation.WildcardOptions]::CultureInvariant -bor `
[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
}
$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)
}
}
}
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 "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
}
}
}
}
Microsoft.PowerShell.Utility\Import-LocalizedData LocalizedData -filename PSGet.Resource.psd1
#region Add .Net type for Telemetry APIs
# This code is required to add a .Net type and call the Telemetry APIs
# This is required since PowerShell does not support generation of .Net Anonymous types
#
$requiredAssembly = (
"system.management.automation, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
)
$source = @"
using System;
using System.Management.Automation;
namespace Microsoft.PowerShell.Get
{
public static class Telemetry
{
public static void TraceMessageModulesNotFound(string[] modulesNotFound)
{
Microsoft.PowerShell.Telemetry.Internal.TelemetryAPI.TraceMessage("PSGET_FIND_MODULE",new { ModulesNotFound = modulesNotFound });
}
}
}
"@
# Telemetry is turned off by default.
$script:TelemetryEnabled = $false
try
{
Add-Type -ReferencedAssemblies $requiredAssembly -TypeDefinition $source -Language CSharp -ErrorAction SilentlyContinue
if (([Microsoft.PowerShell.Get.Telemetry] | Get-Member -Static).Name.Contains("TraceMessageModulesNotFound"))
{
# Turn ON Telemetry if the infrastructure is present on the machine
$script:TelemetryEnabled = $true
}
}
catch
{
# Disable Telemetry if there are any issues finding/loading the Telemetry infrastructure
$script:TelemetryEnabled = $false
}
#endregion
function Publish-Module
{
<#
.ExternalHelp PSGet.psm1-help.xml
#>
[CmdletBinding(SupportsShouldProcess=$true,
PositionalBinding=$false,
HelpUri='http://go.microsoft.com/fwlink/?LinkID=398575',
DefaultParameterSetName="ModuleNameParameterSet")]
Param
(
[Parameter(Mandatory=$true,
ParameterSetName="ModuleNameParameterSet",
ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[string]
$Name,
[Parameter(Mandatory=$true,
ParameterSetName="ModulePathParameterSet",
ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[string]
$Path,
[Parameter(ParameterSetName="ModuleNameParameterSet")]
[ValidateNotNullOrEmpty()]
[Version]
$RequiredVersion,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$NuGetApiKey,
[Parameter()]
[ValidateNotNullOrEmpty()]
[string]
$Repository = $Script:PSGalleryModuleSource,
[Parameter()]
[ValidateSet("1.0")]
[Version]
$FormatVersion,
[Parameter()]
[ValidateNotNullOrEmpty()]
[string[]]
$ReleaseNotes,
[Parameter()]
[ValidateNotNullOrEmpty()]
[string[]]
$Tags,
[Parameter()]
[ValidateNotNullOrEmpty()]
[Uri]
$LicenseUri,
[Parameter()]
[ValidateNotNullOrEmpty()]
[Uri]
$IconUri,
[Parameter()]
[ValidateNotNullOrEmpty()]
[Uri]
$ProjectUri
)
Begin
{
Get-PSGalleryApiAvailability -Repository $Repository
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
}
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
}
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
}
$moduleSource = Get-PSRepository -Name $Repository
$DestinationLocation = $moduleSource.PublishLocation
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
}
$providerName = Get-ProviderName -PSCustomObject $moduleSource
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
}
Install-NuGetClientBinaries
}
Process
{
if($Name)
{
$module = Microsoft.PowerShell.Core\Get-Module -ListAvailable -Name $Name -Verbose:$false |
Microsoft.PowerShell.Core\Where-Object {-not $RequiredVersion -or ($RequiredVersion -eq $_.Version)}
if(-not $module)
{
if($RequiredVersion)
{
$message = $LocalizedData.ModuleWithRequiredVersionNotAvailableLocally -f ($Name, $RequiredVersion)
}
else
{
$message = $LocalizedData.ModuleNotAvailableLocally -f ($Name)
}
ThrowError -ExceptionName "System.ArgumentException" `
-ExceptionMessage $message `
-ErrorId "ModuleNotAvailableLocallyToPublish" `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidArgument `
-ExceptionObject $Name
}
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
}
$Path = $module.ModuleBase
}
else
{
if(-not (Microsoft.PowerShell.Management\Test-Path -path $Path -PathType Container))
{
ThrowError -ExceptionName "System.ArgumentException" `
-ExceptionMessage ($LocalizedData.PathIsNotADirectory -f ($Path)) `
-ErrorId "PathIsNotADirectory" `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidArgument `
-ExceptionObject $Path
}
}
$moduleName = Microsoft.PowerShell.Management\Split-Path $Path -Leaf
# if the Leaf of the $Path is a version, use its parent folder name as the module name
$ModuleVersion = New-Object System.Version
if([System.Version]::TryParse($moduleName, ([ref]$ModuleVersion)))
{
$moduleName = Microsoft.PowerShell.Management\Split-Path -Path (Microsoft.PowerShell.Management\Split-Path $Path -Parent) -Leaf
}
$message = $LocalizedData.PublishModuleLocation -f ($moduleName, $Path)
Write-Verbose -Message $message
# 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"
if(-not $FormatVersion)
{
$tempModulePathForFormatVersion = $tempModulePath
}
elseif ($FormatVersion -eq "1.0")
{
$tempModulePathForFormatVersion = Microsoft.PowerShell.Management\Join-Path $tempModulePath "Content\Deployment\$script:ModuleReferences\$moduleName"
}
$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
{
$manifestPath = Microsoft.PowerShell.Management\Join-Path $tempModulePathForFormatVersion "$moduleName.psd1"
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
}
$moduleInfo = Microsoft.PowerShell.Core\Test-ModuleManifest -Path $manifestPath `
-Verbose:$VerbosePreference
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
}
$currentPSGetItemInfo = Find-Module -Name $moduleInfo.Name `
-Repository $Repository `
-Verbose:$VerbosePreference `
-ErrorAction SilentlyContinue `
-WarningAction SilentlyContinue `
-Debug:$DebugPreference |
Microsoft.PowerShell.Core\Where-Object {$_.Name -eq $moduleInfo.Name} |
Microsoft.PowerShell.Utility\Select-Object -Last 1
if($currentPSGetItemInfo -and $currentPSGetItemInfo.Version -ge $moduleInfo.Version)
{
$message = $LocalizedData.ModuleVersionShouldBeGreaterThanGalleryVersion -f ($moduleInfo.Name, $moduleInfo.Version, $currentPSGetItemInfo.Version, $currentPSGetItemInfo.RepositorySourceLocation)
ThrowError -ExceptionName "System.InvalidOperationException" `
-ExceptionMessage $message `
-ErrorId "ModuleVersionShouldBeGreaterThanGalleryVersion" `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidOperation
}
$shouldProcessMessage = $LocalizedData.PublishModulewhatIfMessage -f ($moduleInfo.Version, $moduleInfo.Name)
if($PSCmdlet.ShouldProcess($shouldProcessMessage, "Publish-Module"))
{
Publish-PSGetExtModule -PSModuleInfo $moduleInfo `
-NugetApiKey $NuGetApiKey `
-Destination $DestinationLocation `
-Repository $Repository `
-NugetPackageRoot $tempModulePath `
-FormatVersion $FormatVersion `
-ReleaseNotes "$ReleaseNotes" `
-Tags $Tags `
-LicenseUri $LicenseUri `
-IconUri $IconUri `
-ProjectUri $ProjectUri `
-Verbose:$VerbosePreference `
-WarningAction $WarningPreference `
-ErrorAction $ErrorActionPreference `
-Debug:$DebugPreference
}
}
finally
{
Microsoft.PowerShell.Management\Remove-Item $tempModulePath -Force -Recurse -ErrorAction SilentlyContinue -WarningAction SilentlyContinue -Confirm:$false -WhatIf:$false
}
}
}
function Find-Module
{
<#
.ExternalHelp PSGet.psm1-help.xml
#>
[CmdletBinding(HelpUri='http://go.microsoft.com/fwlink/?LinkID=398574')]
[outputtype("PSCustomObject[]")]
Param
(
[Parameter(ValueFromPipelineByPropertyName=$true,
Position=0)]
[ValidateNotNullOrEmpty()]
[string[]]
$Name,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[ValidateNotNull()]
[Alias("Version")]
[Version]
$MinimumVersion,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[ValidateNotNull()]
[Version]
$MaximumVersion,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[ValidateNotNull()]
[Version]
$RequiredVersion,
[Parameter()]
[switch]
$AllVersions,
[Parameter()]
[switch]
$IncludeDependencies,
[Parameter()]
[ValidateNotNull()]
[string]
$Filter,
[Parameter()]
[ValidateNotNull()]
[string[]]
$Tag,
[Parameter()]
[ValidateNotNull()]
[ValidateSet("DscResource","Cmdlet","Function")]
[string[]]
$Includes,
[Parameter()]
[ValidateNotNull()]
[string[]]
$DscResource,
[Parameter()]
[ValidateNotNull()]
[string[]]
$Command,
[Parameter()]
[ValidateNotNullOrEmpty()]
[string[]]
$Repository
)
Begin
{
Get-PSGalleryApiAvailability -Repository $Repository
Install-NuGetClientBinaries
}
Process
{
$ValidationResult = Validate-VersionParameters -CallerPSCmdlet $PSCmdlet `
-Name $Name `
-MinimumVersion $MinimumVersion `
-MaximumVersion $MaximumVersion `
-RequiredVersion $RequiredVersion
if(-not $ValidationResult)
{
# Validate-VersionParameters throws the error.
# returning to avoid further execution when different values are specified for -ErrorAction parameter
return
}
$PSBoundParameters["Provider"] = $script:PSModuleProviderName
if($PSBoundParameters.ContainsKey("Repository"))
{
$PSBoundParameters["Source"] = $Repository
$null = $PSBoundParameters.Remove("Repository")
}
$PSBoundParameters["MessageResolver"] = $script:PackageManagementMessageResolverScriptBlock
$modulesFoundInPSGallery = @()
# No Telemetry must be performed if PSGallery is not in the supplied list of Repositories
$isRepositoryNullOrPSGallerySpecified = $false
if ((-not $Repository) -or ($Repository -and ($Repository -Contains $Script:PSGalleryModuleSource)))
{
$isRepositoryNullOrPSGallerySpecified = $true
}
PackageManagement\Find-Package @PSBoundParameters | Microsoft.PowerShell.Core\ForEach-Object {
$psgetItemInfo = New-PSGetItemInfo -SoftwareIdenties $_;
$psgetItemInfo
if ($psgetItemInfo -and
$isRepositoryNullOrPSGallerySpecified -and
$script:TelemetryEnabled -and
($psgetItemInfo.Repository -eq $Script:PSGalleryModuleSource))
{
$modulesFoundInPSGallery += $psgetItemInfo.Name
}
}
# Perform Telemetry if Repository is not supplied or Repository contains PSGallery
# We are only interested in finding modules not in PSGallery
if ($isRepositoryNullOrPSGallerySpecified)
{
Log-ModulesNotFound -ModulesSearched $Name -ModulesFound $modulesFoundInPSGallery
}
}
}
function Save-Module
{
<#
.ExternalHelp PSGet.psm1-help.xml
#>
[CmdletBinding(DefaultParameterSetName='NameAndPathParameterSet',
HelpUri='http://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')]
[ValidateNotNullOrEmpty()]
[string[]]
$Name,
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0,
ParameterSetName='InputOjectAndPathParameterSet')]
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0,
ParameterSetName='InputOjectAndLiteralPathParameterSet')]
[ValidateNotNull()]
[PSCustomObject[]]
$InputObject,
[Parameter(ValueFromPipelineByPropertyName=$true,
ParameterSetName='NameAndPathParameterSet')]
[Parameter(ValueFromPipelineByPropertyName=$true,
ParameterSetName='NameAndLiteralPathParameterSet')]
[Alias("Version")]
[ValidateNotNull()]
[Version]
$MinimumVersion,
[Parameter(ValueFromPipelineByPropertyName=$true,
ParameterSetName='NameAndPathParameterSet')]
[Parameter(ValueFromPipelineByPropertyName=$true,
ParameterSetName='NameAndLiteralPathParameterSet')]
[ValidateNotNull()]
[Version]
$MaximumVersion,
[Parameter(ValueFromPipelineByPropertyName=$true,
ParameterSetName='NameAndPathParameterSet')]
[Parameter(ValueFromPipelineByPropertyName=$true,
ParameterSetName='NameAndLiteralPathParameterSet')]
[ValidateNotNull()]
[Version]
$RequiredVersion,
[Parameter(ValueFromPipelineByPropertyName=$true,
ParameterSetName='NameAndPathParameterSet')]
[Parameter(ValueFromPipelineByPropertyName=$true,
ParameterSetName='NameAndLiteralPathParameterSet')]
[ValidateNotNullOrEmpty()]
[string[]]
$Repository,
[Parameter(Mandatory=$true, ParameterSetName='NameAndPathParameterSet')]
[Parameter(Mandatory=$true, ParameterSetName='InputOjectAndPathParameterSet')]
[string]
$Path,
[Parameter(Mandatory=$true, ParameterSetName='NameAndLiteralPathParameterSet')]
[Parameter(Mandatory=$true, ParameterSetName='InputOjectAndLiteralPathParameterSet')]
[string]
$LiteralPath,
[Parameter()]
[switch]
$Force
)
Begin
{
Get-PSGalleryApiAvailability -Repository $Repository
Install-NuGetClientBinaries
# Module names already tried in the current pipeline for InputObject parameterset
$moduleNamesInPipeline = @()
}
Process
{
$PSBoundParameters["Provider"] = $script:PSModuleProviderName
$PSBoundParameters["MessageResolver"] = $script:PackageManagementSaveModuleMessageResolverScriptBlock
if($Path)
{
$null = $PSBoundParameters.Remove("Path")
$destinationPath = Resolve-PathHelper -Path $Path -CallerPSCmdlet $PSCmdlet | Microsoft.PowerShell.Utility\Select-Object -First 1
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
}
}
else
{
$null = $PSBoundParameters.Remove("LiteralPath")
$destinationPath = Resolve-PathHelper -Path $LiteralPath -IsLiteralPath -CallerPSCmdlet $PSCmdlet | Microsoft.PowerShell.Utility\Select-Object -First 1
if(-not $destinationPath -or -not (Microsoft.PowerShell.Management\Test-path $destinationPath))
{
$errorMessage = ($LocalizedData.PathNotFound -f $LiteralPath)
ThrowError -ExceptionName "System.ArgumentException" `
-ExceptionMessage $errorMessage `
-ErrorId "PathNotFound" `
-CallerPSCmdlet $PSCmdlet `
-ExceptionObject $LiteralPath `
-ErrorCategory InvalidArgument
}
}
$PSBoundParameters["DestinationPath"] = $destinationPath
if($Name)
{
$ValidationResult = Validate-VersionParameters -CallerPSCmdlet $PSCmdlet `
-Name $Name `
-MinimumVersion $MinimumVersion `
-MaximumVersion $MaximumVersion `
-RequiredVersion $RequiredVersion
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"))
{
$PSBoundParameters["Source"] = $Repository
$null = $PSBoundParameters.Remove("Repository")
}
if($PSBoundParameters.ContainsKey("Version"))
{
$null = $PSBoundParameters.Remove("Version")
$PSBoundParameters["MinimumVersion"] = $MinimumVersion
}
$null = PackageManagement\Install-Package @PSBoundParameters
}
elseif($InputObject)
{
$null = $PSBoundParameters.Remove("InputObject")
foreach($inputValue in $InputObject)
{
if (($inputValue.PSTypeNames -notcontains "Microsoft.PowerShell.Commands.PSGetModuleInfo") -and
($inputValue.PSTypeNames -notcontains "Deserialized.Microsoft.PowerShell.Commands.PSGetModuleInfo") -and
($inputValue.PSTypeNames -notcontains "Microsoft.PowerShell.Commands.PSGetDscResourceInfo") -and
($inputValue.PSTypeNames -notcontains "Deserialized.Microsoft.PowerShell.Commands.PSGetDscResourceInfo"))
{
ThrowError -ExceptionName "System.ArgumentException" `
-ExceptionMessage $LocalizedData.InvalidInputObjectValue `
-ErrorId "InvalidInputObjectValue" `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidArgument `
-ExceptionObject $inputValue
}
if( ($inputValue.PSTypeNames -contains "Microsoft.PowerShell.Commands.PSGetDscResourceInfo") -or
($inputValue.PSTypeNames -contains "Deserialized.Microsoft.PowerShell.Commands.PSGetDscResourceInfo"))
{
$psgetModuleInfo = $inputValue.PSGetModuleInfo
}
else
{
$psgetModuleInfo = $inputValue
}
# Skip the module name if it is already tried in the current pipeline
if($moduleNamesInPipeline -contains $psgetModuleInfo.Name)
{
continue
}
$moduleNamesInPipeline += $psgetModuleInfo.Name
if ($psgetModuleInfo.PowerShellGetFormatVersion -and
($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
}
$PSBoundParameters["Name"] = $psgetModuleInfo.Name
$PSBoundParameters["RequiredVersion"] = $psgetModuleInfo.Version
$PSBoundParameters["Location"] = $psgetModuleInfo.RepositorySourceLocation
$PSBoundParameters["PackageManagementProvider"] = (Get-ProviderName -PSCustomObject $psgetModuleInfo)
$null = PackageManagement\Install-Package @PSBoundParameters
}
}
}
}
function Install-Module
{
<#
.ExternalHelp PSGet.psm1-help.xml
#>
[CmdletBinding(DefaultParameterSetName='NameParameterSet',
HelpUri='http://go.microsoft.com/fwlink/?LinkID=398573',
SupportsShouldProcess=$true)]
Param
(
[Parameter(Mandatory=$true,
ValueFromPipelineByPropertyName=$true,
Position=0,
ParameterSetName='NameParameterSet')]
[ValidateNotNullOrEmpty()]
[string[]]
$Name,
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0,
ParameterSetName='InputObject')]
[ValidateNotNull()]
[PSCustomObject[]]
$InputObject,
[Parameter(ValueFromPipelineByPropertyName=$true,
ParameterSetName='NameParameterSet')]
[Alias("Version")]
[ValidateNotNull()]
[Version]
$MinimumVersion,
[Parameter(ValueFromPipelineByPropertyName=$true,
ParameterSetName='NameParameterSet')]
[ValidateNotNull()]
[Version]
$MaximumVersion,
[Parameter(ValueFromPipelineByPropertyName=$true,
ParameterSetName='NameParameterSet')]
[ValidateNotNull()]
[Version]
$RequiredVersion,
[Parameter(ParameterSetName='NameParameterSet')]
[ValidateNotNullOrEmpty()]
[string[]]
$Repository,
[Parameter()]
[ValidateSet("CurrentUser","AllUsers")]
[string]
$Scope = "AllUsers",
[Parameter()]
[switch]
$Force
)
Begin
{
Get-PSGalleryApiAvailability -Repository $Repository
if(-not (Test-RunningAsElevated) -and ($Scope -ne "CurrentUser"))
{
# Throw an error when Install-Module is used as a non-admin user and '-Scope CurrentUser' is not specified
$message = $LocalizedData.InstallModuleNeedsCurrentUserScopeParameterForNonAdminUser -f @($script:programFilesModulesPath, $script:MyDocumentsModulesPath)
ThrowError -ExceptionName "System.ArgumentException" `
-ExceptionMessage $message `
-ErrorId "InstallModuleNeedsCurrentUserScopeParameterForNonAdminUser" `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidArgument
}
Install-NuGetClientBinaries
# Module names already tried in the current pipeline for InputObject parameterset
$moduleNamesInPipeline = @()
$YesToAll = $false
$NoToAll = $false
$SourceSGrantedTrust = @()
$SourcesDeniedTrust = @()
}
Process
{
$RepositoryIsNotTrusted = $LocalizedData.RepositoryIsNotTrusted
$QueryInstallUntrustedPackage = $LocalizedData.QueryInstallUntrustedPackage
$PackageTarget = $LocalizedData.InstallModulewhatIfMessage
$PSBoundParameters["Provider"] = $script:PSModuleProviderName
$PSBoundParameters["MessageResolver"] = $script:PackageManagementInstallModuleMessageResolverScriptBlock
if($PSCmdlet.ParameterSetName -eq "NameParameterSet")
{
$ValidationResult = Validate-VersionParameters -CallerPSCmdlet $PSCmdlet `
-Name $Name `
-MinimumVersion $MinimumVersion `
-MaximumVersion $MaximumVersion `
-RequiredVersion $RequiredVersion
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"))
{
$PSBoundParameters["Source"] = $Repository
$null = $PSBoundParameters.Remove("Repository")
}
if($PSBoundParameters.ContainsKey("Version"))
{
$null = $PSBoundParameters.Remove("Version")
$PSBoundParameters["MinimumVersion"] = $MinimumVersion
}
$null = PackageManagement\Install-Package @PSBoundParameters
}
elseif($PSCmdlet.ParameterSetName -eq "InputObject")
{
$null = $PSBoundParameters.Remove("InputObject")
foreach($inputValue in $InputObject)
{
if (($inputValue.PSTypeNames -notcontains "Microsoft.PowerShell.Commands.PSGetModuleInfo") -and
($inputValue.PSTypeNames -notcontains "Deserialized.Microsoft.PowerShell.Commands.PSGetModuleInfo") -and
($inputValue.PSTypeNames -notcontains "Microsoft.PowerShell.Commands.PSGetDscResourceInfo") -and
($inputValue.PSTypeNames -notcontains "Deserialized.Microsoft.PowerShell.Commands.PSGetDscResourceInfo"))
{
ThrowError -ExceptionName "System.ArgumentException" `
-ExceptionMessage $LocalizedData.InvalidInputObjectValue `
-ErrorId "InvalidInputObjectValue" `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidArgument `
-ExceptionObject $inputValue
}
if( ($inputValue.PSTypeNames -contains "Microsoft.PowerShell.Commands.PSGetDscResourceInfo") -or
($inputValue.PSTypeNames -contains "Deserialized.Microsoft.PowerShell.Commands.PSGetDscResourceInfo"))
{
$psgetModuleInfo = $inputValue.PSGetModuleInfo
}
else
{
$psgetModuleInfo = $inputValue
}
# Skip the module name if it is already tried in the current pipeline
if($moduleNamesInPipeline -contains $psgetModuleInfo.Name)
{
continue
}
$moduleNamesInPipeline += $psgetModuleInfo.Name
if ($psgetModuleInfo.PowerShellGetFormatVersion -and
($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
}
$PSBoundParameters["Name"] = $psgetModuleInfo.Name
$PSBoundParameters["RequiredVersion"] = $psgetModuleInfo.Version
$PSBoundParameters["Location"] = $psgetModuleInfo.RepositorySourceLocation
$PSBoundParameters["PackageManagementProvider"] = (Get-ProviderName -PSCustomObject $psgetModuleInfo)
$InstalledModuleInfo = Test-ModuleInstalled -Name $psgetModuleInfo.Name -RequiredVersion $psgetModuleInfo.Version
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
$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 [Version]"5.0")
{
$sourceTrusted = $psCmdlet.ShouldContinue("$message", "$RepositoryIsNotTrusted",$true, [ref]$YesToAll, [ref]$NoToAll)
}
else
{
$sourceTrusted = $psCmdlet.ShouldContinue("$message", "$RepositoryIsNotTrusted", [ref]$YesToAll, [ref]$NoToAll)
}
if($sourceTrusted)
{
$SourceSGrantedTrust+=$source
}
else
{
$SourcesDeniedTrust+=$source
}
}
}
}
if($installationPolicy.Equals("trusted", [StringComparison]::OrdinalIgnoreCase) -or $SourceSGrantedTrust.Contains($source) -or $YesToAll -or $Force)
{
$PSBoundParameters["Force"] = $true
$null = PackageManagement\Install-Package @PSBoundParameters
}
}
}
}
}
}
function Update-Module
{
<#
.ExternalHelp PSGet.psm1-help.xml
#>
[CmdletBinding(SupportsShouldProcess=$true,
HelpUri='http://go.microsoft.com/fwlink/?LinkID=398576')]
Param
(
[Parameter(ValueFromPipelineByPropertyName=$true,
Position=0)]
[ValidateNotNullOrEmpty()]
[String[]]
$Name,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[ValidateNotNull()]
[Version]
$RequiredVersion,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[ValidateNotNull()]
[Version]
$MaximumVersion,
[Parameter()]
[Switch]
$Force
)
Begin
{
Install-NuGetClientBinaries
# Module names already tried in the current pipeline
$moduleNamesInPipeline = @()
}
Process
{
$moduleBasesToUpdate = @()
$ValidationResult = Validate-VersionParameters -CallerPSCmdlet $PSCmdlet `
-Name $Name `
-MaximumVersion $MaximumVersion `
-RequiredVersion $RequiredVersion
if(-not $ValidationResult)
{
# Validate-VersionParameters throws the error.
# returning to avoid further execution when different values are specified for -ErrorAction parameter
return
}
if($Name)
{
if(($Name.Count -eq 1) -and ($Name -eq $script:PSGetModuleName))
{
Update-PowerShellGetModule
return
}
foreach($moduleName in $Name)
{
$availableModules = Get-Module -ListAvailable $moduleName -Verbose:$false
if(-not $availableModules -and -not (Test-WildcardPattern -Name $moduleName))
{
$message = $LocalizedData.ModuleNotInstalledOnThiseMachine -f ($moduleName)
Write-Error -Message $message -ErrorId "ModuleNotInstalledOnThisMachine" -Category InvalidOperation -TargetObject $moduleName
continue
}
foreach($mod in $availableModules)
{
# Check if this module got installed with PSGet and user has required permissions
$PSGetItemInfoPath = Microsoft.PowerShell.Management\Join-Path $mod.ModuleBase $script:PSGetItemInfoFileName
if (Microsoft.PowerShell.Management\Test-path $PSGetItemInfoPath)
{
if(-not (Test-RunningAsElevated) -and $mod.ModuleBase.StartsWith($script:programFilesModulesPath, [System.StringComparison]::OrdinalIgnoreCase))
{
if(-not (Test-WildcardPattern -Name $moduleName))
{
$message = $LocalizedData.AdminPrivilegesRequiredForUpdate -f ($mod.Name, $mod.ModuleBase)
Write-Error -Message $message -ErrorId "AdminPrivilegesAreRequiredForUpdate" -Category InvalidOperation -TargetObject $moduleName
}
continue
}
$moduleBasesToUpdate += $mod.ModuleBase
}
else
{
if(-not (Test-WildcardPattern -Name $moduleName))
{
$message = $LocalizedData.ModuleNotInstalledUsingPowerShellGet -f ($mod.Name)
Write-Error -Message $message -ErrorId "ModuleNotInstalledUsingInstallModuleCmdlet" -Category InvalidOperation -TargetObject $moduleName
}
continue
}
}
}
}
else
{
$modulePaths = @()
$modulePaths += $script:MyDocumentsModulesPath
if((Test-RunningAsElevated))
{
$modulePaths += $script:programFilesModulesPath
}
foreach ($location in $modulePaths)
{
# find all modules installed using PSGet
$moduleBases = Microsoft.PowerShell.Management\Get-ChildItem $location -Recurse `
-Attributes Hidden -Filter $script:PSGetItemInfoFileName `
-ErrorAction SilentlyContinue `
-WarningAction SilentlyContinue `
| Microsoft.PowerShell.Core\Foreach-Object { $_.Directory }
foreach ($moduleBase in $moduleBases)
{
$PSGetItemInfoPath = Microsoft.PowerShell.Management\Join-Path $moduleBase.FullName $script:PSGetItemInfoFileName
# Check if this module got installed using PSGet, read its contents and compare with current version
if (Microsoft.PowerShell.Management\Test-Path $PSGetItemInfoPath)
{
$moduleBasesToUpdate += $moduleBase
}
}
}
}
$PSBoundParameters["Provider"] = $script:PSModuleProviderName
foreach($moduleBase in $moduleBasesToUpdate)
{
$PSGetItemInfoPath = Microsoft.PowerShell.Management\Join-Path $moduleBase $script:PSGetItemInfoFileName
$psgetItemInfo = Microsoft.PowerShell.Utility\Import-Clixml -Path $PSGetItemInfoPath
# Skip the module name if it is already tried in the current pipeline
if($moduleNamesInPipeline -contains $psgetItemInfo.Name)
{
continue
}
$moduleNamesInPipeline += $psgetItemInfo.Name
$message = $LocalizedData.CheckingForModuleUpdate -f ($psgetItemInfo.Name)
Write-Verbose -Message $message
$providerName = Get-ProviderName -PSCustomObject $psgetItemInfo
if(-not $providerName)
{
$providerName = $script:NuGetProviderName
}
$PSBoundParameters["Name"] = $psgetItemInfo.Name
$PSBoundParameters["Location"] = $psgetItemInfo.RepositorySourceLocation
Get-PSGalleryApiAvailability -Repository (Get-SourceName -Location $psgetItemInfo.RepositorySourceLocation)
$PSBoundParameters["PackageManagementProvider"] = $providerName
$PSBoundParameters["InstallUpdate"] = $true
if($moduleBase.ToString().StartsWith($script:MyDocumentsModulesPath, [System.StringComparison]::OrdinalIgnoreCase))
{
$PSBoundParameters["Scope"] = "CurrentUser"
}
$PSBoundParameters["MessageResolver"] = $script:PackageManagementUpdateModuleMessageResolverScriptBlock
$sid = PackageManagement\Install-Package @PSBoundParameters
}
}
}
function Uninstall-Module
{
<#
.ExternalHelp PSGet.psm1-help.xml
#>
[CmdletBinding(DefaultParameterSetName='NameParameterSet',
SupportsShouldProcess=$true,
HelpUri='http://go.microsoft.com/fwlink/?LinkId=526864')]
Param
(
[Parameter(ValueFromPipelineByPropertyName=$true,
Mandatory=$true,
Position=0,
ParameterSetName='NameParameterSet')]
[ValidateNotNullOrEmpty()]
[String[]]
$Name,
[Parameter(Mandatory=$true,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$true,
Position=0,
ParameterSetName='InputObject')]
[ValidateNotNull()]
[PSCustomObject[]]
$InputObject,
[Parameter(ValueFromPipelineByPropertyName=$true,
ParameterSetName='NameParameterSet')]
[ValidateNotNull()]
[Version]
$MinimumVersion,
[Parameter(ValueFromPipelineByPropertyName=$true,
ParameterSetName='NameParameterSet')]
[ValidateNotNull()]
[Version]
$RequiredVersion,
[Parameter(ValueFromPipelineByPropertyName=$true,
ParameterSetName='NameParameterSet')]
[ValidateNotNull()]
[Version]
$MaximumVersion,
[Parameter()]
[Switch]
$Force
)
Process
{
$PSBoundParameters["Provider"] = $script:PSModuleProviderName
$PSBoundParameters["MessageResolver"] = $script:PackageManagementUnInstallModuleMessageResolverScriptBlock
if($PSCmdlet.ParameterSetName -eq "InputObject")
{
$null = $PSBoundParameters.Remove("InputObject")
foreach($inputValue in $InputObject)
{
if (($inputValue.PSTypeNames -notcontains "Microsoft.PowerShell.Commands.PSGetModuleInfo") -and
($inputValue.PSTypeNames -notcontains "Deserialized.Microsoft.PowerShell.Commands.PSGetModuleInfo"))
{
ThrowError -ExceptionName "System.ArgumentException" `
-ExceptionMessage $LocalizedData.InvalidInputObjectValue `
-ErrorId "InvalidInputObjectValue" `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidArgument `
-ExceptionObject $inputValue
}
$PSBoundParameters["Name"] = $inputValue.Name
$PSBoundParameters["RequiredVersion"] = $inputValue.Version
$null = PackageManagement\Uninstall-Package @PSBoundParameters
}
}
else
{
$ValidationResult = Validate-VersionParameters -CallerPSCmdlet $PSCmdlet `
-Name $Name `
-MinimumVersion $MinimumVersion `
-MaximumVersion $MaximumVersion `
-RequiredVersion $RequiredVersion
if(-not $ValidationResult)
{
# Validate-VersionParameters throws the error.
# returning to avoid further execution when different values are specified for -ErrorAction parameter
return
}
$null = PackageManagement\Uninstall-Package @PSBoundParameters
}
}
}
function Get-InstalledModule
{
<#
.ExternalHelp PSGet.psm1-help.xml
#>
[CmdletBinding(HelpUri='http://go.microsoft.com/fwlink/?LinkId=526863')]
Param
(
[Parameter(ValueFromPipelineByPropertyName=$true,
Position=0)]
[ValidateNotNullOrEmpty()]
[String[]]
$Name,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[ValidateNotNull()]
[Version]
$MinimumVersion,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[ValidateNotNull()]
[Version]
$RequiredVersion,
[Parameter(ValueFromPipelineByPropertyName=$true)]
[ValidateNotNull()]
[Version]
$MaximumVersion
)
Process
{
$ValidationResult = Validate-VersionParameters -CallerPSCmdlet $PSCmdlet `
-Name $Name `
-MinimumVersion $MinimumVersion `
-MaximumVersion $MaximumVersion `
-RequiredVersion $RequiredVersion
if(-not $ValidationResult)
{
# Validate-VersionParameters throws the error.
# returning to avoid further execution when different values are specified for -ErrorAction parameter
return
}
$PSBoundParameters["Provider"] = $script:PSModuleProviderName
$PSBoundParameters["MessageResolver"] = $script:PackageManagementMessageResolverScriptBlock
PackageManagement\Get-Package @PSBoundParameters | Microsoft.PowerShell.Core\ForEach-Object {New-PSGetItemInfo -SoftwareIdenties $_}
}
}
function Register-PSRepository
{
<#
.ExternalHelp PSGet.psm1-help.xml
#>
[CmdletBinding(PositionalBinding=$false,
HelpUri='http://go.microsoft.com/fwlink/?LinkID=517129')]
Param
(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$Name,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[Uri]
$SourceLocation,
[Parameter()]
[ValidateNotNullOrEmpty()]
[Uri]
$PublishLocation,
[Parameter()]
[ValidateSet('Trusted','Untrusted')]
[string]
$InstallationPolicy = 'Untrusted',
[Parameter()]
[ValidateNotNullOrEmpty()]
[string]
$PackageManagementProvider
)
DynamicParam
{
if (Get-Variable -Name SourceLocation -ErrorAction SilentlyContinue)
{
Set-Variable -Name selctedProviderName -value $null -Scope 1
if(Get-Variable -Name PackageManagementProvider -ErrorAction SilentlyContinue)
{
$selctedProviderName = $PackageManagementProvider
$null = Get-DynamicParameters -Location $SourceLocation -PackageManagementProvider ([REF]$selctedProviderName)
}
else
{
$dynamicParameters = Get-DynamicParameters -Location $SourceLocation -PackageManagementProvider ([REF]$selctedProviderName)
Set-Variable -Name PackageManagementProvider -Value $selctedProviderName -Scope 1
$null = $dynamicParameters
}
}
}
Begin
{
Get-PSGalleryApiAvailability -Repository $Name
Install-NuGetClientBinaries
}
Process
{
if($InstallationPolicy -eq "Trusted")
{
$PSBoundParameters.Add("Trusted", $true)
}
$providerName = $null
if($PackageManagementProvider)
{
$providerName = $PackageManagementProvider
}
elseif($selctedProviderName)
{
$providerName = $selctedProviderName
}
else
{
$providerName = Get-PackageManagementProviderName -Location $SourceLocation
}
if($providerName)
{
$PSBoundParameters[$script:PackageManagementProviderParam] = $providerName
}
if($PublishLocation)
{
$PSBoundParameters[$script:PublishLocation] = Get-LocationString -LocationUri $PublishLocation
}
$PSBoundParameters["Provider"] = $script:PSModuleProviderName
$PSBoundParameters["Location"] = Get-LocationString -LocationUri $SourceLocation
$null = $PSBoundParameters.Remove("SourceLocation")
$null = $PSBoundParameters.Remove("InstallationPolicy")
$PSBoundParameters["MessageResolver"] = $script:PackageManagementMessageResolverScriptBlock
$null = PackageManagement\Register-PackageSource @PSBoundParameters
}
}
function Set-PSRepository
{
<#
.ExternalHelp PSGet.psm1-help.xml
#>
[CmdletBinding(PositionalBinding=$false, SupportsShouldProcess=$true,
HelpUri='http://go.microsoft.com/fwlink/?LinkID=517128')]
Param
(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$Name,
[Parameter()]
[ValidateNotNullOrEmpty()]
[Uri]
$SourceLocation,
[Parameter()]
[ValidateNotNullOrEmpty()]
[Uri]
$PublishLocation,
[Parameter()]
[ValidateSet('Trusted','Untrusted')]
[string]
$InstallationPolicy,
[Parameter()]
[ValidateNotNullOrEmpty()]
[string]
$PackageManagementProvider
)
DynamicParam
{
if (Get-Variable -Name Name -ErrorAction SilentlyContinue)
{
$moduleSource = Get-PSRepository -Name $Name -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
if($moduleSource)
{
$providerName = (Get-ProviderName -PSCustomObject $moduleSource)
$loc = $moduleSource.SourceLocation
if(Get-Variable -Name SourceLocation -ErrorAction SilentlyContinue)
{
$loc = $SourceLocation
}
if(Get-Variable -Name PackageManagementProvider -ErrorAction SilentlyContinue)
{
$providerName = $PackageManagementProvider
}
$null = Get-DynamicParameters -Location $loc -PackageManagementProvider ([REF]$providerName)
}
}
}
Begin
{
Get-PSGalleryApiAvailability -Repository $Name
Install-NuGetClientBinaries
}
Process
{
$ModuleSource = Get-PSRepository -Name $Name -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
if(-not $ModuleSource)
{
$message = $LocalizedData.RepositoryNotFound -f ($Name)
ThrowError -ExceptionName "System.InvalidOperationException" `
-ExceptionMessage $message `
-ErrorId "RepositoryNotFound" `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidOperation `
-ExceptionObject $Name
}
if (-not $PackageManagementProvider)
{
$PackageManagementProvider = (Get-ProviderName -PSCustomObject $ModuleSource)
}
$Trusted = $ModuleSource.Trusted
if($InstallationPolicy)
{
if($InstallationPolicy -eq "Trusted")
{
$Trusted = $true
}
else
{
$Trusted = $false
}
$null = $PSBoundParameters.Remove("InstallationPolicy")
}
if($PublishLocation)
{
$PSBoundParameters[$script:PublishLocation] = Get-LocationString -LocationUri $PublishLocation
}
if($SourceLocation)
{
$PSBoundParameters["NewLocation"] = Get-LocationString -LocationUri $SourceLocation
$null = $PSBoundParameters.Remove("SourceLocation")
}
$PSBoundParameters[$script:PackageManagementProviderParam] = $PackageManagementProvider
$PSBoundParameters.Add("Trusted", $Trusted)
$PSBoundParameters["Provider"] = $script:PSModuleProviderName
$PSBoundParameters["MessageResolver"] = $script:PackageManagementMessageResolverScriptBlock
$null = PackageManagement\Set-PackageSource @PSBoundParameters
}
}
function Unregister-PSRepository
{
<#
.ExternalHelp PSGet.psm1-help.xml
#>
[CmdletBinding(HelpUri='http://go.microsoft.com/fwlink/?LinkID=517130')]
Param
(
[Parameter(ValueFromPipelineByPropertyName=$true,
Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string[]]
$Name
)
Begin
{
Get-PSGalleryApiAvailability -Repository $Name
}
Process
{
$PSBoundParameters["Provider"] = $script:PSModuleProviderName
$PSBoundParameters["MessageResolver"] = $script:PackageManagementMessageResolverScriptBlock
$null = $PSBoundParameters.Remove("Name")
foreach ($moduleSourceName in $Name)
{
# Check if $moduleSourceName contains any wildcards
if(Test-WildcardPattern $moduleSourceName)
{
$message = $LocalizedData.RepositoryNameContainsWildCards -f ($moduleSourceName)
Write-Error -Message $message -ErrorId "RepositoryNameContainsWildCards" -Category InvalidOperation
continue
}
$PSBoundParameters["Source"] = $moduleSourceName
$null = PackageManagement\Unregister-PackageSource @PSBoundParameters
}
}
}
function Get-PSRepository
{
<#
.ExternalHelp PSGet.psm1-help.xml
#>
[CmdletBinding(HelpUri='http://go.microsoft.com/fwlink/?LinkID=517127')]
Param
(
[Parameter(ValueFromPipelineByPropertyName=$true)]
[ValidateNotNullOrEmpty()]
[string[]]
$Name
)
Begin
{
Get-PSGalleryApiAvailability -Repository $Name
}
Process
{
$PSBoundParameters["Provider"] = $script:PSModuleProviderName
$PSBoundParameters["MessageResolver"] = $script:PackageManagementMessageResolverScriptBlock
if($Name)
{
foreach($sourceName in $Name)
{
$PSBoundParameters["Name"] = $sourceName
$packageSources = PackageManagement\Get-PackageSource @PSBoundParameters
$packageSources | Microsoft.PowerShell.Core\ForEach-Object { New-ModuleSourceFromPackageSource -PackageSource $_ }
}
}
else
{
$packageSources = PackageManagement\Get-PackageSource @PSBoundParameters
$packageSources | Microsoft.PowerShell.Core\ForEach-Object { New-ModuleSourceFromPackageSource -PackageSource $_ }
}
}
}
#region Utility functions
function Resolve-PathHelper
{
param
(
[Parameter()]
[ValidateNotNullOrEmpty()]
[string[]]
$path,
[Parameter()]
[switch]
$isLiteralPath,
[Parameter()]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.PSCmdlet]
$callerPSCmdlet
)
$resolvedPaths =@()
foreach($currentPath in $path)
{
try
{
if($isLiteralPath)
{
$currentResolvedPaths = Microsoft.PowerShell.Management\Resolve-Path -LiteralPath $currentPath -ErrorAction Stop
}
else
{
$currentResolvedPaths = Microsoft.PowerShell.Management\Resolve-Path -Path $currentPath -ErrorAction Stop
}
}
catch
{
$errorMessage = ($LocalizedData.PathNotFound -f $currentPath)
ThrowError -ExceptionName "System.InvalidOperationException" `
-ExceptionMessage $errorMessage `
-ErrorId "PathNotFound" `
-CallerPSCmdlet $callerPSCmdlet `
-ErrorCategory InvalidOperation
}
foreach($currentResolvedPath in $currentResolvedPaths)
{
$resolvedPaths += $currentResolvedPath.ProviderPath
}
}
$resolvedPaths
}
function Check-PSGalleryApiAvailability
{
param
(
[Parameter()]
[ValidateNotNullOrEmpty()]
[string[]]
$PSGalleryV2ApiUri,
[Parameter()]
[ValidateNotNullOrEmpty()]
[string[]]
$PSGalleryV3ApiUri
)
# check internet availability first
$connected = Microsoft.PowerShell.Management\Test-Connection -ComputerName "www.microsoft.com" -Count 1 -Quiet
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
}
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
}
function Ping-Endpoint
{
param
(
[Parameter()]
[ValidateNotNullOrEmpty()]
[string[]]
$Endpoint
)
$results = @{}
$iss = [System.Management.Automation.Runspaces.InitialSessionState]::Create()
$iss.types.clear()
$iss.formats.clear()
$iss.LanguageMode = "FullLanguage"
$cmd = @'
try
{{
$request = [System.Net.WebRequest]::Create("{0}")
$request.Method = 'GET'
$request.Timeout = 30000
$response = [System.Net.HttpWebResponse]$request.GetResponse()
$response
$response.Close()
}}
catch [System.Net.WebException]
{{
"Error:System.Net.WebException"
}}
'@ -f $EndPoint
$ps = [powershell]::Create($iss).AddScript($cmd)
$response = $ps.Invoke()
$ps.dispose()
if ($response -ne "Error:System.Net.WebException")
{
$results.Add($Script:ResponseUri,$response.ResponseUri.ToString())
$results.Add($Script:StatusCode,$response.StatusCode.value__)
}
return $results
}
function Validate-VersionParameters
{
Param(
[parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.PSCmdlet]
$CallerPSCmdlet,
[Parameter()]
[String[]]
$Name,
[Parameter()]
[Version]
$MinimumVersion,
[Parameter()]
[Version]
$RequiredVersion,
[Parameter()]
[Version]
$MaximumVersion
)
if($RequiredVersion -and ($MinimumVersion -or $MaximumVersion))
{
ThrowError -ExceptionName "System.ArgumentException" `
-ExceptionMessage $LocalizedData.VersionRangeAndRequiredVersionCannotBeSpecifiedTogether `
-ErrorId "VersionRangeAndRequiredVersionCannotBeSpecifiedTogether" `
-CallerPSCmdlet $CallerPSCmdlet `
-ErrorCategory InvalidArgument
}
if($RequiredVersion -or $MinimumVersion -or $MaximumVersion)
{
if(-not $Name -or $Name.Count -ne 1 -or (Test-WildcardPattern -Name $Name[0]))
{
ThrowError -ExceptionName "System.ArgumentException" `
-ExceptionMessage $LocalizedData.VersionParametersAreAllowedOnlyWithSingleModule `
-ErrorId "VersionParametersAreAllowedOnlyWithSingleModule" `
-CallerPSCmdlet $CallerPSCmdlet `
-ErrorCategory InvalidArgument
}
}
if($MinimumVersion -and $MaximumVersion -and ($MinimumVersion -gt $MaximumVersion))
{
$Message = $LocalizedData.MinimumVersionIsGreaterThanMaximumVersion -f ($MinimumVersion, $MaximumVersion)
ThrowError -ExceptionName "System.ArgumentException" `
-ExceptionMessage $Message `
-ErrorId "MinimumVersionIsGreaterThanMaximumVersion" `
-CallerPSCmdlet $CallerPSCmdlet `
-ErrorCategory InvalidArgument
}
return $true
}
function Set-ModuleSourcesVariable
{
param([switch]$Force)
if(-not $script:PSGetModuleSources -or $Force)
{
if(Microsoft.PowerShell.Management\Test-Path $script:PSGetModuleSourcesFilePath)
{
$script:PSGetModuleSources = Microsoft.PowerShell.Utility\Import-Clixml $script:PSGetModuleSourcesFilePath
}
else
{
$script:PSGetModuleSources = [ordered]@{}
}
if(-not $script:PSGetModuleSources.Contains($Script:PSGalleryModuleSource))
{
$psgalleryLocation = $null
try
{
$psgalleryLocation = Get-ValidModuleLocation -LocationString $Script:PSGallerySourceUri -ParameterName "Source" -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
}
catch
{
}
if($psgalleryLocation)
{
$moduleSource = Microsoft.PowerShell.Utility\New-Object PSCustomObject -Property ([ordered]@{
Name = $Script:PSGalleryModuleSource
SourceLocation = $psgalleryLocation
PublishLocation = $Script:PSGalleryPublishUri
Trusted=$false
Registered=$true
InstallationPolicy = 'Untrusted'
PackageManagementProvider=$script:NuGetProviderName
ProviderOptions = @{}
})
$moduleSource.PSTypeNames.Insert(0, "Microsoft.PowerShell.Commands.PSRepository")
$script:PSGetModuleSources.Add($Script:PSGalleryModuleSource, $moduleSource)
}
}
}
}
function Get-PackageManagementProviderName
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[Uri]
$Location
)
$PackageManagementProviderName = $null
$loc = Get-LocationString -LocationUri $Location
$providers = PackageManagement\Get-PackageProvider | Where-Object { $_.Features.ContainsKey($script:SupportsPSModulesFeatureName) }
foreach($provider in $providers)
{
# Skip the PSModule provider
if($provider.ProviderName -eq $script:PSModuleProviderName)
{
continue
}
$packageSource = Get-PackageSource -Location $loc -Provider $provider.ProviderName -ErrorAction SilentlyContinue
if($packageSource)
{
$PackageManagementProviderName = $provider.ProviderName
break
}
}
return $PackageManagementProviderName
}
function Get-ProviderName
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true)]
[PSCustomObject]
$PSCustomObject
)
$providerName = $script:NuGetProviderName
if((Get-Member -InputObject $PSCustomObject -Name PackageManagementProvider))
{
$providerName = $PSCustomObject.PackageManagementProvider
}
return $providerName
}
function Get-DynamicParameters
{
[CmdletBinding()]
Param
(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[Uri]
$Location,
[Parameter(Mandatory=$true)]
[REF]
$PackageManagementProvider
)
$paramDictionary = New-Object System.Management.Automation.RuntimeDefinedParameterDictionary
$dynamicOptions = $null
$loc = Get-LocationString -LocationUri $Location
$providers = PackageManagement\Get-PackageProvider | Where-Object { $_.Features.ContainsKey($script:SupportsPSModulesFeatureName) }
if ($PackageManagementProvider.Value)
{
# Skip the PSModule provider
if($PackageManagementProvider.Value -ne $script:PSModuleProviderName)
{
$SelectedProvider = $providers | Where-Object {$_.ProviderName -eq $PackageManagementProvider.Value}
if($SelectedProvider)
{
$res = Get-PackageSource -Location $loc -Provider $PackageManagementProvider.Value -ErrorAction SilentlyContinue
if($res)
{
$dynamicOptions = $SelectedProvider.DynamicOptions
}
}
}
}
else
{
$PackageManagementProvider.Value = Get-PackageManagementProviderName -Location $Location
if($PackageManagementProvider.Value)
{
$provider = $providers | Where-Object {$_.ProviderName -eq $PackageManagementProvider.Value}
$dynamicOptions = $provider.DynamicOptions
}
}
foreach ($option in $dynamicOptions)
{
# Skip the Destination parameter
if( $option.IsRequired -and
($option.Name -eq "Destination") )
{
continue
}
$paramAttribute = New-Object System.Management.Automation.ParameterAttribute
$paramAttribute.Mandatory = $option.IsRequired
$message = $LocalizedData.DynamicParameterHelpMessage -f ($option.Name, $PackageManagementProvider.Value, $loc, $option.Name)
$paramAttribute.HelpMessage = $message
$attributeCollection = new-object System.Collections.ObjectModel.Collection[System.Attribute]
$attributeCollection.Add($paramAttribute)
$ageParam = New-Object System.Management.Automation.RuntimeDefinedParameter($option.Name,
$script:DynamicOptionTypeMap[$option.Type.value__],
$attributeCollection)
$paramDictionary.Add($option.Name, $ageParam)
}
return $paramDictionary
}
function New-PSGetItemInfo
{
param
(
[Parameter(Mandatory=$true)]
$SoftwareIdenties,
[Parameter()]
$PackageManagementProviderName
)
foreach($swid in $SoftwareIdenties)
{
$sourceName = (Get-First $swid.Metadata["SourceName"])
if(-not $sourceName)
{
$sourceName = (Get-SourceName -Location $swid.Source)
}
$published = (Get-First $swid.Metadata["published"])
$PublishedDate = New-Object System.DateTime
$tags = (Get-First $swid.Metadata["tags"]) -split " "
$userTags = @()
$exportedDscResources = @()
$exportedCommands = @()
$exportedCmdlets = @()
$exportedFunctions = @()
$PSGetFormatVersion = $null
ForEach($tag in $tags)
{
$parts = $tag -split "_",2
if($parts.Count -ne 2)
{
$userTags += $tag
continue
}
Switch($parts[0])
{
$script:Command { $exportedCommands += $parts[1]; break }
$script:DscResource { $exportedDscResources += $parts[1]; break }
$script:Cmdlet { $exportedCmdlets += $parts[1]; break }
$script:Function { $exportedFunctions += $parts[1]; break }
$script:PSGetFormatVersion { $PSGetFormatVersion = $parts[1]; break }
Default { $userTags += $tag; break }
}
}
$ModuleDependencies = @()
Foreach ($dependencyString in $swid.Dependencies)
{
[Uri]$packageId = $null
if([Uri]::TryCreate($dependencyString, [System.UriKind]::Absolute, ([ref]$packageId)))
{
$segments = $packageId.Segments
$Version = $null
$ModuleName = $null
if ($segments)
{
$ModuleName = [Uri]::UnescapeDataString($segments[0].Trim('/', '\'))
$Version = if($segments.Count -gt 1){[Uri]::UnescapeDataString($segments[1])}
}
$dep = [ordered]@{
ModuleName=$ModuleName
}
if($Version)
{
# Required/exact version is represented in NuGet as "[2.0]"
if ($Version -match "\[+[0-9.]+\]")
{
$dep["RequiredVersion"] = $Version.Trim('[', ']')
}
else
{
$dep["ModuleVersion"] = $Version
}
}
$dep["CanonicalId"]=$dependencyString
$ModuleDependencies += $dep
}
}
$PSGetItemInfo = Microsoft.PowerShell.Utility\New-Object PSCustomObject -Property ([ordered]@{
Name = $swid.Name
Version = [Version]$swid.Version
Description = (Get-First $swid.Metadata["description"])
Author = (Get-EntityName -SoftwareIdentity $swid -Role "author")
CompanyName = (Get-EntityName -SoftwareIdentity $swid -Role "owner")
Copyright = (Get-First $swid.Metadata["copyright"])
PublishedDate = if([System.DateTime]::TryParse($published, ([ref]$PublishedDate))){$PublishedDate};
LicenseUri = (Get-UrlFromSwid -SoftwareIdentity $swid -UrlName "license")
ProjectUri = (Get-UrlFromSwid -SoftwareIdentity $swid -UrlName "project")
IconUri = (Get-UrlFromSwid -SoftwareIdentity $swid -UrlName "icon")
Tags = $userTags
Includes = @{
DscResource = $exportedDscResources
Command = $exportedCommands
Cmdlet = $exportedCmdlets
Function = $exportedFunctions
}
PowerShellGetFormatVersion=[Version]$PSGetFormatVersion
ReleaseNotes = (Get-First $swid.Metadata["releaseNotes"])
Dependencies = $ModuleDependencies
RepositorySourceLocation = $swid.Source
Repository = if($sourceName) { $sourceName } else { $swid.Source }
PackageManagementProvider = if($PackageManagementProviderName) { $PackageManagementProviderName } else { (Get-First $swid.Metadata["PackageManagementProvider"]) }
})
$PSGetItemInfo.PSTypeNames.Insert(0, "Microsoft.PowerShell.Commands.PSGetModuleInfo")
$PSGetItemInfo
}
}
function Get-SourceName
{
[CmdletBinding()]
[OutputType("string")]
Param
(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$Location
)
Set-ModuleSourcesVariable
foreach($psModuleSource in $script:PSGetModuleSources.Values)
{
if($psModuleSource.SourceLocation -eq $Location)
{
return $psModuleSource.Name
}
}
}
function Get-UrlFromSwid
{
param
(
[Parameter(Mandatory=$true)]
$SoftwareIdentity,
[Parameter(Mandatory=$true)]
$UrlName
)
foreach($link in $SoftwareIdentity.Links)
{
if( $link.Relationship -eq $UrlName)
{
return $link.HRef
}
}
return $null
}
function Get-EntityName
{
param
(
[Parameter(Mandatory=$true)]
$SoftwareIdentity,
[Parameter(Mandatory=$true)]
$Role
)
foreach( $entity in $SoftwareIdentity.Entities )
{
if( $entity.Role -eq $Role)
{
$entity.Name
}
}
}
function Install-NuGetClientBinaries
{
[CmdletBinding(SupportsShouldProcess=$true)]
param()
if($script:NuGetClient -and (Microsoft.PowerShell.Management\Test-Path $script:NuGetClient))
{
return
}
# Bootstrap NuGet provider if it is not available
$nugetProvider = PackageManagement\Get-PackageProvider -ErrorAction SilentlyContinue -WarningAction SilentlyContinue | Microsoft.PowerShell.Core\Where-Object {$_.Name -eq "NuGet"}
if($nugetProvider -and
$nugetProvider.Features.Exe -and
(Microsoft.PowerShell.Management\Test-Path $nugetProvider.Features.Exe))
{
$script:NuGetClient = $nugetProvider.Features.Exe
}
else
{
$ShouldContinueQueryMessage = $LocalizedData.InstallNuGetBinariesShouldContinueQuery -f @($script:NuGetBinaryProgramDataPath,$script:NuGetBinaryLocalAppDataPath)
if($PSCmdlet.ShouldProcess($ShouldContinueQueryMessage, $LocalizedData.InstallNuGetBinariesShouldContinueCaption))
{
Write-Verbose -Message $LocalizedData.DownloadingNugetBinaries
# Bootstrap the NuGet provider
$nugetProvider = PackageManagement\Get-PackageProvider -Name NuGet -Force
if($nugetProvider -and
$nugetProvider.Features.Exe -and
(Microsoft.PowerShell.Management\Test-Path $nugetProvider.Features.Exe))
{
$script:NuGetClient = $nugetProvider.Features.Exe
}
}
}
if(-not $script:NuGetClient -or
-not (Microsoft.PowerShell.Management\Test-Path $script:NuGetClient))
{
$message = $LocalizedData.CouldNotInstallNuGetBinaries -f @($script:NuGetBinaryProgramDataPath,$script:NuGetBinaryLocalAppDataPath)
ThrowError -ExceptionName "System.InvalidOperationException" `
-ExceptionMessage $message `
-ErrorId "CouldNotInstallNuGetBinaries" `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidOperation
}
}
# Check if current user is running with elevated privileges
function Test-RunningAsElevated
{
[CmdletBinding()]
[OutputType([bool])]
Param()
$wid=[System.Security.Principal.WindowsIdentity]::GetCurrent()
$prp=new-object System.Security.Principal.WindowsPrincipal($wid)
$adm=[System.Security.Principal.WindowsBuiltInRole]::Administrator
return $prp.IsInRole($adm)
}
function Get-EscapedString
{
[CmdletBinding()]
[OutputType([String])]
Param
(
[Parameter()]
[string]
$ElementValue
)
return [System.Security.SecurityElement]::Escape($ElementValue)
}
function ValidateAndGet-RequiredModuleDetails
{
param(
[Parameter()]
$ModuleManifestRequiredModules,
[Parameter()]
[PSModuleInfo[]]
$RequiredPSModuleInfos,
[Parameter(Mandatory=$true)]
[string]
$Repository,
[Parameter(Mandatory=$true)]
[PSModuleInfo]
$DependentModuleInfo,
[parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.PSCmdlet]
$CallerPSCmdlet
)
$RequiredModuleDetails = @()
if(-not $RequiredPSModuleInfos)
{
return $RequiredModuleDetails
}
if($ModuleManifestRequiredModules)
{
ForEach($RequiredModule in $ModuleManifestRequiredModules)
{
$ModuleName = $null
$VersionString = $null
$ReqModuleInfo = @{}
$FindModuleArguments = @{
Repository = $Repository
Verbose = $VerbosePreference
ErrorAction = 'SilentlyContinue'
WarningAction = 'SilentlyContinue'
Debug = $DebugPreference
}
# ModuleSpecification case
if($RequiredModule.GetType().ToString() -eq 'System.Collections.Hashtable')
{
$ModuleName = $RequiredModule.ModuleName
# Version format in NuSpec:
# "[2.0]" --> (== 2.0) Required Version
# "2.0" --> (>= 2.0) Minimum Version
if($RequiredModule.Keys -Contains "RequiredVersion")
{
$FindModuleArguments['RequiredVersion'] = $RequiredModule.RequiredVersion
$ReqModuleInfo['RequiredVersion'] = $RequiredModule.RequiredVersion
}
elseif($RequiredModule.Keys -Contains "ModuleVersion")
{
$FindModuleArguments['MinimumVersion'] = $RequiredModule.ModuleVersion
$ReqModuleInfo['MinimumVersion'] = $RequiredModule.ModuleVersion
}
}
else
{
# Just module name was specified
$ModuleName = $RequiredModule.ToString()
}
if((Get-ExternalModuleDependencies -PSModuleInfo $DependentModuleInfo) -contains $ModuleName)
{
Write-Verbose -Message ($LocalizedData.SkippedModuleDependency -f $ModuleName)
continue
}
# Skip this module name if it's name is not in $RequiredPSModuleInfos.
# This is required when a ModuleName is part of the NestedModules list of the actual module.
# $ModuleName is packaged as part of the actual module When $RequiredPSModuleInfos doesn't contain it's name.
if($RequiredPSModuleInfos.Name -notcontains $ModuleName)
{
continue
}
$ReqModuleInfo['Name'] = $ModuleName
# Add the dependency only if the module is available on the gallery
# Otherwise Module installation will fail as all required modules need to be available on
# the same Repository
$FindModuleArguments['Name'] = $ModuleName
$psgetItemInfo = Find-Module @FindModuleArguments |
Microsoft.PowerShell.Core\Where-Object {$_.Name -eq $ModuleName} |
Microsoft.PowerShell.Utility\Select-Object -Last 1
if(-not $psgetItemInfo)
{
$message = $LocalizedData.UnableToResolveModuleDependency -f ($ModuleName, $DependentModuleInfo.Name, $Repository, $ModuleName, $Repository, $ModuleName, $ModuleName)
ThrowError -ExceptionName "System.InvalidOperationException" `
-ExceptionMessage $message `
-ErrorId "UnableToResolveModuleDependency" `
-CallerPSCmdlet $CallerPSCmdlet `
-ErrorCategory InvalidOperation
}
$RequiredModuleDetails += $ReqModuleInfo
}
}
else
{
# If Import-LocalizedData cmdlet was failed to read the .psd1 contents
# use provided $RequiredPSModuleInfos (PSModuleInfo.RequiredModules or PSModuleInfo.NestedModules of the actual dependent module)
$FindModuleArguments = @{
Repository = $Repository
Verbose = $VerbosePreference
ErrorAction = 'SilentlyContinue'
WarningAction = 'SilentlyContinue'
Debug = $DebugPreference
}
ForEach($RequiredModuleInfo in $RequiredPSModuleInfos)
{
$ModuleName = $requiredModuleInfo.Name
if((Get-ExternalModuleDependencies -PSModuleInfo $DependentModuleInfo) -contains $ModuleName)
{
Write-Verbose -Message ($LocalizedData.SkippedModuleDependency -f $ModuleName)
continue
}
$FindModuleArguments['Name'] = $ModuleName
$FindModuleArguments['MinimumVersion'] = $requiredModuleInfo.Version
$psgetItemInfo = Find-Module @FindModuleArguments |
Microsoft.PowerShell.Core\Where-Object {$_.Name -eq $ModuleName} |
Microsoft.PowerShell.Utility\Select-Object -Last 1
if(-not $psgetItemInfo)
{
$message = $LocalizedData.UnableToResolveModuleDependency -f ($ModuleName, $DependentModuleInfo.Name, $Repository, $ModuleName, $Repository, $ModuleName, $ModuleName)
ThrowError -ExceptionName "System.InvalidOperationException" `
-ExceptionMessage $message `
-ErrorId "UnableToResolveModuleDependency" `
-CallerPSCmdlet $PSCmdlet `
-ErrorCategory InvalidOperation
}
$RequiredModuleDetails += @{
Name=$_.Name
MinimumVersion=$_.Version
}
}
}
return $RequiredModuleDetails
}
function Get-ExternalModuleDependencies
{
Param (
[Parameter(Mandatory=$true)]
[PSModuleInfo]
$PSModuleInfo
)
if($PSModuleInfo.PrivateData -and
($PSModuleInfo.PrivateData.GetType().ToString() -eq "System.Collections.Hashtable") -and
$PSModuleInfo.PrivateData["PSData"] -and
($PSModuleInfo.PrivateData["PSData"].GetType().ToString() -eq "System.Collections.Hashtable") -and
$PSModuleInfo.PrivateData.PSData['ExternalModuleDependencies'] -and
($PSModuleInfo.PrivateData.PSData['ExternalModuleDependencies'].GetType().ToString() -eq "System.Object[]")
)
{
return $PSModuleInfo.PrivateData.PSData.ExternalModuleDependencies
}
}
function Get-ModuleDependencies
{
Param (
[Parameter(Mandatory=$true)]
[PSModuleInfo]
$PSModuleInfo,
[Parameter(Mandatory=$true)]
[string]
$Repository,
[parameter(Mandatory = $true)]
[ValidateNotNullOrEmpty()]
[System.Management.Automation.PSCmdlet]
$CallerPSCmdlet
)
$DependentModuleDetails = @()
if($PSModuleInfo.RequiredModules -or $PSModuleInfo.NestedModules)
{
# PSModuleInfo.RequiredModules doesn't provide the RequiredVersion info from the ModuleSpecification
# Reading the contents of module manifest file using Import-LocalizedData cmdlet
# to get the RequiredVersion details.
Import-LocalizedData -BindingVariable ModuleManifestHashTable `
-FileName (Microsoft.PowerShell.Management\Split-Path $PSModuleInfo.Path -Leaf) `
-BaseDirectory $PSModuleInfo.ModuleBase `
-ErrorAction SilentlyContinue `
-WarningAction SilentlyContinue
if($PSModuleInfo.RequiredModules)
{
$ModuleManifestRequiredModules = $null
if($ModuleManifestHashTable)
{
$ModuleManifestRequiredModules = $ModuleManifestHashTable.RequiredModules
}
$DependentModuleDetails += ValidateAndGet-RequiredModuleDetails -ModuleManifestRequiredModules $ModuleManifestRequiredModules `
-RequiredPSModuleInfos $PSModuleInfo.RequiredModules `
-Repository $Repository `
-DependentModuleInfo $PSModuleInfo `
-CallerPSCmdlet $CallerPSCmdlet `
-Verbose:$VerbosePreference `
-Debug:$DebugPreference
}
if($PSModuleInfo.NestedModules)
{
$ModuleManifestRequiredModules = $null
if($ModuleManifestHashTable)
{
$ModuleManifestRequiredModules = $ModuleManifestHashTable.NestedModules
}
# A nested module is a required module if it's ModuleBase is not starting with the current module's ModuleBase.
$RequiredPSModuleInfos = $PSModuleInfo.NestedModules | Microsoft.PowerShell.Core\Where-Object {-not $_.ModuleBase.StartsWith($PSModuleInfo.ModuleBase, [System.StringComparison]::OrdinalIgnoreCase)}
$DependentModuleDetails += ValidateAndGet-RequiredModuleDetails -ModuleManifestRequiredModules $ModuleManifestRequiredModules `
-RequiredPSModuleInfos $RequiredPSModuleInfos `
-Repository $Repository `
-DependentModuleInfo $PSModuleInfo `
-CallerPSCmdlet $CallerPSCmdlet `
-Verbose:$VerbosePreference `
-Debug:$DebugPreference
}
}
return $DependentModuleDetails
}
function Publish-PSGetExtModule
{
[CmdletBinding(PositionalBinding=$false)]
Param
(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[PSModuleInfo]
$PSModuleInfo,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$Destination,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$Repository,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$NugetApiKey,
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[string]
$NugetPackageRoot,
[Parameter()]
[Version]
$FormatVersion,
[Parameter()]
[string]
$ReleaseNotes,
[Parameter()]
[string[]]
$Tags,
[Parameter()]
[Uri]
$LicenseUri,
[Parameter()]
[Uri]
$IconUri,
[Parameter()]
[Uri]
$ProjectUri
)
if(-not (Microsoft.PowerShell.Management\Test-Path $script:NuGetClient))
{
Install-NuGetClientBinaries
}
if($PSModuleInfo.PrivateData -and
($PSModuleInfo.PrivateData.GetType().ToString() -eq "System.Collections.Hashtable") -and
$PSModuleInfo.PrivateData["PSData"] -and
($PSModuleInfo.PrivateData["PSData"].GetType().ToString() -eq "System.Collections.Hashtable")
)
{
if( -not $Tags -and $PSModuleInfo.PrivateData.PSData["Tags"])
{
$Tags = $PSModuleInfo.PrivateData.PSData.Tags
}
if( -not $ReleaseNotes -and $PSModuleInfo.PrivateData.PSData["ReleaseNotes"])
{
$ReleaseNotes = $PSModuleInfo.PrivateData.PSData.ReleaseNotes
}
if( -not $LicenseUri -and $PSModuleInfo.PrivateData.PSData["LicenseUri"])
{
$LicenseUri = $PSModuleInfo.PrivateData.PSData.LicenseUri
}
if( -not $IconUri -and $PSModuleInfo.PrivateData.PSData["IconUri"])
{
$IconUri = $PSModuleInfo.PrivateData.PSData.IconUri
}
if( -not $ProjectUri -and $PSModuleInfo.PrivateData.PSData["ProjectUri"])
{
$ProjectUri = $PSModuleInfo.PrivateData.PSData.ProjectUri
}
}
# Add PSModule and PSGet format version tags
if(-not $Tags)
{
$Tags = @()
}
if($FormatVersion)
{
$Tags += "$($script:PSGetFormatVersion)_$FormatVersion"
}
$Tags += "PSModule"
if($PSModuleInfo.ExportedCommands.Count)
{
if($PSModuleInfo.ExportedCmdlets.Count)
{
$Tags += "$($script:Includes)_Cmdlet"
$Tags += $PSModuleInfo.ExportedCmdlets.Keys | Microsoft.PowerShell.Core\ForEach-Object { "$($script:Cmdlet)_$_" }
}
if($PSModuleInfo.ExportedFunctions.Count)
{
$Tags += "$($script:Includes)_Function"
$Tags += $PSModuleInfo.ExportedFunctions.Keys | Microsoft.PowerShell.Core\ForEach-Object { "$($script:Function)_$_" }
}
$Tags += $PSModuleInfo.ExportedCommands.Keys | Microsoft.PowerShell.Core\ForEach-Object { "$($script:Command)_$_" }
}
$dscResourceNames = Get-ExportedDscResources -PSModuleInfo $PSModuleInfo
if($dscResourceNames)
{
$Tags += "$($script:Includes)_DscResource"
$Tags += $dscResourceNames | Microsoft.PowerShell.Core\ForEach-Object { "$($script:DscResource)_$_" }
}
# Populate the module dependencies elements from RequiredModules and
# NestedModules properties of the current PSModuleInfo
$DependentModuleDetails = Get-ModuleDependencies -PSModuleInfo $PSModuleInfo `
-Repository $Repository `
-CallerPSCmdlet $PSCmdlet `
-Verbose:$VerbosePreference `
-Debug:$DebugPreference
$dependencies = @()
ForEach($Dependency in $DependentModuleDetails)
{
$ModuleName = $Dependency.Name
$VersionString = $null
# Version format in NuSpec:
# "[2.0]" --> (== 2.0) Required Version
# "2.0" --> (>= 2.0) Minimum Version
if($Dependency.Keys -Contains "RequiredVersion")
{
$VersionString = "[$($Dependency.RequiredVersion)]"
}
elseif($Dependency.Keys -Contains "MinimumVersion")
{
$VersionString = "$($Dependency.MinimumVersion)"
}
$dependencies += "<dependency id='$($ModuleName)' version='$($VersionString)' />"
}
# Populate the nuspec elements
$nuspec = @"
<?xml version="1.0"?>
<package >
<metadata>
<id>$(Get-EscapedString -ElementValue $PSModuleInfo.Name)</id>
<version>$($PSModuleInfo.Version)</version>
<authors>$(Get-EscapedString -ElementValue $PSModuleInfo.Author)</authors>
<owners>$(Get-EscapedString -ElementValue $PSModuleInfo.CompanyName)</owners>
<description>$(Get-EscapedString -ElementValue $PSModuleInfo.Description)</description>
<releaseNotes>$(Get-EscapedString -ElementValue $ReleaseNotes)</releaseNotes>
<copyright>$(Get-EscapedString -ElementValue $PSModuleInfo.Copyright)</copyright>
<tags>$(if($Tags){ Get-EscapedString -ElementValue ($Tags -join ' ')})</tags>
$(if($LicenseUri){
"<licenseUrl>$(Get-EscapedString -ElementValue $LicenseUri)</licenseUrl>
<requireLicenseAcceptance>true</requireLicenseAcceptance>"
})
$(if($ProjectUri){
"<projectUrl>$(Get-EscapedString -ElementValue $ProjectUri)</projectUrl>"
})
$(if($IconUri){
"<iconUrl>$(Get-EscapedString -ElementValue $IconUri)</iconUrl>"
})
<dependencies>
$dependencies
</dependencies>
</metadata>
</package>
"@
try
{
$NupkgPath = "$NugetPackageRoot\$($PSModuleInfo.Name).$($PSModuleInfo.Version.ToString()).nupkg"
$NuspecPath = "$NugetPackageRoot\$($PSModuleInfo.Name).nuspec"
# Remove existing nuspec and nupkg files
Microsoft.PowerShell.Management\Remove-Item $NupkgPath -Force -ErrorAction SilentlyContinue -WarningAction SilentlyContinue -Confirm:$false -WhatIf:$false
Microsoft.PowerShell.Management\Remove-Item $NuspecPath -Force -ErrorAction SilentlyContinue -WarningAction SilentlyContinue -Confirm:$false -WhatIf:$false
Microsoft.PowerShell.Management\Set-Content -Value $nuspec -Path $NuspecPath
# Create .nupkg file
$output = & $script:NuGetClient pack $NuspecPath -OutputDirectory $NugetPackageRoot
if($LASTEXITCODE)
{
$message = $LocalizedData.FailedToCreateCompressedModule -f ($output)
Write-Error -Message $message -ErrorId "FailedToCreateCompressedModule" -Category InvalidOperation
return
}
# Publish the .nupkg to gallery
$output = & $script:NuGetClient push $NupkgPath -source $Destination -NonInteractive -ApiKey $NugetApiKey
if($LASTEXITCODE)
{
$message = $LocalizedData.FailedToPublish -f ($output)
Write-Error -Message $message -ErrorId "FailedToPublishTheModule" -Category InvalidOperation
}
else
{
$message = $LocalizedData.PublishedSuccessfully -f ($PSModuleInfo.Name, $Destination, $PSModuleInfo.Name)
Write-Verbose -Message $message
}
}
finally
{
Microsoft.PowerShell.Management\Remove-Item $NupkgPath -Force -ErrorAction SilentlyContinue -WarningAction SilentlyContinue -Confirm:$false -WhatIf:$false
Microsoft.PowerShell.Management\Remove-Item $NuspecPath -Force -ErrorAction SilentlyContinue -WarningAction SilentlyContinue -Confirm:$false -WhatIf:$false
}
}
function Get-ExportedDscResources
{
[CmdletBinding(PositionalBinding=$false)]
Param
(
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[PSModuleInfo]
$PSModuleInfo
)
$dscResources = @()
if(Get-Command -Name Get-DscResource -Module PSDesiredStateConfiguration -ErrorAction SilentlyContinue)
{
$OldPSModulePath = $env:PSModulePath