From 119e762f6ee5dd0fea37a0b12b813cfe496c28c2 Mon Sep 17 00:00:00 2001 From: Paul Higinbotham Date: Wed, 27 Jul 2022 17:12:37 -0700 Subject: [PATCH 1/8] parent c966cd85c4265c149ee70cf69613dce129fceca9 author Paul Higinbotham 1658967157 -0700 committer Amber Erickson 1660524892 -0700 Remove unneeded copy (#736) Add error message for failure to install after choosing not to trust repository (#712) Remove ShouldProcess from FindPSResource (#710) Add OutputType attributes to Get-PSResource and Get-PSResourceRepository (#706) Add PSModulePath paths when retrieving resource paths (#700) Remove .nupkg.metadata file (#738) Change "IncludeXML" to "IncludeXml" (#739) Cannot assume PSScriptInfo metadata will have empty lines in between (#744) * for PSScriptInfo metadata not assume first line will be empty line and can be ignored * add test scripts without empty lines Change default path to CurrentFileSystemLocation (#742) Change ConfirmImpact from Medium to Low Add ValueFromPipelineByPropertyName to Set-PSResourceRepository (#705) Editorial pass on cmdlet ref (#743) Update priority range for PSResourceRepository to 0-100 (#741) Add -Force param to Register-PSResourceRepository and Set-PSResourceRepository (#717) Allow publishing of module directories, .psd1, and .ps1 Add tests Update src/code/PublishPSResource.cs Co-authored-by: Paul Higinbotham Update src/code/PublishPSResource.cs Co-authored-by: Paul Higinbotham Update src/code/PublishPSResource.cs Co-authored-by: Paul Higinbotham Update src/code/PublishPSResource.cs Co-authored-by: Paul Higinbotham Update src/code/PublishPSResource.cs Co-authored-by: Paul Higinbotham Refactor code based on code review suggestions Fix changes made from upstream merge Add method back removed from resolving merge conflict Add tests --- .ci/ci_release.yml | 7 - .gitignore | 2 + help/Find-PSResource.md | 313 +++++++----- help/Get-PSResource.md | 151 ++++-- help/Get-PSResourceRepository.md | 93 ++-- help/Install-PSResource.md | 465 +++++++++-------- help/New-PSScriptFileInfo.md | 260 +++++----- help/PowerShellGet.md | 48 +- help/Publish-PSResource.md | 118 +++-- help/Register-PSResourceRepository.md | 283 +++++++---- help/Save-PSResource.md | 243 +++++---- help/Set-PSResourceRepository.md | 240 ++++++--- help/Test-PSScriptFileInfo.md | 117 ++--- help/Uninstall-PSResource.md | 166 ++++-- help/Unregister-PSResourceRepository.md | 110 ++-- help/Update-ModuleManifest.md | 481 +++++++++++------- help/Update-PSResource.md | 238 +++++---- help/Update-PSScriptFileInfo.md | 212 ++++---- help/en-US/PowerShellGet.dll-Help.xml | 14 +- src/code/GetPSResource.cs | 1 + src/code/GetPSResourceRepository.cs | 1 + src/code/InstallHelper.cs | 22 +- src/code/InstallPSResource.cs | 2 +- src/code/PSRepositoryInfo.cs | 2 +- src/code/PSScriptMetadata.cs | 2 +- src/code/PublishPSResource.cs | 188 ++++--- src/code/RegisterPSResourceRepository.cs | 141 +++-- src/code/RepositorySettings.cs | 194 ++++++- src/code/SavePSResource.cs | 18 +- src/code/SetPSResourceRepository.cs | 117 ++--- src/code/UpdatePSResource.cs | 2 +- src/code/Utils.cs | 42 +- test/InstallPSResource.Tests.ps1 | 7 + test/PublishPSResource.Tests.ps1 | 49 ++ test/RegisterPSResourceRepository.Tests.ps1 | 98 +++- test/SavePSResource.Tests.ps1 | 2 +- test/SetPSResourceRepository.Tests.ps1 | 32 +- test/TestPSScriptFileInfo.Tests.ps1 | 14 + ...tWithoutEmptyLinesBetweenCommentBlocks.ps1 | 24 + .../ScriptWithoutEmptyLinesInMetadata.ps1 | 23 + 40 files changed, 2889 insertions(+), 1653 deletions(-) create mode 100644 test/testFiles/testScripts/ScriptWithoutEmptyLinesBetweenCommentBlocks.ps1 create mode 100644 test/testFiles/testScripts/ScriptWithoutEmptyLinesInMetadata.ps1 diff --git a/.ci/ci_release.yml b/.ci/ci_release.yml index 8aa38bbfc..706572091 100644 --- a/.ci/ci_release.yml +++ b/.ci/ci_release.yml @@ -239,13 +239,6 @@ stages: } } } - $noticeTxt = "$(signSrcPath)\PowerShellGet\Notice.txt" - $licenseTxt = "$(signSrcPath)\PowerShellGet\LICENSE" - - $netStandardSignedOutPath = Join-Path -Path $signOutPath -ChildPath "netstandard2.0" - - Copy-Item -Path $noticeTxt -Dest "$netStandardSignedOutPath\Notice.txt" -Force -Verbose - Copy-Item -Path $licenseTxt -Dest "$netStandardSignedOutPath\LICENSE" -Force -Verbose displayName: Copy already properly signed third party files condition: and(and(succeeded(), eq(variables['Build.Reason'], 'Manual')), ne(variables['SkipSigning'], 'True')) diff --git a/.gitignore b/.gitignore index 557d7d4e0..ab0db5255 100644 --- a/.gitignore +++ b/.gitignore @@ -3,3 +3,5 @@ src/code/obj srcOld/code/bin srcOld/code/obj out +test/**/obj +test/**/bin \ No newline at end of file diff --git a/help/Find-PSResource.md b/help/Find-PSResource.md index 2be404745..67db70601 100644 --- a/help/Find-PSResource.md +++ b/help/Find-PSResource.md @@ -1,6 +1,7 @@ --- external help file: PowerShellGet.dll-Help.xml Module Name: PowerShellGet +ms.date: 08/03/2022 online version: schema: 2.0.0 --- @@ -8,127 +9,189 @@ schema: 2.0.0 # Find-PSResource ## SYNOPSIS -Searches for packages from a repository (local or remote), based on `-Name` and other package properties. +Searches for packages from a repository (local or remote), based on a name or other package +properties. ## SYNTAX ### ResourceNameParameterSet (Default) -``` PowerShell -[[-Name] ] [-Type ] [-Version ] [-Prerelease] [-Tag ] [-Repository ] [-Credential ] [-IncludeDependencies] [-WhatIf] [-Confirm] [] + +``` +Find-PSResource [[-Name] ] [-Type ] [-Version ] [-Prerelease] + [-Tag ] [-Repository ] [-Credential ] [-IncludeDependencies] + [] ``` ### CommandNameParameterSet -``` PowerShell -[[-CommandName] ] [-ModuleName ] [-Version ] [-Prerelease] [-Tag ] -[-Repository ] [-Credential ] [-IncludeDependencies] [-WhatIf] [-Confirm] [] + +``` +Find-PSResource -CommandName [-Version ] [-Prerelease] [-ModuleName ] + [-Tag ] [-Repository ] [-Credential ] [-IncludeDependencies] + [] ``` ### DscResourceNameParameterSet -``` PowerShell -[[-DscResourceName] ] [-ModuleName ] [-Version ] [-Prerelease] [-Tag ] -[-Repository ] [-Credential ] [-IncludeDependencies] [-WhatIf] [-Confirm] [] -``` -### TagParameterSet -``` PowerShell -[-Name ][-Tag ] [-Prerelease] -[-Repository ] [-Credential ] [-IncludeDependencies] [-WhatIf] [-Confirm] [] ``` - -### TypeParameterSet -``` PowerShell -[Name ] [-Prerelease] [-Type ] -[-Repository ] [-Credential ] [-IncludeDependencies] [-WhatIf] [-Confirm] [] +Find-PSResource -DscResourceName [-Version ] [-Prerelease] + [-ModuleName ] [-Tag ] [-Repository ] [-Credential ] + [-IncludeDependencies] [] ``` ## DESCRIPTION -The `Find-PSResource` cmdlet searches for a package from a repository (local or remote) based on `-Name` or other package properties. + +The `Find-PSResource` cmdlet searches for a package from a repository (local or remote) based on a +name or other package properties. ## EXAMPLES ### Example 1 + +This examples searches PowerShell Gallery for the **PowerShellGet** package. The cmdlet returns the +highest non-prerelease version. + ```powershell -PS C:\> Find-PSResource -Name "Microsoft.PowerShell.SecretManagement" -Repository PSGallery - Name Version Prerelease Description - ---- ------- ---------- ----------- - Microsoft.PowerShell.SecretManagement 1.0.0.0 This module ... +Find-PSResource -Name PowerShellGet -Repository PSGallery ``` -These examples assume that the PSGallery repository is registered and contains the packages we are searching for. -This examples searches for the package with `-Name` "Microsoft.PowerShell.SecretManagement". It returns the highest non-prerelease version for the package found by searching through the `-Repository` "PSGallery", which at the time of writing this example is version "1.0.0.0". +```Output +Name Version Prerelease Repository Description +---- ------- ---------- ---------- ----------- +PowerShellGet 2.2.5.0 PSGallery PowerShell module with commands for discovering, installing, updating and … +``` ### Example 2 + +This examples searches PowerShell Gallery for the **PowerShellGet** package, including prerelease +versions. + ```powershell -PS C:\> Find-PSResource -Name "Microsoft.PowerShell.SecretManagement" -Repository PSGallery -Prerelease - Name Version Prerelease Description - ---- ------- ---------- ----------- - Microsoft.PowerShell.SecretManagement 1.1.0.0 preview2 This module ... +Find-PSResource -Name PowerShellGet -Repository PSGallery -Prerelease ``` -This examples searches for the package with `-Name` "Microsoft.PowerShell.SecretManagement". It returns the highest version (including considering prerelease versions) for the package found by searching through the specified `-Repository` "PSGallery", which at the time of writing this example is version "1.1.0-preview2". +```Output +Name Version Prerelease Repository Description +---- ------- ---------- ---------- ----------- +PowerShellGet 3.0.14.0 beta14 PSGallery PowerShell module with commands for discovering, installing, updating and… +``` ### Example 3 + +This examples searches PowerShell Gallery for the **Microsoft.PowerShell.SecretManagement** package. +The cmdlet returns all versions that satisfy the specified **Version** range. + ```powershell -PS C:\> Find-PSResource -Name "Microsoft.PowerShell.SecretManagement" -Version "(0.9.0.0, 1.0.0.0]" -Repository PSGallery -Prerelease - Name Version Prerelease Description - ---- ------- ---------- ----------- - Microsoft.PowerShell.SecretManagement 0.9.1.0 This module ... - Microsoft.PowerShell.SecretManagement 1.0.0.0 This module ... +Find-PSResource -Name "Microsoft.PowerShell.SecretManagement" -Version "(0.9.0.0, 1.2.0.0]" -Repository PSGallery -Prerelease ``` -This examples searches for the package with `-Name` "Microsoft.PowerShell.SecretManagement". It returns all versions which satisfy the specified `-Version` range by looking through the specified `-Repository` "PSGallery". At the time of writing this example those satisfying versions are: "0.9.1.0" and "1.0.0.0". +```Output +Name Version Prerelease Repository Description +---- ------- ---------- ---------- ----------- +Microsoft.PowerShell.SecretManagement 1.1.2.0 PSGallery … +Microsoft.PowerShell.SecretManagement 1.1.1.0 PSGallery … +Microsoft.PowerShell.SecretManagement 1.1.0.0 PSGallery … +Microsoft.PowerShell.SecretManagement 1.0.0.0 PSGallery … +Microsoft.PowerShell.SecretManagement 0.9.1.0 PSGallery … +``` ### Example 4 -```powershell -PS C:\> Find-PSResource -CommandName "Get-TargetResource" -Repository PSGallery - Name Version Prerelease ModuleName Repository - ---- ------- ---------- ---------- ---------- - Get-TargetResource 3.1.0.0 xPowerShellExecutionPolicy PSGallery - Get-TargetResource 1.0.0.4 WindowsDefender PSGallery - Get-TargetResource 1.2.0.0 SystemLocaleDsc PSGallery - Get-TargetResource 1.0.0.0 xInternetExplorerHomePage PSGallery - Get-TargetResource 4.0.1055.0 OctopusDSC PSGallery - Get-TargetResource 1.2.0.0 cRegFile PSGallery - Get-TargetResource 1.1.0.0 cWindowsErrorReporting PSGallery - Get-TargetResource 1.0.0.0 cVNIC PSGallery - Get-TargetResource 1.1.17.0 supVsts PSGallery +This examples searches for all module resources containing the **CommandName** of +`Get-TargetResource`. The cmdlet returns all the module resources that include the command. + +```powershell +Find-PSResource -CommandName Get-TargetResource -Repository PSGallery | + Select-Object -ExpandProperty ParentResource ``` -This examples searches for all module resources with `-CommandName` "Get-TargetResource" from the `-Repository` PSGallery. It returns all the module resources which include a command named "Get-TargetResource" and also lists the following information for each module resource: version, name (displayed under ModuleName) and repository. To access the rest of the properties of the parent module resource, you can access the `$_.ParentResource` of the PSIncludedResourceInfo object returned from the CommandName parameter set. +```Output +Name Version Prerelease Repository Description +---- ------- ---------- ---------- ----------- +xPowerShellExecutionPolicy 3.1.0.0 PSGallery This DSC resource can change the user preference for the W… +WindowsDefender 1.0.0.4 PSGallery Windows Defender module allows you to configure Windows De… +SystemLocaleDsc 1.2.0.0 PSGallery This DSC Resource allows configuration of the Windows Syst… +xInternetExplorerHomePage 1.0.0.0 PSGallery This DSC Resources can easily set an URL for the home page… +OctopusDSC 4.0.1127.0 PSGallery Module with DSC resource to install and configure an Octop… +cRegFile 1.2.0.0 PSGallery DSC resource which is designed to manage large numbers of … +cWindowsErrorReporting 1.1.0.0 PSGallery DSC Resource to enable or disable Windows Error Reporting +cVNIC 1.0.0.0 PSGallery DSC Module to create and configuring virutal network adapt… +supVsts 1.1.17.0 PSGallery Dsc module for interfacing with VSTS. +``` ### Example 5 + +This examples searches for a module resource with a a specific module with a named command. + ```powershell -PS C:\> Find-PSResource -CommandName "Get-TargetResource" -ModuleName "SystemLocaleDsc" -Repository PSGallery - Name Version Prerelease ModuleName Repository - ---- ------- ---------- ---------- ---------- - Get-TargetResource 1.2.0.0 SystemLocaleDsc PSGallery +Find-PSResource -CommandName Get-TargetResource -ModuleName SystemLocaleDsc -Repository PSGallery | + Select-Object -ExpandProperty ParentResource ``` -This examples searches for a module resource with a command named "Get-TargetResource" (via the `-CommandName` parameter), specifically from the module resource "SystemLocaleDsc" (via the `-ModuleName` parameter) from the `-Repository` PSGallery. The "SystemLocaleDsc" resource does indeed include a command named Get-TargetResource so this resource will be returned. The returned object lists the name of the command (displayed under Name) and the following information for the parent module resource: version, name (displayed under ModuleName) and repository. To access the rest of the properties of the parent module resource, you can access the `$_.ParentResource` of the PSIncludedResourceInfo object returned from the CommandName parameter set. +```Output +Name Version Prerelease Repository Description +---- ------- ---------- ---------- ----------- +SystemLocaleDsc 1.2.0.0 PSGallery This DSC Resource allows configuration of the Windows System Locale. +``` ### Example 6 -```powershell -PS C:\> Find-PSResource -DscResourceName "SystemLocale" -Repository PSGallery - Name Version Prerelease ModuleName Repository - ---- ------- ---------- ---------- ---------- - Get-TargetResource 8.5.0.0 ComputerManagementDsc PSGallery - Get-TargetResource 1.2.0.0 SystemLocaleDsc PSGallery +This examples searches for all module resources containing the DSC Resource `SystemLocale`. + +```powershell +Find-PSResource -DscResourceName SystemLocale -Repository PSGallery | + Select-Object -ExpandProperty ParentResource ``` -This examples searches for all module resources with `-DscResourceName` "SystemLocale" from the `-Repository` PSGallery. It returns all the module resources which include a DSC resource named "SystemLocale" and also lists the following information for each module resource: version, name (displayed under ModuleName) and repository. To access the rest of the properties of the parent module resource, you can access the `$_.ParentResource` of the PSIncludedResourceInfo object returned from the DSCResourceName parameter set. +```Output +Name Version Prerelease Repository Description +---- ------- ---------- ---------- ----------- +ComputerManagementDsc 8.5.0.0 PSGallery DSC resources for configuration of a Windows computer. These DSC r… +SystemLocaleDsc 1.2.0.0 PSGallery This DSC Resource allows configuration of the Windows System Local… +``` ### Example 7 + +This example searches all registered PSResourceRepositories for resources with names starting with +`Computer`. + ```powershell -PS C:\> Find-PSResource -Name * +Find-PSResource -Name Computer* ``` -This will search all PSResources from registered PSResourceRepositories. +```Output +Name Version Prerelease Repository Description +---- ------- ---------- ---------- ----------- +ComputerManagementDsc 8.5.0.0 PSGallery DSC resources for configuration … +ComputerManagement 1.1.2.3 PSGallery A PowerShell module for working … +Computer_JoinDomain_Config 1.0.0.0 PSGalleryScripts This configuration sets the mach… +Computer_UnjoinDomainAndJoinWorkgroup_Config 1.0.0.0 PSGalleryScripts This example switches the comput… +Computer_SetComputerDescriptionInWorkgroup_Config 1.0.0.0 PSGalleryScripts This example will set the comput… +Computer_JoinDomainSpecifyingDC_Config 1.0.0.0 PSGalleryScripts This configuration sets the mach… +Computer_RenameComputerAndSetWorkgroup_Config 1.0.0.0 PSGalleryScripts This configuration will set the … +Computer_RenameComputerInDomain_Config 1.0.0.0 PSGalleryScripts This example will change the mac… +Computer_RenameComputerInWorkgroup_Config 1.0.0.0 PSGalleryScripts This example will set the machin… +``` ## PARAMETERS +### -CommandName + +The name of the command to search for. + +```yaml +Type: System.String[] +Parameter Sets: CommandNameParameterSet +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + ### -Credential + Optional credentials to be used when accessing a repository. ```yaml @@ -143,9 +206,26 @@ Accept pipeline input: False Accept wildcard characters: False ``` +### -DscResourceName + +The name of the DSC Resource to search for. + +```yaml +Type: System.String[] +Parameter Sets: DscResourceNameParameterSet +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + ### -IncludeDependencies -When specified, search will return all matched resources along with any resources the matched resources depends on. -Dependencies are deduplicated. + +When specified, search returns all matching resources their dependencies. Dependencies are +deduplicated. ```yaml Type: System.Management.Automation.SwitchParameter @@ -154,19 +234,20 @@ Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -ModuleName -Specifies a module resource package name type to search for. -Wildcards are supported. + +Specifies a module resource package name type to search for. Wildcards are supported. + Not yet implemented. ```yaml -Type: System.String -Parameter Sets: (All) +Type: System.String[] +Parameter Sets: CommandNameParameterSet, DscResourceNameParameterSet Aliases: Required: False @@ -177,22 +258,25 @@ Accept wildcard characters: False ``` ### -Name -Name of a resource or resources to find. -Accepts wild card character '*'. + +Name of a resource to find. Wildcards are supported but NuGet only accepts the `*` character. NuGet +does not support wildcard searches of local (file-based) repositories. + ```yaml Type: System.String[] -Parameter Sets: (All) +Parameter Sets: ResourceNameParameterSet Aliases: -Required: True +Required: False Position: 0 Default value: None -Accept pipeline input: True (ByPropertyName, ByValue) +Accept pipeline input: True (ByValue) Accept wildcard characters: True ``` ### -Prerelease + When specified, includes prerelease versions in search results returned. ```yaml @@ -202,14 +286,19 @@ Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Repository -Specifies one or more repository names to search, which can include wildcard. -If not specified, search will include all currently registered repositories, in order of highest priority, until a repository is found that contains the package. + +Specifies one or more repository names to search. Wildcards are supported. + +If not specified, search includes all registered repositories, in priority order (highest first), +until a repository is found that contains the package. + +Lower **Priority** values have a higher precedence. ```yaml Type: System.String[] @@ -224,6 +313,7 @@ Accept wildcard characters: True ``` ### -Tag + Filters search results for resources that include one or more of the specified tags. ```yaml @@ -239,12 +329,17 @@ Accept wildcard characters: False ``` ### -Type -Specifies one or more resource types to find. -Resource types supported are: Module, Script, Command, DscResource. + +Specifies one or more resource types to find. Resource types supported are: + +- `Module` +- `Script` +- `Command` +- `DscResource` ```yaml -Type: Microsoft.PowerShell.PowerShellGet.UtilClasses.ResourceType[] -Parameter Sets: (All) +Type: Microsoft.PowerShell.PowerShellGet.UtilClasses.ResourceType +Parameter Sets: ResourceNameParameterSet Aliases: Accepted values: Module, Script, DscResource, Command @@ -256,16 +351,17 @@ Accept wildcard characters: False ``` ### -Version + Specifies the version of the resource to be returned. The value can be an exact version or a version range using the NuGet versioning syntax. -For more information about NuGet version ranges, see [Package versioning](/nuget/concepts/package-versioning#version-ranges) +Wildcards are supported but NuGet only accepts wildcard character `*`. For more information about +NuGet version ranges, see [Package versioning](/nuget/concepts/package-versioning#version-ranges). PowerShellGet supports all but the _minimum inclusive version_ listed in the NuGet version range -documentation. So inputting "1.0.0.0" as the version doesn't yield versions 1.0.0.0 and higher -(minimum inclusive range). Instead, the values is considered as the required version and yields -version 1.0.0.0 only (required version). To use the minimum inclusive range, provide `[1.0.0.0, ]` as -the version range. +documentation. Using `1.0.0.0` as the version doesn't yield versions 1.0.0.0 and higher (minimum +inclusive range). Instead, the value is considered to be the required version. To search for a +minimum inclusive range, use `[1.0.0.0, ]` as the version range. ```yaml Type: System.String @@ -279,39 +375,12 @@ Accept pipeline input: False Accept wildcard characters: True ``` -### -Confirm -Prompts you for confirmation before running the cmdlet. - -```yaml -Type: System.Management.Automation.SwitchParameter -Parameter Sets: (All) -Aliases: cf - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - -### -WhatIf -Shows what would happen if the cmdlet runs. -The cmdlet is not run. - -```yaml -Type: System.Management.Automation.SwitchParameter -Parameter Sets: (All) -Aliases: wi - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - ### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, +-InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, +-WarningAction, and -WarningVariable. For more information, see +[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS @@ -324,5 +393,3 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## NOTES ## RELATED LINKS - -[]() diff --git a/help/Get-PSResource.md b/help/Get-PSResource.md index 97484d7cd..1e4b281be 100644 --- a/help/Get-PSResource.md +++ b/help/Get-PSResource.md @@ -1,6 +1,7 @@ --- external help file: PowerShellGet.dll-Help.xml Module Name: PowerShellGet +ms.date: 08/03/2022 online version: schema: 2.0.0 --- @@ -8,98 +9,151 @@ schema: 2.0.0 # Get-PSResource ## SYNOPSIS -Returns resources (modules and scripts) installed on the machine via PowerShellGet. +Returns modules and scripts installed on the machine via **PowerShellGet**. ## SYNTAX +### __AllParameterSets + ``` -Get-PSResource [[-Name] ] [-Version ] [-Path ] [-Scope ] [] +Get-PSResource [[-Name] ] [-Version ] [-Path ] [-Scope ] + [] ``` ## DESCRIPTION -The Get-PSResource cmdlet combines the Get-InstalledModule, Get-InstalledScript cmdlets from V2. It performs a search within module or script installation paths based on the -Name parameter argument. It returns PSResourceInfo objects which describes each resource item found. Other parameters allow the returned results to be filtered by version and path. + +This cmdlet searches the module and script installation paths and returns **PSResourceInfo** objects +that describes each resource item found. This is equivalent to the combined output of the +`Get-InstalledModule` and `Get-InstalledScript` cmdlets from **PowerShellGet** v2. ## EXAMPLES ### Example 1 + +This example return all versions of modules and scripts installed on the machine. + ```powershell -PS C:\> Get-PSResource Az +Get-PSResource ``` -This will return versions (stable and prerelease) of the Az module installed via PowerShellGet. - ### Example 2 + +This example returns all versions of the **Az** module installed using **PowerShellGet**. + ```powershell -PS C:\> Get-PSResource Az -version "1.0.0" +Get-PSResource Az ``` -This will return version 1.0.0 of the Az module. - ### Example 3 + +This example return all versions of the **Az** module installed in the current directory. + ```powershell -PS C:\> Get-PSResource Az -version "(1.0.0, 3.0.0)" +Get-PSResource Az -Path . ``` -This will return all versions of the Az module within the specified range. - ### Example 4 + +This example returns a specific version of the Az module if it's installed on the system.. + ```powershell -PS C:\> Get-PSResource Az -version "4.0.1-preview" +Get-PSResource Az -Version 1.0.0 ``` -Assume that the package Az version 4.0.1-preview is already installed. This will return version 4.0.1-preview of the Az module. - ### Example 5 + +This example return all installed versions of the Az module within the specified version range. + ```powershell -PS C:\> Get-PSResource Az -version "4.0.1" +Get-PSResource Az -Version "(1.0.0, 3.0.0)" ``` -Assume that the package Az version 4.0.1-preview is already installed. This will not return Az version 4.0.1-preview as the full version (including prerelease label, i.e "4.0.1-preview") was not specified. ### Example 6 + +This example returns a specific preview version of the **PowerShellGet** module if it's installed +on the system. + ```powershell -PS C:\> Get-PSResource Az -Version "[4.0.1, 4.0.2-preview] +Get-PSResource PowerShellGet -Version 3.0.14-beta14 ``` -Assume that the following versions are already installed for package Az: 4.0.1-preview and 4.0.2-preview. This will only return version 4.0.2-preview as it is the only one which falls within the specified version range. Per NuGetVersion rules, a prerelease version is less than a stable version, so 4.0.1-preview is less than the 4.0.1 specified version so 4.0.1-preview does not fall within the specified version range and won't be returned. - +```Output +Name Version Prerelease Repository Description +---- ------- ---------- ---------- ----------- +PowerShellGet 3.0.14 beta14 PSGallery PowerShell module with commands for discovering, installing, updating and … +``` ### Example 6 + +The previous example showed that **PowerShellGet** version 3.0.14-beta14 was installed on the +system. This example shows that you must provide the full version, including the **Prerelease** +label to identify the installed module by **Version**. + ```powershell -PS C:\> Get-PSResource Az -Path . +Get-PSResource PowerShellGet -Version 3.0.14 ``` -This will return all versions of the Az module that have been installed in the current directory. +There is no output from this command. ### Example 7 + +In this example you see that there are four version of **PSReadLine** installed on the system. The +second command searches for a range of version between `2.2.0` and `2.3.0`. + ```powershell -PS C:\> Get-PSResource +Get-PSResource PSReadLine +``` + +```Output +Name Version Prerelease Repository Description +---- ------- ---------- ---------- ----------- +PSReadLine 2.2.6 PSGallery Great command line editing in the PowerShell console host +PSReadLine 2.2.5 PSGallery Great command line editing in the PowerShell console host +PSReadLine 2.2.2 PSGallery Great command line editing in the PowerShell console host +PSReadLine 2.2.0 beta4 PSGallery Great command line editing in the PowerShell console host +``` + +```powershell +Get-PSResource PSReadLine -Version '[2.2.0, 2.3.0]' +``` + +```Output +Name Version Prerelease Repository Description +---- ------- ---------- ---------- ----------- +PSReadLine 2.2.6 PSGallery Great command line editing in the PowerShell console host +PSReadLine 2.2.5 PSGallery Great command line editing in the PowerShell console host +PSReadLine 2.2.2 PSGallery Great command line editing in the PowerShell console host ``` -This will return all versions and scripts installed on the machine. +According to NuGet version rules a prerelease version is less than a stable version, so +`2.2.0-beta4` is less than the `2.2.0` version in the specified version range. ## PARAMETERS ### -Name -Name of a resource or resources to find. Accepts wild card characters or a null value. + +Name of a resource to find. Wildcards are supported but NuGet only accepts the `*` character. NuGet +does not support wildcard searches of local (file-based) repositories. ```yaml Type: System.String[] -Parameter Sets: NameParameterSet +Parameter Sets: (All) Aliases: Required: False Position: 0 Default value: None -Accept pipeline input: True +Accept pipeline input: True (ByValue) Accept wildcard characters: True ``` ### -Path + Specifies the path to search in. ```yaml Type: System.String -Parameter Sets: NameParameterSet +Parameter Sets: (All) Aliases: Required: False @@ -109,22 +163,15 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -Version -Specifies the version of the resource to be returned. The value can be an exact version or a version -range using the NuGet versioning syntax. - -For more information about NuGet version ranges, see [Package versioning](/nuget/concepts/package-versioning#version-ranges) +### -Scope -PowerShellGet supports all but the _minimum inclusive version_ listed in the NuGet version range -documentation. So inputting "1.0.0.0" as the version doesn't yield versions 1.0.0.0 and higher -(minimum inclusive range). Instead, the values is considered as the required version and yields -version 1.0.0.0 only (required version). To use the minimum inclusive range, provide `[1.0.0.0, ]` as -the version range. +Specifies the scope of the resource. ```yaml -Type: System.String -Parameter Sets: NameParameterSet +Type: Microsoft.PowerShell.PowerShellGet.UtilClasses.ScopeType +Parameter Sets: (All) Aliases: +Accepted values: CurrentUser, AllUsers Required: False Position: Named @@ -132,14 +179,24 @@ Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -Scope -Specifies the scope of the resource. + +### -Version + +Specifies the version of the resource to be returned. The value can be an exact version or a version +range using the NuGet versioning syntax. + +For more information about NuGet version ranges, see +[Package versioning](/nuget/concepts/package-versioning#version-ranges). + +PowerShellGet supports all but the _minimum inclusive version_ listed in the NuGet version range +documentation. Using `1.0.0.0` as the version doesn't yield versions 1.0.0.0 and higher (minimum +inclusive range). Instead, the value is considered to be the required version. To search for a +minimum inclusive range, use `[1.0.0.0, ]` as the version range. ```yaml -Type: Microsoft.PowerShell.PowerShellGet.UtilClasses.ScopeType +Type: System.String Parameter Sets: (All) Aliases: -Accepted values: CurrentUser, AllUsers Required: False Position: Named @@ -149,7 +206,11 @@ Accept wildcard characters: False ``` ### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, +-InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, +-WarningAction, and -WarningVariable. For more information, see +[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## NOTES diff --git a/help/Get-PSResourceRepository.md b/help/Get-PSResourceRepository.md index 87689c67d..6b96388e9 100644 --- a/help/Get-PSResourceRepository.md +++ b/help/Get-PSResourceRepository.md @@ -1,7 +1,8 @@ --- external help file: PowerShellGet.dll-Help.xml Module Name: PowerShellGet -online version: +ms.date: 08/03/2022 +online version: schema: 2.0.0 --- @@ -12,69 +13,88 @@ Finds and returns registered repository information. ## SYNTAX +### __AllParameterSets + ``` -Get-PSResourceRepository [[-Name] ] [] +Get-PSResourceRepository [[-Name] ] [] ``` ## DESCRIPTION -The Get-PSResourceRepository cmdlet searches for the PowerShell resource repositories that are registered on the machine. By default it will return all registered repositories, or if the `-Name` parameter argument is specified then it will return the repository which matches that name. It returns PSRepositoryInfo objects which contain information for each repository item found. + +This cmdlet searches for PowerShell resource repositories that are registered on the machine. By +default, it returns all registered repositories. ## EXAMPLES ### Example 1 -``` -PS C:\> Get-PSResourceRepository -Name "PSGallery" - Name Uri Trusted Priority - ---- --- ------- -------- - PSGallery https://www.powershellgallery.com/api/v2 False 50 + +This example returns all the repositories registered on the machine. + +```powershell +Get-PSResourceRepository ``` -This example runs the command with the 'Name' parameter being set to "PSGallery". This repository is registered on this machine so the command returns information on this repository. +```Output +Name Uri Trusted Priority +---- --- ------- -------- +PoshTestGallery https://www.poshtestgallery.com/api/v2 True 40 +PSGallery https://www.powershellgallery.com/api/v2 False 50 +psgettestlocal file:///c:/code/testdir True 50 +``` ### Example 2 -``` -PS C:\> Get-PSResourceRepository -Name "*Gallery" - Name Uri Trusted Priority - ---- --- ------- -------- - PoshTestGallery https://www.poshtestgallery.com/api/v2 True 40 - PSGallery https://www.powershellgallery.com/api/v2 False 50 +This example uses the **Name** parameter to get a specific repository. + +```powershell +Get-PSResourceRepository -Name PSGallery ``` -This example runs the command with the 'Name' parameter being set to "*Gallery" which includes a wildcard. The following repositories are registered on this machine and match the name pattern, so the command returns information on these repositories. +```Output +Name Uri Trusted Priority +---- --- ------- -------- +PSGallery https://www.powershellgallery.com/api/v2 False 50 +``` ### Example 3 -``` -PS C:\> Get-PSResourceRepository -Name "PSGallery","PoshTestGallery" - Name Uri Trusted Priority - ---- --- ------- -------- - PoshTestGallery https://www.poshtestgallery.com/api/v2 True 40 - PSGallery https://www.powershellgallery.com/api/v2 False 50 +This example uses the **Name** parameter to get all repositories that end with `Gallery`. + +```powershell +Get-PSResourceRepository -Name "*Gallery" ``` -This example runs the command with the 'Name' parameter being set to an array of Strings. Both of the specified repositories are registered on this machine and match the name pattern, so the command returns information on these repositories. +```Output +Name Uri Trusted Priority +---- --- ------- -------- +PoshTestGallery https://www.poshtestgallery.com/api/v2 True 40 +PSGallery https://www.powershellgallery.com/api/v2 False 50 +``` ### Example 4 -``` -PS C:\> Get-PSResourceRepository -Name "*" - Name Uri Trusted Priority - ---- --- ------- -------- - PoshTestGallery https://www.poshtestgallery.com/api/v2 True 40 - PSGallery https://www.powershellgallery.com/api/v2 False 50 - psgettestlocal file:///c:/code/testdir True 50 +This example uses the **Name** parameter to get a list of named respositories. + +```powershell +Get-PSResourceRepository -Name "PSGallery","PoshTestGallery" ``` -This example runs the command with the 'Name' parameter being set to a single wildcard character. So all the repositories registered on this machine are returned. +```Output +Name Uri Trusted Priority +---- --- ------- -------- +PoshTestGallery https://www.poshtestgallery.com/api/v2 True 40 +PSGallery https://www.powershellgallery.com/api/v2 False 50 +``` ## PARAMETERS ### -Name -This parameter takes a String argument, including wildcard characters, or an array of such String arguments. It is used to search for repository names from the repository store which match the provided name pattern. Tab completion is provided on this argument and will display registered repository names. + +The name of the repository to search for. Wildcards are supported. Tab completion for this parameter +cycles through the registered repository names. ```yaml -Type: String[] +Type: System.String[] Parameter Sets: (All) Aliases: @@ -86,7 +106,11 @@ Accept wildcard characters: True ``` ### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, +-InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, +-WarningAction, and -WarningVariable. For more information, see +[about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS @@ -97,6 +121,5 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ### Microsoft.PowerShell.PowerShellGet.UtilClasses.PSRepositoryInfo ## NOTES -If no value for Name is provided, Get-PSResourceRepository will return information for all registered repositories. ## RELATED LINKS diff --git a/help/Install-PSResource.md b/help/Install-PSResource.md index f4120260b..28eb45d6f 100644 --- a/help/Install-PSResource.md +++ b/help/Install-PSResource.md @@ -1,165 +1,156 @@ --- external help file: PowerShellGet.dll-Help.xml Module Name: PowerShellGet -online version: +ms.date: 08/03/2022 +online version: schema: 2.0.0 --- # Install-PSResource ## SYNOPSIS -Installs resources (modules and scripts) from a registered repository onto the machine. +Installs resources from a registered repository. ## SYNTAX -### NameParameterSet +### NameParameterSet (Default) + ``` -Install-PSResource [-Name ] [-Version ] [-Prerelease] - [-Repository ] [-Credential ] [-Scope ] [-TrustRepository] - [-Reinstall] [-Quiet] [-AcceptLicense] [-NoClobber] [-SkipDependencyCheck] [-AuthenticodeCheck] [-PassThru] [-WhatIf] [-Confirm] [] +Install-PSResource [-Name] [-Version ] [-Prerelease] [-Repository ] + [-Credential ] [-Scope ] [-TrustRepository] [-Reinstall] [-Quiet] + [-AcceptLicense] [-NoClobber] [-SkipDependencyCheck] [-AuthenticodeCheck] [-PassThru] [-WhatIf] + [-Confirm] [] ``` ### InputObjectParameterSet + ``` -Install-PSResource [-InputObject ] [-Credential ] [-Scope ] [-TrustRepository] - [-Reinstall] [-Quiet] [-AcceptLicense] [-NoClobber] [-SkipDependencyCheck] [-AuthenticodeCheck] [-WhatIf] [-Confirm] [] +Install-PSResource [-InputObject] [-Credential ] + [-Scope ] [-TrustRepository] [-Reinstall] [-Quiet] [-AcceptLicense] [-NoClobber] + [-SkipDependencyCheck] [-AuthenticodeCheck] [-PassThru] [-WhatIf] [-Confirm] [] ``` - -### RequiredResourceParameterSet + +### RequiredResourceFileParameterSet + ``` -Install-PSResource [-RequiredResource ] [-Credential ] [-Scope ] [-TrustRepository] - [-Reinstall] [-Quiet] [-AcceptLicense] [-NoClobber] [-SkipDependencyCheck] [-AuthenticodeCheck] [-PassThru] [-WhatIf] [-Confirm] [] +Install-PSResource [-Credential ] [-Scope ] [-TrustRepository] + [-Reinstall] [-Quiet] [-AcceptLicense] [-NoClobber] [-SkipDependencyCheck] [-AuthenticodeCheck] + [-PassThru] [-RequiredResourceFile ] [-WhatIf] [-Confirm] [] ``` - -### RequiredResourceFileParameterSet + +### RequiredResourceParameterSet + ``` -Install-PSResource [-RequiredResourceFile ] [-Credential ] [-Scope ] [-TrustRepository] - [-Reinstall] [-Quiet] [-AcceptLicense] [-NoClobber] [-SkipDependencyCheck] [-AuthenticodeCheck] [-PassThru] [-WhatIf] [-Confirm] [] +Install-PSResource [-Credential ] [-Scope ] [-TrustRepository] + [-Reinstall] [-Quiet] [-AcceptLicense] [-NoClobber] [-SkipDependencyCheck] [-AuthenticodeCheck] + [-PassThru] [-RequiredResource ] [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION -The Install-PSResource cmdlet combines the Install-Module and Install-Script cmdlets from V2. -It installs a resource from a registered repository to an installation path on a machine based on the -Name parameter argument. It does not return any object. Other parameters allow the resource to be specified by repository and version, and allow the user to suppress prompts or specify the scope of installation. + +This cmdlet installs resources from a registered repository to an installation path on a machine. By +default, the cmdlet doesn't return any object. Other parameters allow you to specify the repository, +scope, and version for a resource, and suppress license prompts. + +This cmdlet combines the functions of the `Install-Module` and `Install-Script` cmdlets from +**PowerShellGet** v2. ## EXAMPLES ### Example 1 -```powershell -PS C:\> Install-PSResource Az -``` -Installs the Az module. +Installs the latest stable (non-prerelease) version of the **Az** module. -### Example 2 ```powershell -PS C:\> Install-PSResource Az -Version "[2.0.0, 3.0.0]" +Install-PSResource Az ``` -Installs the latest stable Az module that is within the range 2.0.0 and 3.0.0. +### Example 2 + +Installs the latest stable **Az** module within the between versions `7.3.0` and `8.3.0`. -### Example 3 ```powershell -PS C:\> Install-PSResource Az -Repository PSGallery +Install-PSResource Az -Version '[7.3.0, 8.3.0]' ``` -Installs the latest stable Az module from the PowerShellGallery. +### Example 3 +Installs the latest stable version of the **Az** module. When the **Reinstall** parameter is used, +the cmdlet writes over any previously installed version. -### Example 3 ```powershell -PS C:\> Install-PSResource Az -Reinstall +Install-PSResource Az -Reinstall ``` -Installs the Az module and will write over any previously installed version if it is already installed. - ### Example 4 -```powershell -PS C:\> Install-PSResource -RequiredResourceFile myRequiredModules.psd1 -``` Installs the PSResources specified in the psd1 file. +```powershell +Install-PSResource -RequiredResourceFile myRequiredModules.psd1 +``` + ### Example 5 + +Installs the PSResources specified in the hashtable. + ```powershell -PS C:\> Install-PSResource -RequiredResource @{ +Install-PSResource -RequiredResource @{ TestModule = @{ version = "[0.0.1,1.3.0]" repository = "PSGallery" } - TestModulePrerelease = @{ + TestModulePrerelease = @{ version = "[0.0.0,0.0.5]" repository = "PSGallery" prerelease = "true" - } + } TestModule99 = @{} } ``` -Installs the PSResources specified in the hashtable. - ## PARAMETERS -### -Name -Name of a resource or resources to install. Does not accept wildcard characters or a null value. - -```yaml -Type: System.String[] -Parameter Sets: NameParameterSet -Aliases: - -Required: True -Position: 0 -Default value: None -Accept pipeline input: True (ByValue) -Accept wildcard characters: False -``` - -### -Version -Specifies the version of the resource to be installed. The value can be an exact version or a version -range using the NuGet versioning syntax. - -For more information about NuGet version ranges, see [Package versioning](/nuget/concepts/package-versioning#version-ranges) +### -AcceptLicense -PowerShellGet supports all but the _minimum inclusive version_ listed in the NuGet version range -documentation. So inputting "1.0.0.0" as the version doesn't yield versions 1.0.0.0 and higher -(minimum inclusive range). Instead, the values is considered as the required version and yields -version 1.0.0.0 only (required version). To use the minimum inclusive range, provide `[1.0.0.0, ]` as -the version range. +Specifies that the resource should accept any request to accept the license agreement. This +suppresses prompting if the module mandates that a user accept the license agreement. ```yaml -Type: System.String -Parameter Sets: NameParameterSet +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` -### -Prerelease -When specified, includes prerelease versions in search results returned. +### -AuthenticodeCheck + +Validates Authenticode signatures and catalog files on Windows. ```yaml Type: System.Management.Automation.SwitchParameter -Parameter Sets: NameParameterSet +Parameter Sets: (All) Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` -### -Repository -Specifies one or more repository names to search. -If not specified, search will include all currently registered repositories, in order of highest priority, until first repository package is found in. +### -Credential + +Optional credentials used when accessing a repository. ```yaml -Type: System.String[] -Parameter Sets: NameParameterSet +Type: System.Management.Automation.PSCredential +Parameter Sets: (All) Aliases: Required: False @@ -168,93 +159,30 @@ Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -RequiredResource -A hashtable or json string which specifies resources to install. Does not accept wildcard characters or a null value. -The hashtable will take a format with the module attributes like the following example -```Powershell - @{ - TestModule = @{ - version = "[0.0.1,1.3.0]" - repository = "PSGallery" - } - - TestModulePrerelease = @{ - version = "[0.0.0,0.0.5]" - repository = "PSGallery" - prerelease = "true" - } +### -InputObject - TestModule99 = @{} -} -``` -A json string will take the following example format -```json -{ - "TestModule": { - "version": "[0.0.1,1.3.0)", - "repository": "PSGallery" - }, - "TestModulePrerelease": { - "version": "[0.0.0,0.0.5]", - "repository": "PSGallery", - "prerelease": "true" - }, - "TestModule99": {} -} -``` +Used for pipeline input. ```yaml -Type: RequiredResource -Parameter Sets: RequiredResource +Type: Microsoft.PowerShell.PowerShellGet.UtilClasses.PSResourceInfo +Parameter Sets: InputObjectParameterSet Aliases: Required: True -Position: 0 +Position: Named Default value: None Accept pipeline input: True (ByValue) Accept wildcard characters: False -``` - -### -RequiredResourceFile -Path to a psd1 or json which specifies resources to install. Does not accept wildcard characters or a null value. +``` -The psd1 will take a hashtable format with the module attributes like the following example -```Powershell - @{ - TestModule = @{ - version = "[0.0.1,1.3.0]" - repository = "PSGallery" - } +### -Name - TestModulePrerelease = @{ - version = "[0.0.0,0.0.5]" - repository = "PSGallery" - prerelease = "true" - } - - TestModule99 = @{} -} -``` -json files will take the following example format -```json -{ - "TestModule": { - "version": "[0.0.1,1.3.0)", - "repository": "PSGallery" - }, - "TestModulePrerelease": { - "version": "[0.0.0,0.0.5]", - "repository": "PSGallery", - "prerelease": "true" - }, - "TestModule99": {} -} -``` +The name of one or more resources to install. ```yaml Type: System.String[] -Parameter Sets: RequiredResourceFileParameterSet +Parameter Sets: NameParameterSet Aliases: Required: True @@ -264,55 +192,57 @@ Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` +### -NoClobber -### -Credential -Optional credentials to be used when accessing a repository. +Prevents installing a package that contains cmdlets that already exist on the machine. ```yaml -Type: System.Management.Automation.PSCredential +Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` -### -Scope -Specifies the scope under which a user has access. +### -PassThru + +When specified, outputs a **PSResourceInfo** object for the saved resource. ```yaml -Type: Microsoft.PowerShell.PowerShellGet.UtilClasses.ScopeType +Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: -Accepted values: CurrentUser, AllUsers Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` -### -TrustRepository -Suppress prompts to trust repository. The prompt to trust repository only occurs if the repository is not already set to a trusted level. +### -Prerelease + +When specified, includes prerelease versions in search results returned. ```yaml Type: System.Management.Automation.SwitchParameter -Parameter Sets: (All) +Parameter Sets: NameParameterSet Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` -### -Reinstall -Writes over any previously installed resource version that already exists on the machine. +### -Quiet + +Suppresses installation progress bar. ```yaml Type: System.Management.Automation.SwitchParameter @@ -321,13 +251,18 @@ Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` -### -Quiet -Supresses installation progress bar. +### -Reinstall + +Installs the latest version of a module even if the latest version is already installed. The +installed version is overwritten. This allows you to repair a damaged installation of the module. + +If an older version of the module is installed, the new version is installed side-by-side in a new +version-specific folder. ```yaml Type: System.Management.Automation.SwitchParameter @@ -336,17 +271,23 @@ Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` -### -AcceptLicense -Specifies that the resource should accept any request to accept license. This will suppress prompting if the module mandates that a user accept their license. +### -Repository + +Specifies one or more repository names to search. Wildcards are supported. + +If not specified, search includes all registered repositories, in priority order (highest first), +until a repository is found that contains the package. + +Lower **Priority** values have a higher precedence. ```yaml -Type: System.Management.Automation.SwitchParameter -Parameter Sets: (All) +Type: System.String[] +Parameter Sets: NameParameterSet Aliases: Required: False @@ -356,28 +297,64 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -NoClobber -Prevents installing a package that contains cmdlets that already exist on the machine. +### -RequiredResource + +A hashtable or JSON string that specifies resources to install. Wildcard characters aren't allowed. +See the [NOTES](#notes) section for a description of the file formats. ```yaml -Type: System.Management.Automation.SwitchParameter -Parameter Sets: (All) -Aliases: +Type: System.Object +Parameter Sets: RequiredResourceParameterSet +Aliases: Required: False -Position: Named +Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -SkipDependencyCheck -Skips the check for resource dependencies, so that only found resources are installed, and not any resources the found resource depends on. +### -RequiredResourceFile + +Path to a `.psd1` or `.json` that specifies resources to install. Wildcard characters aren't +allowed. See the [NOTES](#notes) section for a description of the file formats. ```yaml -Type: System.Management.Automation.SwitchParameter +Type: System.String +Parameter Sets: RequiredResourceFileParameterSet +Aliases: + +Required: False +Position: 0 +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Scope + +Specifies the installation scope. Accepted values are: + +- `CurrentUser` +- `AllUsers` + +The default scope is `CurrentUser`, which doesn't require elevation for install. + +The `AllUsers` scope installs modules in a location accessible to all users of the computer. For +example: + +- `$env:ProgramFiles\PowerShell\Modules` + +The `CurrentUser` installs modules in a location accessible only to the current user of the +computer. For example: + +- `$home\Documents\PowerShell\Modules` + +```yaml +Type: Microsoft.PowerShell.PowerShellGet.UtilClasses.ScopeType Parameter Sets: (All) -Aliases: +Aliases: +Accepted values: CurrentUser, AllUsers Required: False Position: Named @@ -385,23 +362,28 @@ Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -AuthenticodeCheck -Does a check to to validate signed files and catalog files on Windows. + +### -SkipDependencyCheck + +Skips the check for resource dependencies. Only found resources are installed. No resources of the +found resource are installed. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) -Aliases: +Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False -``` +``` -### -PassThru -Passes the resource installed to the console. +### -TrustRepository + +Suppress prompts to trust repository. The prompt to trust repository only occurs if the repository +isn't configured as trusted. ```yaml Type: System.Management.Automation.SwitchParameter @@ -410,18 +392,28 @@ Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` -### -InputObject -Used for pipeline input. +### -Version + +Specifies the version of the resource to be returned. The value can be an exact version or a version +range using the NuGet versioning syntax. + +For more information about NuGet version ranges, see +[Package versioning](/nuget/concepts/package-versioning#version-ranges). + +PowerShellGet supports all but the _minimum inclusive version_ listed in the NuGet version range +documentation. Using `1.0.0.0` as the version doesn't yield versions 1.0.0.0 and higher (minimum +inclusive range). Instead, the value is considered to be the required version. To search for a +minimum inclusive range, use `[1.0.0.0, ]` as the version range. ```yaml -Type: Microsoft.PowerShell.PowerShellGet.UtilClasses.PSResourceInfo -Parameter Sets: (All) -Aliases: wi +Type: System.String +Parameter Sets: NameParameterSet +Aliases: Required: False Position: Named @@ -431,6 +423,7 @@ Accept wildcard characters: False ``` ### -Confirm + Prompts you for confirmation before running the cmdlet. ```yaml @@ -440,14 +433,14 @@ Aliases: cf Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf -Shows what would happen if the cmdlet runs. -The cmdlet is not run. + +Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter @@ -456,14 +449,86 @@ Aliases: wi Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, +-InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, +-WarningAction, and -WarningVariable. For more information, see +[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS + +### Microsoft.PowerShell.PowerShellGet.UtilClasses.PSResourceInfo + +By default, the cmdlet doesn't return any objects. When the **PassThru** parameter is used, the +cmdlet outputs a **PSResourceInfo** object for the saved resource. ## NOTES +The **RequiredResource** and **RequiredResourceFile** parameters are used to match **PSResources** +matching specific criteria. You can specify the criteria using a hashtable or a JSON object. For the +**RequiredResourceFile** parameter, the hashtable is stored in a `.psd1` file and the JSON object is +stored in a `.json` file. + +The hashtable can contain attributes for multiple modules. The following example show the structure +of the module specification: + +```Syntax +@{ + = @{ + version = '' + repository = '' + prerelease = '' + } +} +``` + +This example contains specifications for three modules. As you can, the module attributes are +optional. + +```powershell + @{ + TestModule = @{ + version = '[0.0.1,1.3.0]' + repository = 'PSGallery' + } + + TestModulePrerelease = @{ + version = '[0.0.0,0.0.5]' + repository = 'PSGallery' + prerelease = 'true' + } + + TestModule99 = @{} +} +``` + +The next example shows the same specification in JSON format. + +```json +{ + "TestModule": { + "version": "[0.0.1,1.3.0)", + "repository": "PSGallery" + }, + "TestModulePrerelease": { + "version": "[0.0.0,0.0.5]", + "repository": "PSGallery", + "prerelease": "true" + }, + "TestModule99": {} +} +``` + ## RELATED LINKS + +[Package versioning](/nuget/concepts/package-versioning#version-ranges) + +[Uninstall-PSResource](Uninstall-PSResource.md) diff --git a/help/New-PSScriptFileInfo.md b/help/New-PSScriptFileInfo.md index 48301c3d5..d21f2db2c 100644 --- a/help/New-PSScriptFileInfo.md +++ b/help/New-PSScriptFileInfo.md @@ -1,35 +1,48 @@ --- external help file: PowerShellGet-help.xml Module Name: PowerShellGet -online version: +ms.date: 08/03/2022 +online version: schema: 2.0.0 --- # New-PSScriptFileInfo ## SYNOPSIS - -Creates a new .ps1 file containing metadata for the script, which is used when publishing a script package. +The cmdlet creates a new script file, including metadata about the script. ## SYNTAX ### __AllParameterSets ``` -New-PSScriptFileInfo [-FilePath] -Description [-Author ] [-CompanyName ] [-Copyright ] [-ExternalModuleDependencies ] [-ExternalScriptDependencies ] [-Force] [-Guid ] [-IconUri ] [-LicenseUri ] [-PrivateData ] [-ProjectUri ] [-ReleaseNotes ] [-RequiredModules ] [-RequiredScripts ] [-Tags ] [-Version ] [] +New-PSScriptFileInfo [-FilePath] -Description [-Version ] + [-Author ] [-Guid ] [-CompanyName ] [-Copyright ] + [-RequiredModules ] [-ExternalModuleDependencies ] + [-RequiredScripts ] [-ExternalScriptDependencies ] [-Tags ] + [-ProjectUri ] [-LicenseUri ] [-IconUri ] [-ReleaseNotes ] + [-PrivateData ] [-Force] [] ``` ## DESCRIPTION -The New-PSScriptFileInfo cmdlet creates a .ps1 file containing metadata for the script. +The cmdlet creates a new script file containing the required metadata needed to publish a script +package. ## EXAMPLES -### Example 1: Creating a script with minimum required parameters +### Example 1: Creating an empty script with minimal information + +This example runs the cmdlet using only required parameters. The **FilePath** parameter specifies +the nane and location of the script. The **Description** parameter provide the description used in +the comment-based help for the script. +```powershell +New-PSScriptFileInfo -FilePath ./test_script.ps1 -Description "This is a test script." +Get-Content ./test_script.ps1 ``` -PS C:\> New-PSScriptFileInfo -FilePath "C:\Users\johndoe\MyScripts\test_script.ps1" -Description "this is a test script" -PS C:\> cat "C:\Users\johndoe\MyScripts\test_script.ps1" + +```Output <#PSScriptInfo .VERSION 1.0.0.0 @@ -50,11 +63,11 @@ PS C:\> cat "C:\Users\johndoe\MyScripts\test_script.ps1" .ICONURI -.EXTERNALMODULEDEPENDENCIES +.EXTERNALMODULEDEPENDENCIES -.REQUIREDSCRIPTS +.REQUIREDSCRIPTS -.EXTERNALSCRIPTDEPENDENCIES +.EXTERNALSCRIPTDEPENDENCIES .RELEASENOTES @@ -67,21 +80,36 @@ PS C:\> cat "C:\Users\johndoe\MyScripts\test_script.ps1" <# .DESCRIPTION -this is a test script +This is a test script. #> - -``` -This example runs the cmdlet with the only required parameters, the 'FilePath' parameter sets the path the script is to be created and the 'Description' parameter contains the description for the script. The script is successfully created and if the contents of the file are viewed we can see the Description set as well as Author, Guid, and Version (with default values). - -### Example 2: Creating a script with RequiredModules, Author, Version and Description parameters +``` +### Example 2: Creating a script with required modules + +This example runs the cmdlet with additional parameters, including **RequiredModules**. The +**RequiredModules** parameter describes modules required by the script. The parameter takes an array +of hashtables. The **ModuleName** key in the hashtable is required. You can also include +**ModuleVersion**, **RequiredVersion**, **MaximumVersion**, or **MinimumVersion** keys. + +```powershell +$parameters = @{ + FilePath = './test_script2.ps1' + Description = 'This is a test script.' + Version = '2.0.0.0' + Author = 'janedoe' + RequiredModules = @( + @{ModuleName = "PackageManagement"; ModuleVersion = "1.0.0.0" }, + @{ModuleName = "PSReadLine"} + ) +} +New-PSScriptFileInfo @parameters +Get-Content ./test_script2.ps1 ``` -PS C:\> $requiredModules = @(@{ModuleName = "PackageManagement"; ModuleVersion = "1.0.0.0" }, @{ModuleName = "PSReadLine"}) -PS C:\> New-PSScriptFileInfo -FilePath "C:\Users\johndoe\MyScripts\test_script2.ps1" -Description "this is a test script" -Version "2.0.0.0" -Author "janedoe" -RequiredModules $requiredModules -PS C:\> cat "C:\Users\johndoe\MyScripts\test_script.ps1" + +```Output <#PSScriptInfo .VERSION 2.0.0.0 @@ -90,7 +118,7 @@ PS C:\> cat "C:\Users\johndoe\MyScripts\test_script.ps1" .AUTHOR janedoe -.COMPANYNAME Jane Corporation +.COMPANYNAME .COPYRIGHT @@ -102,11 +130,11 @@ PS C:\> cat "C:\Users\johndoe\MyScripts\test_script.ps1" .ICONURI -.EXTERNALMODULEDEPENDENCIES +.EXTERNALMODULEDEPENDENCIES -.REQUIREDSCRIPTS +.REQUIREDSCRIPTS -.EXTERNALSCRIPTDEPENDENCIES +.EXTERNALSCRIPTDEPENDENCIES .RELEASENOTES @@ -122,30 +150,27 @@ PS C:\> cat "C:\Users\johndoe\MyScripts\test_script.ps1" <# .DESCRIPTION -this is a test script +This is a test script. #> - -``` -This example runs the cmdlet with the required 'FilePath' and 'Description' parameters, as well as 'Author', 'Version', and 'RequiredModules' parameters. The 'RequiredModules' parameter describes modules required by the script. It is necessary to provide the ModuleName key in the hashtable and if one wishes to specify verion they must also specify ModuleVersion, RequiredVersion, MaximumVersion, or MinimumVersion keys. The script is successfully created and if the contents of the file are viewed we can see the following values are set in the script file: Description, Author, Guid, and Version and RequiredModules. +``` ## PARAMETERS ### -Author -The author of the script. +The name of the author of the script. ```yaml Type: System.String Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` @@ -155,14 +180,13 @@ Accept wildcard characters: False The name of the company owning the script. ```yaml -Type: String +Type: System.String Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` @@ -172,14 +196,13 @@ Accept wildcard characters: False The copyright information for the script. ```yaml -Type: String +Type: System.String Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` @@ -189,14 +212,13 @@ Accept wildcard characters: False The description of the script. ```yaml -Type: String +Type: System.String Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: True Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` @@ -206,14 +228,13 @@ Accept wildcard characters: False The list of external module dependencies taken by this script. ```yaml -Type: String[] +Type: System.String[] Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` @@ -223,99 +244,94 @@ Accept wildcard characters: False The list of external script dependencies taken by this script. ```yaml -Type: String[] +Type: System.String[] Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -FilePath -The path the .ps1 script info file will be created at. +The filename and location where the script is created. ```yaml -Type: String +Type: System.String Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: True Position: 0 -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Force -If used and the .ps1 file specified at the path exists, it rewrites the file. +Forces the cmdlet to overwrite any existing file. ```yaml -Type: SwitchParameter +Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Guid -The GUID for the script. +The unique identifier for the script in GUID format. If you don't provide a GUID, the cmdlet creates +a new one automatically. ```yaml -Type: Guid +Type: System.Guid Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: Randomly generated Accept pipeline input: False Accept wildcard characters: False ``` ### -IconUri -The Uri for the icon associated with the script. +A Uniform Resource Identifier (URI) pointing to the icon associated with the script. ```yaml -Type: String +Type: System.String Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -LicenseUri -The Uri for the license associated with the script. +The URI pointing to the license agreement file associated with the script. ```yaml -Type: String +Type: System.String Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` @@ -325,31 +341,29 @@ Accept wildcard characters: False The private data associated with the script. ```yaml -Type: String +Type: System.String Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ProjectUri -The Uri for the project associated with the script. +The URI pointing to the project site associated with the script. ```yaml -Type: String +Type: System.String Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` @@ -359,31 +373,37 @@ Accept wildcard characters: False The release notes for the script. ```yaml -Type: String[] +Type: System.String Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RequiredModules -The list of modules required by the script. +The parameter takes an array of module specification hashtables. A module specification is a +hashtable that has the following keys. + +- **ModuleName** - Required Specifies the module name. +- **GUID** - Optional Specifies the GUID of the module. +- One of these three version key is Required. These keys can't be used together. + - **ModuleVersion** - Specifies a minimum acceptable version of the module. + - **RequiredVersion** - Specifies an exact, required version of the module. + - **MaximumVersion** - Specifies the maximum acceptable version of the module. ```yaml -Type: Hashtable[] +Type: System.Collections.Hashtable[] Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` @@ -393,67 +413,75 @@ Accept wildcard characters: False The list of scripts required by the script. ```yaml -Type: String[] +Type: System.String[] Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: -Required: True (None) False (All) +Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Tags -The tags associated with the script. +The tags associated with the script. Tag values are strings that should not contain spaces. For more +information, see [Tag details][1]. ```yaml -Type: String[] +Type: System.String[] Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: -Required: True (None) False (All) +Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Version -The version of the script. +The version of the script. If no value is provided **Version** defaults to `1.0.0.0`. ```yaml -Type: String +Type: System.String Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: -Required: True (None) False (All) +Required: False Position: Named -Default value: +Default value: 1.0.0.0 Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, +-InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, +-WarningAction, and -WarningVariable. For more information, see +[about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None - - ## OUTPUTS -### None +### System.Object ## NOTES ## RELATED LINKS +[PowerShellGallery Publishing Guidelines and Best Practices][2] + +[Package manifest values that impact the PowerShell Gallery UI][3] + + + +[1]: /powershell/scripting/gallery/concepts/package-manifest-affecting-ui#tag-details +[2]: /powershell/scripting/gallery/concepts/publishing-guidelines +[3]: /powershell/scripting/gallery/concepts/package-manifest-affecting-ui diff --git a/help/PowerShellGet.md b/help/PowerShellGet.md index 548aaf5ab..fe3f5e99f 100644 --- a/help/PowerShellGet.md +++ b/help/PowerShellGet.md @@ -1,46 +1,64 @@ --- -Module Name: PowerShellGet -Module Guid: 1d73a601-4a6c-43c5-ba3f-619b18bbb404 -Download Help Link: {{ Update Download Link }} -Help Version: {{ Please enter version of help manually (X.X.X.X) format }} +Download Help Link: https://aka.ms/powershell73-help +Help Version: 3.0.16 Locale: en-US +Module Guid: 1d73a601-4a6c-43c5-ba3f-619b18bbb404 +Module Name: PowerShellGet +ms.date: 08/03/2022 --- # PowerShellGet Module ## Description -{{ Fill in the Description }} +PowerShellGet is a module with commands for discovering, installing, updating and publishing +PowerShell artifacts like Modules, DSC Resources, Role Capabilities, and Scripts. + +This documentation covers the latest preview version PowerShellGet v3. ## PowerShellGet Cmdlets ### [Find-PSResource](Find-PSResource.md) -{{ Fill in the Description }} +Searches for packages from a repository (local or remote), based on a name or other package properties. ### [Get-PSResource](Get-PSResource.md) -{{ Fill in the Description }} +Returns modules and scripts installed on the machine via **PowerShellGet**. ### [Get-PSResourceRepository](Get-PSResourceRepository.md) -{{ Fill in the Description }} +Finds and returns registered repository information. ### [Install-PSResource](Install-PSResource.md) +Installs resources from a registered repository. + +### [New-PSScriptFileInfo](New-PSScriptFileInfo.md) +The cmdlet creates a new script file, including metadata about the script. + +### [PowerShellGet](PowerShellGet.md) {{ Fill in the Description }} ### [Publish-PSResource](Publish-PSResource.md) -{{ Fill in the Description }} +Publishes a specified module from the local computer to PSResource repository. ### [Register-PSResourceRepository](Register-PSResourceRepository.md) -{{ Fill in the Description }} +Registers a repository for PowerShell resources. ### [Save-PSResource](Save-PSResource.md) -{{ Fill in the Description }} +Saves resources (modules and scripts) from a registered repository onto the machine. ### [Set-PSResourceRepository](Set-PSResourceRepository.md) -{{ Fill in the Description }} +Sets information for a registered repository. + +### [Test-PSScriptFileInfo](Test-PSScriptFileInfo.md) +Tests the comment-based metadata in a `.ps1` file to ensure it's valid for publication. ### [Uninstall-PSResource](Uninstall-PSResource.md) -{{ Fill in the Description }} +Uninstalls a resource that was installed using **PowerShellGet**. ### [Unregister-PSResourceRepository](Unregister-PSResourceRepository.md) -{{ Fill in the Description }} +Removes a registered repository from the local machine. + +### [Update-ModuleManifest](Update-ModuleManifest.md) +Updates a module manifest file. ### [Update-PSResource](Update-PSResource.md) -{{ Fill in the Description }} +Downloads and installs the newest version of a package already installed on the local machine. +### [Update-PSScriptFileInfo](Update-PSScriptFileInfo.md) +This cmdlet updates the comment-based metadata in an existing script `.ps1` file. diff --git a/help/Publish-PSResource.md b/help/Publish-PSResource.md index 22d95ea50..4bf3bc1c7 100644 --- a/help/Publish-PSResource.md +++ b/help/Publish-PSResource.md @@ -1,7 +1,8 @@ --- external help file: PowerShellGet.dll-Help.xml Module Name: PowerShellGet -online version: +ms.date: 08/03/2022 +online version: schema: 2.0.0 --- @@ -13,35 +14,41 @@ Publishes a specified module from the local computer to PSResource repository. ## SYNTAX ``` -Publish-PSResource [-APIKey ] [-Repository ] [-Path] [-DestinationPath] - [-Credential ] [-SkipDependenciesCheck] - [-WhatIf] [-Confirm] [] +Publish-PSResource -Path [-ApiKey ] [-Repository ] + [-DestinationPath ] [-Credential ] [-SkipDependenciesCheck] [-Proxy ] + [-ProxyCredential ] [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION -The Publish-PSResource cmdlet combines the Publish-Module and Publish-Script cmdlets from V2. -It publishes a specified resource from the local computer to an online Nuget-based gallery by using an API key, stored as part of a user's profile in the gallery or to a local repository. -You can specify the resource to publish either by the resource's name, or by the path to the folder containing the module or script resource. + +This cmdlet combines the functions of the `Publish-Module` and `Publish-Script` cmdlets from +**PowerShellGet** v2. `Publish-PSResource` publishes a resource from the local computer to an online +Nuget-based repository. You can specify the resource by the resource's name or by the path +containing the module or script resource. ## EXAMPLES ### Example 1 + +This example publishes the module **TestModule** to the repository registered with highest priority. + ```powershell -PS C:\> Publish-PSResource -Path c:\Test-Module +Publish-PSResource -Path c:\TestModule ``` -This will publish the module 'Test-Module' to the highest priority repository - ### Example 2 + +This example publishes the module **TestModule** to the PowerShell Gallery. The API key is a secret +that is generated by the PowerShell Gallery for a user account. + ```powershell -PS C:\> Publish-PSResource -Path c:\Test-Module -Repository PSGallery -APIKey '1234567' +Publish-PSResource -Path c:\TestModule -Repository PSGallery -APIKey '1234567' ``` -This will publish the module 'Test-Module' to the PowerShellGallery. Note that the API key is a secret that is generated for a user from the website itself. - ## PARAMETERS -### -APIKey +### -ApiKey + Specifies the API key that you want to use to publish a resource to the online gallery. ```yaml @@ -56,8 +63,27 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -Repository -Specifies the repository to publish to. +### -Credential + +Specifies a user account that has rights to a specific repository. + +```yaml +Type: System.Management.Automation.PSCredential +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -DestinationPath + +Specifies the path where the NuGet package `.nupkg` file should be saved. This parameter can be used +in conjunction with the **Repository** parameter to publish to a repository and also save the exact +same package to the local file system. ```yaml Type: System.String @@ -72,7 +98,9 @@ Accept wildcard characters: False ``` ### -Path -When specified, includes prerelease versions in search. + +The path to the module or script file or the path to a folder containing the module or script file +to be published. ```yaml Type: System.String @@ -86,23 +114,25 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -DestinationPath -Specifies the path to where the resource (as a nupkg) should be saved to. This parameter can be used in conjunction with the -Repository parameter to publish to a repository and also save the exact same package to the local file system. +### -Proxy + +The URL to a proxy server used to access repositories outside of your network. ```yaml -Type: System.String +Type: System.Uri Parameter Sets: (All) Aliases: -Required: True +Required: False Position: Named Default value: None -Accept pipeline input: True (ByPropertyName, ByValue) +Accept pipeline input: False Accept wildcard characters: False ``` -### -Credential -Specifies a user account that has rights to a specific repository (used for finding dependencies). +### -ProxyCredential + +The credentials required to use the proxy server. ```yaml Type: System.Management.Automation.PSCredential @@ -116,8 +146,25 @@ Accept pipeline input: False Accept wildcard characters: False ``` +### -Repository + +Specifies the repository to publish to. + +```yaml +Type: System.String +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + ### -SkipDependenciesCheck -Bypasses the default check that all dependencies are present on the repository which the resource is being published to. + +Bypasses the default check that all dependencies are present in the target repository. ```yaml Type: System.Management.Automation.SwitchParameter @@ -126,12 +173,13 @@ Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm + Prompts you for confirmation before running the cmdlet. ```yaml @@ -141,14 +189,14 @@ Aliases: cf Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf -Shows what would happen if the cmdlet runs. -The cmdlet is not run. + +Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter @@ -157,15 +205,21 @@ Aliases: wi Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, +-InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, +-WarningAction, and -WarningVariable. For more information, see +[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## NOTES -## RELATED LINKS +Fileshare-based repository have no metadata about the resources. Therefore, there is no way to check +for dependencies. +## RELATED LINKS diff --git a/help/Register-PSResourceRepository.md b/help/Register-PSResourceRepository.md index 9c7d3ac90..308be06ec 100644 --- a/help/Register-PSResourceRepository.md +++ b/help/Register-PSResourceRepository.md @@ -1,7 +1,8 @@ --- external help file: PowerShellGet.dll-Help.xml Module Name: PowerShellGet -online version: +ms.date: 08/03/2022 +online version: schema: 2.0.0 --- @@ -13,71 +14,142 @@ Registers a repository for PowerShell resources. ## SYNTAX ### NameParameterSet (Default) + ``` -Register-PSResourceRepository [-Name ] [-Uri ] [CredentialInfo ] [-Trusted] [-Priority ] [-PassThru] +Register-PSResourceRepository [-Name] [-Uri] [-Trusted] [-Priority ] + [-CredentialInfo ] [-Proxy ] [-ProxyCredential ] [-PassThru] [-WhatIf] [-Confirm] [] ``` ### PSGalleryParameterSet + ``` -Register-PSResourceRepository [-PSGallery] [-Trusted] [-Priority ] [-PassThru] [-WhatIf] [-Confirm] - [] +Register-PSResourceRepository -PSGallery [-Trusted] [-Priority ] [-Proxy ] + [-ProxyCredential ] [-PassThru] [-WhatIf] [-Confirm] [] ``` ### RepositoriesParameterSet + ``` -Register-PSResourceRepository -Repository [-PassThru] [-WhatIf] [-Confirm] [] +Register-PSResourceRepository -Repository [-Proxy ] + [-ProxyCredential ] [-PassThru] [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION -The Register-PSResourceRepository cmdlet registers a repository for PowerShell resources. + +The cmdlet registers a NuGet repository containing PowerShell resources. ## EXAMPLES ### Example 1 -``` -PS C:\> Register-PSResourceRepository -Name "PoshTestGallery" -Uri "https://www.powershellgallery.com/api/v2" -PS C:\> Get-PSResourceRepository -Name "PoshTestGallery" - Name Uri Trusted Priority - ---- --- ------- -------- - PoshTestGallery https://www.poshtestgallery.com/api/v2 False 50 + +This example registers the repository with the **Name** of `PoshTestGallery`. + +```powershell +Register-PSResourceRepository -Name PoshTestGallery -Uri "https://www.powershellgallery.com/api/v2" +Get-PSResourceRepository -Name PoshTestGallery ``` -This example registers the repository with the `-Name` of "PoshTestGallery" along with the associated `Uri` value for it. +```Output +Name Uri Trusted Priority +---- --- ------- -------- +PoshTestGallery https://www.poshtestgallery.com/api/v2 False 50 +``` ### Example 2 -``` -PS C:\> Register-PSResourceRepository -PSGallery -PS C:\> Get-PSResourceRepository -Name "PSGallery" - Name Uri Trusted Priority - ---- --- ------- -------- - PSGallery https://www.powershellgallery.com/api/v2 False 50 + +This example registers the default `PSGallery` repository. Unlike the previous example, we can't use +the **Name** and **Uri** parameters to register the `PSGallery` repository. The `PSGallery` +repository is registered by default but can be removed. Use this command to restore the default +registration. + +```powershell +Register-PSResourceRepository -PSGallery +Get-PSResourceRepository -Name "PSGallery" ``` -This example registers the "PSGallery" repository, with the 'PSGallery' parameter. Unlike the previous example, we cannot use the `-Name` or `-Uri` parameters to register the "PSGallery" repository as it is considered Powershell's default repository store and has its own value for Uri. +```Output +Name Uri Trusted Priority +---- --- ------- -------- +PSGallery https://www.powershellgallery.com/api/v2 False 50 +``` ### Example 3 + +This example registers multiple repositories at once. To do so, we use the **Repository** parameter +and provide an array of hashtables. Each hashtable can only have keys associated with parameters for +the **NameParameterSet** or the **PSGalleryParameterSet**. + +```powershell +$arrayOfHashtables = @{Name = "Local"; Uri = "D:/PSRepoLocal/"; Trusted = $true; Priority = 20 }, + @{Name = "PSGv3"; Uri = "https://www.powershellgallery.com/api/v3"; Trusted = $true; Priority = 50 }, + @{PSGallery = $true; Trusted = $true; Priority = 10 } +Register-PSResourceRepository -Repository $arrayOfHashtables +Get-PSResourceRepository ``` -PS C:\> $arrayOfHashtables = @{Name = "psgettestlocal"; Uri = "c:/code/testdir"}, @{PSGallery = $True} -PS C:\> Register-PSResourceRepository -Repository $arrayOfHashtables -PS C:\> Get-PSResourceRepository - Name Uri Trusted Priority - ---- --- ------- -------- - PSGallery https://www.powershellgallery.com/api/v2 False 50 - psgettestlocal file:///c:/code/testdir False 50 +```Output +Name Uri Trusted Priority +---- --- ------- -------- +PSGallery https://www.powershellgallery.com/api/v2 False 50 +psgettestlocal file:///c:/code/testdir False 50 ``` -This example registers multiple repositories at once. To do so, we use the `-Repository` parameter and provide an array of hashtables. Each hashtable can only have keys associated with parameters for the NameParameterSet or the PSGalleryParameterSet. Upon running the command we can see that the "psgettestlocal" and "PSGallery" repositories have been succesfully registered. +### Example 4 + +This example registers a repository with credential information to be retrieved from a registered +**Microsoft.PowerShell.SecretManagement** vault. You must have the +**Microsoft.PowerShell.SecretManagement** module install and have a registered vault containing the +stored secret. The format of the secret must match the requirements of the repository. + +```powershell +$parameters = @{ + Name = "PSGv3" + Uri = "https://www.powershellgallery.com/api/v3" + Trusted = $true + Priority = 50 + CredentialInfo = New-Object Microsoft.PowerShell.PowerShellGet.UtilClasses.PSCredentialInfo ('SecretStore', 'TestSecret') +} +Register-PSResourceRepository @parameters +Get-PSResourceRepository | Select-Object * -ExpandProperty CredentialInfo +``` + +```Output +Name : PSGv3 +Uri : https://www.powershellgallery.com/api/v3 +Trusted : True +Priority : 50 +CredentialInfo : Microsoft.PowerShell.PowerShellGet.UtilClasses.PSCredentialInfo +VaultName : SecretStore +SecretName : TestSecret +Credential : +``` ## PARAMETERS +### -CredentialInfo + +A **PSCredentialInfo** object that includes the name of a vault and a secret that is stored in a +**Microsoft.PowerShell.SecretManagement** store. + +```yaml +Type: PSCredentialInfo +Parameter Sets: NameParameterSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + ### -Name -Name of the repository to be registered. -Cannot be "PSGallery". + +Name of the repository to be registered. Can't be `PSGallery`. ```yaml -Type: String +Type: System.String Parameter Sets: NameParameterSet Aliases: @@ -88,12 +160,31 @@ Accept pipeline input: False Accept wildcard characters: False ``` +### -PassThru + +When specified, displays the successfully registered repository and its information. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + ### -Priority -Specifies the priority ranking of the repository. -Repositories with higher ranking priority are searched before a lower ranking priority one, when searching for a repository item across multiple registered repositories. Valid priority values range from 0 to 50, such that a lower numeric value (i.e 10) corresponds to a higher priority ranking than a higher numeric value (i.e 40). Has default value of 50. + +Specifies the priority ranking of the repository. Valid priority values range from 0 to 100. Lower +values have a higher priority ranking. The default value is `100`. + +Repositories are searched in priority order (highest first). ```yaml -Type: Int32 +Type: System.Int32 Parameter Sets: NameParameterSet, PSGalleryParameterSet Aliases: @@ -104,11 +195,44 @@ Accept pipeline input: False Accept wildcard characters: False ``` +### -Proxy + +The URL to a proxy server used to access repositories outside of your network. + +```yaml +Type: System.Uri +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -ProxyCredential + +The credentials required to use the proxy server. + +```yaml +Type: System.Management.Automation.PSCredential +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + ### -PSGallery -When specified, registers PSGallery repository. + +When specified, registers **PSGallery** repository. ```yaml -Type: SwitchParameter +Type: System.Management.Automation.SwitchParameter Parameter Sets: PSGalleryParameterSet Aliases: @@ -120,26 +244,30 @@ Accept wildcard characters: False ``` ### -Repository -Specifies an array of hashtables which contains repository information and is used to register multiple repositories at once. + +Specifies an array of hashtables that contain repository information. Use this parameter to register +multiple repositories at once. Each hashtable can only have keys associated with parameters for +the **NameParameterSet** or the **PSGalleryParameterSet**. ```yaml -Type: Hashtable[] +Type: System.Collections.Hashtable[] Parameter Sets: RepositoriesParameterSet Aliases: Required: True Position: Named Default value: None -Accept pipeline input: True (ByValue) +Accept pipeline input: False Accept wildcard characters: False ``` ### -Trusted + Specifies whether the repository should be trusted. ```yaml -Type: SwitchParameter -Parameter Sets: (All) +Type: System.Management.Automation.SwitchParameter +Parameter Sets: NameParameterSet, PSGalleryParameterSet Aliases: Required: False @@ -150,44 +278,33 @@ Accept wildcard characters: False ``` ### -Uri -Specifies the location of the repository to be registered. -Uri can be of the following Uri schemas: HTTPS, HTTP, FTP, file share based. -```yaml -Type: String -Parameter Sets: NameParameterSet -Aliases: - -Required: True -Position: 1 -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` -### -CredentialInfo -Specifies where a credential is stored to access the PSResourceRepository for Find/Install/Update commands. -Takes a PSCredentialInfo Objects which takes in a vault name and secret name. -This parameter utilizes the Microsoft.PowerShell.SecretManagement module for interfacing with the stored credential. +Specifies the location of the repository to be registered. The value must use one of the following +URI schemas: -`New-Object Microsoft.PowerShell.PowerShellGet.UtilClasses.PSCredentialInfo ("VaultName", "SecretName")` +- `https://` +- `http://` +- `ftp://` +- `file://` ```yaml -Type: PSCredentialInfo +Type: System.String Parameter Sets: NameParameterSet Aliases: -Required: False -Position: Named +Required: True +Position: 1 Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Confirm + Prompts you for confirmation before running the cmdlet. ```yaml -Type: SwitchParameter +Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf @@ -199,11 +316,11 @@ Accept wildcard characters: False ``` ### -WhatIf -Shows what would happen if the cmdlet runs. -The cmdlet is not run. + +Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml -Type: SwitchParameter +Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi @@ -214,23 +331,12 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -PassThru -When specified, displays the succcessfully registered repository and its information. - -```yaml -Type: SwitchParameter -Parameter Sets: (All) -Aliases: - -Required: False -Position: Named -Default value: None -Accept pipeline input: False -Accept wildcard characters: False -``` - ### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, +-InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, +-WarningAction, and -WarningVariable. For more information, see +[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS @@ -238,13 +344,16 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## OUTPUTS -### Microsoft.PowerShell.PowerShellGet.UtilClasses.PSRepositoryInfo (if 'PassThru' parameter is used) +### Microsoft.PowerShell.PowerShellGet.UtilClasses.PSRepositoryInfo -## NOTES -Repositories are unique by 'Name'. Attempting to register a repository with same 'Name' as an already registered repository will not successfully register. +By default, the cmdlet produces no output. When you use the **PassThru** parameter, the cmdlet +returns a **PSRepositoryInfo** object. -Registering the PSGallery repository must be done via the PSGalleryParameterSet (i.e by using the 'PSGallery' parameter instead of 'Name' and 'Uri' parameters). +## NOTES -Uri string input must be of one of the following Uri schemes: HTTP, HTTPS, FTP, File +Repositories are unique by **Name**. Attempting to register a repository with same name results in +an error. ## RELATED LINKS + +[Microsoft.PowerShell.SecretManagement](/powershell/utility-modules/secretmanagement/overview) diff --git a/help/Save-PSResource.md b/help/Save-PSResource.md index d8c1e30e3..2029fb6d4 100644 --- a/help/Save-PSResource.md +++ b/help/Save-PSResource.md @@ -1,7 +1,8 @@ --- external help file: PowerShellGet.dll-Help.xml Module Name: PowerShellGet -online version: +ms.date: 08/03/2022 +online version: schema: 2.0.0 --- @@ -13,94 +14,108 @@ Saves resources (modules and scripts) from a registered repository onto the mach ## SYNTAX ### NameParameterSet + ``` -Save-PSResource [-Name] [-Version ] [-Prerelease] [-Repository ] - [-Credential ] [-AsNupkg] [-IncludeXML] [-Path ] [-TrustRepository] [-SkipDependencyCheck] [-AuthenticodeCheck] [-PassThru] [-Quiet] [-WhatIf] [-Confirm] [] +Save-PSResource [-Name] [-Version ] [-Prerelease] [-Repository ] + [-Credential ] [-AsNupkg] [-IncludeXML] [-Path ] [-TrustRepository] + [-PassThru] [-SkipDependencyCheck] [-AuthenticodeCheck] [-Quiet] [-WhatIf] [-Confirm] + [] ``` ### InputObjectParameterSet + ``` -Save-PSResource [-InputObject] [-Credential ] [-AsNupkg] - [-IncludeXML] [-Path ] [-TrustRepository] [-SkipDependencyCheck] [-PassThru] [-Quiet] [-WhatIf] [-Confirm] [] +Save-PSResource [-InputObject] [-Credential ] [-AsNupkg] + [-IncludeXML] [-Path ] [-TrustRepository] [-PassThru] [-SkipDependencyCheck] + [-AuthenticodeCheck] [-Quiet] [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION -The Save-PSResource cmdlet combines the Save-Module and Save-Script cmdlets from V2. -It saves a resource from a registered repository to a specific path on a machine based on the -Name parameter argument. It does not return any object. Other parameters allow the resource to be specified by repository and version, and allow the user to save the resource as a .nupkg or with the PowerShellGet XML metadata. + +This cmdlet combines the functionality of the `Save-Module` and `Save-Script` cmdlets from +**PowerShellGet** v2. `Save-PSResource` downloads a resource from a registered repository to a +specific path on the local machine. By default, the resource is saved in the unpacked or installed +format. The scripts or modules could be run from the saved location. There is also an option to +download the resource in `.nupkg` format. ## EXAMPLES ### Example 1 + +Downloads the **Az** module from the highest priority repository and saves it to the current +location. + ```powershell -PS C:\> Save-PSResource -Name Az +Save-PSResource -Name Az ``` -Saves the Az module ### Example 2 + +Downloads the **Az** module from the PowerShell Gallery and saves it to the current location. + ```powershell -PS C:\> Save-PSResource -Name Az -Repository PSGallery +Save-PSResource -Name Az -Repository PSGallery ``` -Saves the Az module found in the PowerShellGallery ### Example 3 + +Downloads the **Az** module from the highest priority repository and saves it in `.nupkg` format to +the current location. + ```powershell -PS C:\> Save-PSResource Az -AsNupkg +Save-PSResource Az -AsNupkg ``` -Saves the Az module as a .nupkg file ### Example 4 + +Downloads the **Az** module from the highest priority repository and includes the **PowerShellGet** +XML metadata file. + ```powershell -PS C:\> Save-PSResource Az -IncludeXML +Save-PSResource Az -IncludeXML ``` -Saves the Az module and includes the PowerShellGet XML metadata ## PARAMETERS -### -Name -Name of a resource or resources to save. Does not accept wildcard characters or a null value. +### -AsNupkg + +Saves the resource as a `.nupkg` file. ```yaml -Type: System.String[] -Parameter Sets: NameParameterSet +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) Aliases: -Required: True -Position: 0 -Default value: None -Accept pipeline input: True (ByValue) +Required: False +Position: Named +Default value: False +Accept pipeline input: False Accept wildcard characters: False ``` -### -Version -Specifies the version of the resource to be saved. The value can be an exact version or a version -range using the NuGet versioning syntax. - -For more information about NuGet version ranges, see [Package versioning](/nuget/concepts/package-versioning#version-ranges) +### -AuthenticodeCheck -PowerShellGet supports all but the _minimum inclusive version_ listed in the NuGet version range -documentation. So inputting "1.0.0.0" as the version doesn't yield versions 1.0.0.0 and higher -(minimum inclusive range). Instead, the values is considered as the required version and yields -version 1.0.0.0 only (required version). To use the minimum inclusive range, provide `[1.0.0.0, ]` as -the version range. +Validates the resource's signed files and catalog files on Windows. ```yaml -Type: System.String -Parameter Sets: NameParameterSet +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` -### -Prerelease -Specifies to include prerelease versions. +### -Credential + +Optional credentials used when accessing a repository. ```yaml -Type: System.Management.Automation.SwitchParameter -Parameter Sets: NameParameterSet +Type: System.Management.Automation.PSCredential +Parameter Sets: (All) Aliases: Required: False @@ -110,53 +125,58 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -Repository -Specifies one or more repository names to search. -If not specified, search will include all currently registered repositories, in order of highest priority, until first repository package is found in. +### -IncludeXML + +Includes the **PowerShellGet** metadata XML used to verify that **PowerShellGet** has installed a +module. ```yaml -Type: System.String[] -Parameter Sets: NameParameterSet +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` -### -Credential -Optional credentials to be used when accessing a repository. +### -InputObject + +Used for pipeline input. ```yaml -Type: System.Management.Automation.PSCredential -Parameter Sets: (All) +Type: Microsoft.PowerShell.PowerShellGet.UtilClasses.PSResourceInfo +Parameter Sets: InputObjectParameterSet Aliases: -Required: False +Required: True Position: Named Default value: None -Accept pipeline input: False +Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` -### -AsNupkg -Saves the resource as a zipped .nupkg file. +### -Name + +The name of one or more resources to install. + ```yaml -Type: System.Management.Automation.SwitchParameter -Parameter Sets: (All) +Type: System.String[] +Parameter Sets: NameParameterSet Aliases: -Required: False -Position: Named +Required: True +Position: 0 Default value: None -Accept pipeline input: False +Accept pipeline input: True (ByValue) Accept wildcard characters: False ``` -### -IncludeXML -Includes the PowerShellGet metadata XML (used to verify that PowerShellGet has installed a module). +### -PassThru + +When specified, outputs a **PSResourceInfo** object for the saved resource. ```yaml Type: System.Management.Automation.SwitchParameter @@ -165,13 +185,15 @@ Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -Path -Specifies the path to save the resource to. + +Specifies the path to save the resource to. If no path is provided, the resource is saved to the +current location. ```yaml Type: System.String @@ -181,71 +203,84 @@ Aliases: Required: False Position: Named Default value: None -Accept pipeline input: True (ByPropertyName, ByValue) +Accept pipeline input: False Accept wildcard characters: False ``` -### -TrustRepository -Suppress prompts to trust repository. The prompt to trust repository only occurs if the repository is not already set to a trusted level. +### -Prerelease + +When specified, includes prerelease versions in search results returned. ```yaml Type: System.Management.Automation.SwitchParameter -Parameter Sets: (All) +Parameter Sets: NameParameterSet Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` -### -AuthenticodeCheck -Does a check to to validate signed files and catalog files on Windows. + +### -Quiet + +Supresses progress information. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) -Aliases: +Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` -### -PassThru -Passes the resource saved to the console. +### -Repository + +Specifies one or more repository names to search. Wildcards are supported. + +If not specified, search includes all registered repositories, in priority order (highest first), +until a repository is found that contains the package. + +Lower **Priority** values have a higher precedence. ```yaml -Type: System.Management.Automation.SwitchParameter -Parameter Sets: (All) +Type: System.String[] +Parameter Sets: NameParameterSet Aliases: Required: False Position: Named Default value: None Accept pipeline input: False -Accept wildcard characters: False +Accept wildcard characters: True ``` ### -SkipDependencyCheck -Skips the check for resource dependencies, so that only found resources are saved, and not any resources the found resource depends on. + +Skips the check for resource dependencies. Only found resources are installed. No resources of the +found resource are installed. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) -Aliases: +Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` -### -Quiet -Supresses progress information. +### -TrustRepository + +Suppress prompts to trust repository. The prompt to trust repository only occurs if the repository +isn't configured as trusted. ```yaml Type: System.Management.Automation.SwitchParameter @@ -254,18 +289,28 @@ Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` -### -InputObject -Used for pipeline input. +### -Version + +Specifies the version of the resource to be returned. The value can be an exact version or a version +range using the NuGet versioning syntax. + +For more information about NuGet version ranges, see +[Package versioning](/nuget/concepts/package-versioning#version-ranges). + +PowerShellGet supports all but the _minimum inclusive version_ listed in the NuGet version range +documentation. Using `1.0.0.0` as the version doesn't yield versions 1.0.0.0 and higher (minimum +inclusive range). Instead, the value is considered to be the required version. To search for a +minimum inclusive range, use `[1.0.0.0, ]` as the version range. ```yaml -Type: Microsoft.PowerShell.PowerShellGet.UtilClasses.PSResourceInfo -Parameter Sets: (All) -Aliases: wi +Type: System.String +Parameter Sets: NameParameterSet +Aliases: Required: False Position: Named @@ -275,6 +320,7 @@ Accept wildcard characters: False ``` ### -Confirm + Prompts you for confirmation before running the cmdlet. ```yaml @@ -284,14 +330,14 @@ Aliases: cf Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf -Shows what would happen if the cmdlet runs. -The cmdlet is not run. + +Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter @@ -300,16 +346,27 @@ Aliases: wi Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, +-InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, +-WarningAction, and -WarningVariable. For more information, see +[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS +## OUTPUTS + +### Microsoft.PowerShell.PowerShellGet.UtilClasses.PSResourceInfo + +By default, the cmdlet doesn't return any objects. When the **PassThru** parameter is used, the +cmdlet outputs a **PSResourceInfo** object for the saved resource. + ## NOTES ## RELATED LINKS diff --git a/help/Set-PSResourceRepository.md b/help/Set-PSResourceRepository.md index 658cb9174..1027234be 100644 --- a/help/Set-PSResourceRepository.md +++ b/help/Set-PSResourceRepository.md @@ -1,6 +1,7 @@ --- external help file: PowerShellGet.dll-Help.xml Module Name: PowerShellGet +ms.date: 08/03/2022 online version: schema: 2.0.0 --- @@ -13,71 +14,159 @@ Sets information for a registered repository. ## SYNTAX ### NameParameterSet (Default) + ``` -Set-PSResourceRepository [-Name] [-Uri ][CredentialInfo ] [-Trusted] [-Priority ] [-WhatIf] [-Confirm] [] +Set-PSResourceRepository [-Name] [-Uri ] [-Trusted] [-Priority ] + [-CredentialInfo ] [-PassThru] [-WhatIf] [-Confirm] [] ``` ### RepositoriesParameterSet + ``` -Set-PSResourceRepository -Repository [-Priority ] [-WhatIf] [-Confirm] [] +Set-PSResourceRepository -Repository [-PassThru] [-WhatIf] [-Confirm] + [] ``` ## DESCRIPTION + The Set-PSResourceRepository cmdlet sets information for a registered repository. ## EXAMPLES ### Example 1 + +In this example, the **Uri** for the **PoshTestGallery** repository has been registered. The +`Set-PSResourceRepository` cmdlet is used to change the **Uri** to a local path. The **PassThru** +parameter allows you to see the changed repository. + +```powershell +Get-PSResourceRepository -Name "PoshTestGallery" +``` + +```Output +Name Uri Trusted Priority +---- --- ------- -------- +PoshTestGallery https://www.poshtestgallery.com/api/v2 False 50 +``` + ```powershell -PS C:\> Get-PSResourceRepository -Name "PoshTestGallery" - Name Uri Trusted Priority - ---- --- ------- -------- - PoshTestGallery https://www.poshtestgallery.com/api/v2 False 50 -PS C:\> Set-PSResourceRepository -Name "PoshTestGallery" -Uri "c:/code/testdir" -PassThru - Name Uri Trusted Priority - ---- --- ------- -------- - PoshTestGallery file:///c:/code/testdir False 50 +Set-PSResourceRepository -Name "PoshTestGallery" -Uri "c:/code/testdir" -PassThru ``` -This example first checks if the PoshTestGallery repository has been registered. We wish to set the `-Uri` value of this repository by running the Set-PSResourceRepository cmdlet with the `-Uri` parameter and a valid Uri scheme Uri. We run the Get-PSResourceRepository cmdlet again to ensure that the `-Uri` of the repository was changed. We also use the `-PassThru` parameter to see the changed repository. +```Output +Name Uri Trusted Priority +---- --- ------- -------- +PoshTestGallery file:///c:/code/testdir False 50 +``` ### Example 2 + +This example changes the **Priority** and **Trusted** values of the repository. were changed. + +> [!NOTE] +> The **Uri** value of the default **PSGallery** repository can't be changed. + ```powershell -PS C:\> Get-PSResourceRepository -Name "PSGallery" - Name Uri Trusted Priority - ---- --- ------- -------- - PSGallery https://www.powershellgallery.com/api/v2 False 50 -PS C:\> Set-PSResourceRepository -Name "PSGallery" -Priority 25 -Trusted -PassThru - Name Uri Trusted Priority - ---- --- ------- -------- - PSGallery https://www.powershellgallery.com/api/v2 True 25 +Get-PSResourceRepository -Name "PSGallery" +``` + +```Output +Name Uri Trusted Priority +---- --- ------- -------- +PSGallery https://www.powershellgallery.com/api/v2 False 50 + +Set-PSResourceRepository -Name "PSGallery" -Priority 25 -Trusted -PassThru ``` -This example first checks if the PSGallery repository has been registered. We wish to set the `-Priority` and `-Trusted` values of this repository by running the Set-PSResourceRepository cmdlet with the `-Priority` parameter set to a value between 0 and 50 and by using the `-Trusted` parameter switch. We run the Get-PSResourceRepository cmdlet again to ensure that the `-Priority` and `-Trusted` values of the repository were changed. An important note here is that just for the default PSGallery repository, the `-Uri` value can't be changed/set. We also use the `-PassThru` parameter to see the changed repository. +```Output +Name Uri Trusted Priority +---- --- ------- -------- +PSGallery https://www.powershellgallery.com/api/v2 True 25 +``` ### Example 3 + +This example uses the **Repository** parameter to change values for multiple respositories. The +parameter takes an array of hashtables. Each hashtable contains information the repository being +updated. + ```powershell -PS C:\> Get-PSResourceRepository -Name "*" - Name Uri Trusted Priority - ---- --- ------- -------- - PSGallery https://www.powershellgallery.com/api/v2 False 50 - PoshTestGallery https://www.poshtestgallery.com/api/v2 False 50 +Get-PSResourceRepository +``` -PS C:\> $arrayOfHashtables = @{Name = "PSGallery"; Trusted = $True}, @{Name = "PoshTestGallery"; Uri = "c:/code/testdir"} +```Output +Name Uri Trusted Priority +---- --- ------- -------- +PSGallery https://www.powershellgallery.com/api/v2 False 50 +PoshTestGallery https://www.poshtestgallery.com/api/v2 False 50 +``` -PS C:\> Set-PSResourceRepository -Repository $arrayOfHashtables -PassThru - Name Uri Trusted Priority - ---- --- ------- -------- - PSGallery https://www.powershellgallery.com/api/v2 True 50 - PoshTestGallery file:///c:/code/testdir False 50 +```powershell +$arrayOfHashtables = @{Name = "PSGallery"; Trusted = $True}, + @{Name = "PoshTestGallery"; Uri = "c:/code/testdir"} +Set-PSResourceRepository -Repository $arrayOfHashtables -PassThru ``` -This example first checks for all registered repositories. We wish to set the properties for multiple repositories at once (i.e the PSGallery and PoshTestGallery repositories), so we run Set-PSResourceRepository with the `-Repository` parameter. This parameter takes an array of hashtables, where each hashtable contains information for a repository we wish to set information for. We also use the `-PassThru` parameter to see the changed repositories. +```Output +Name Uri Trusted Priority +---- --- ------- -------- +PSGallery https://www.powershellgallery.com/api/v2 True 50 +PoshTestGallery file:///c:/code/testdir False 50 +``` + +### Example 4 + +This example updates a repository with credential information to be retrieved from a registered +**Microsoft.PowerShell.SecretManagement** vault. You must have the +**Microsoft.PowerShell.SecretManagement** module install and have a registered vault containing the +stored secret. The format of the secret must match the requirements of the repository. + +```powershell +$parameters = @{ + Name = "PoshTestGallery" + Uri = "c:/code/testdir" + CredentialInfo = New-Object Microsoft.PowerShell.PowerShellGet.UtilClasses.PSCredentialInfo ('SecretStore', 'TestSecret') +} +Set-PSResourceRepository @parameters -PassThru | Select-Object * -ExpandProperty CredentialInfo +``` + +```Output +Name : PoshTestGallery +Uri : file:///c:/code/testdir +Trusted : False +Priority : 50 +CredentialInfo : Microsoft.PowerShell.PowerShellGet.UtilClasses.PSCredentialInfo +VaultName : SecretStore +SecretName : TestSecret +Credential : +``` ## PARAMETERS +### -CredentialInfo + +A **PSCredentialInfo** object that includes the name of a vault and a secret that is stored in a +**Microsoft.PowerShell.SecretManagement** store. + +```yaml +Type: Microsoft.PowerShell.PowerShellGet.UtilClasses.PSCredentialInfo +Parameter Sets: NameParameterSet +Aliases: + +Required: False +Position: Named +Default value: None +Accept pipeline input: False +Accept wildcard characters: False +``` + ### -Name -Specifies the name of the repository to be set. + +Specifies the name of the repository to be modified. + +> [!NOTE] +> The **Uri** value of the default **PSGallery** repository can't be changed. + ```yaml Type: System.String @@ -87,30 +176,35 @@ Aliases: Required: True Position: 0 Default value: None -Accept pipeline input: True (ByValue) +Accept pipeline input: True (ByValue, ByPropertyName) Accept wildcard characters: False ``` -### -Priority -Specifies the priority ranking of the repository, such that repositories with higher ranking priority are searched before a lower ranking priority one, when searching for a repository item across multiple registered repositories. Valid priority values range from 0 to 50, such that a lower numeric value (i.e 10) corresponds to a higher priority ranking than a higher numeric value (i.e 40). +### -PassThru + +When specified, displays the successfully registered repository and its information. ```yaml -Type: System.Int32 +Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` -### -Trusted -Specifies whether the repository should be trusted. +### -Priority + +Specifies the priority ranking of the repository. Valid priority values range from 0 to 50. Lower +values have a higher priority ranking. The default value is `50`. + +Repositories are searched in priority order (highest first). ```yaml -Type: System.Management.Automation.SwitchParameter +Type: System.Int32 Parameter Sets: NameParameterSet Aliases: @@ -121,46 +215,54 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -Uri -Specifies the location of the repository to be set. +### -Repository + +Specifies an array of hashtables that contain repository information. Use this parameter to register +multiple repositories at once. Each hashtable can only have keys associated with parameters for +the **NameParameterSet**. ```yaml -Type: String -Parameter Sets: NameParameterSet +Type: System.Collections.Hashtable[] +Parameter Sets: RepositoriesParameterSet Aliases: -Required: False +Required: True Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False ``` -### -CredentialInfo -Specifies where a credential is stored to access the PSResourceRepository for Find/Install/Update commands. -Takes a PSCredentialInfo Objects which takes in a vault name and secret name. -This parameter utilizes the Microsoft.PowerShell.SecretManagement module for interfacing with the stored credential. -`New-Object Microsoft.PowerShell.PowerShellGet.UtilClasses.PSCredentialInfo ("VaultName", "SecretName")` +### -Trusted + +Specifies whether the repository should be trusted. ```yaml -Type: PSCredentialInfo +Type: System.Management.Automation.SwitchParameter Parameter Sets: NameParameterSet Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` -### -PassThru -When specified, displays the succcessfully registered repository and its information +### -Uri + +Specifies the location of the repository to be registered. The value must use one of the following +URI schemas: + +- `https://` +- `http://` +- `ftp://` +- `file://` ```yaml -Type: System.Management.Automation.SwitchParameter -Parameter Sets: (All) -Aliases: cf +Type: System.String +Parameter Sets: NameParameterSet +Aliases: Required: False Position: Named @@ -170,6 +272,7 @@ Accept wildcard characters: False ``` ### -Confirm + Prompts you for confirmation before running the cmdlet. ```yaml @@ -179,14 +282,14 @@ Aliases: cf Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf -Shows what would happen if the cmdlet runs. -The cmdlet is not run. + +Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter @@ -195,13 +298,17 @@ Aliases: wi Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, +-InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, +-WarningAction, and -WarningVariable. For more information, see +[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS @@ -211,8 +318,13 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## OUTPUTS -### Microsoft.PowerShell.PowerShellGet.UtilClasses.PSRepositoryInfo (if 'PassThru' parameter used) +### Microsoft.PowerShell.PowerShellGet.UtilClasses.PSRepositoryInfo + +By default, the cmdlet produces no output. When you use the **PassThru** parameter, the cmdlet +returns a **PSRepositoryInfo** object. ## NOTES ## RELATED LINKS + +[Microsoft.PowerShell.SecretManagement](/powershell/utility-modules/secretmanagement/overview) diff --git a/help/Test-PSScriptFileInfo.md b/help/Test-PSScriptFileInfo.md index fb906a964..d05281d09 100644 --- a/help/Test-PSScriptFileInfo.md +++ b/help/Test-PSScriptFileInfo.md @@ -1,91 +1,56 @@ --- external help file: PowerShellGet-help.xml Module Name: PowerShellGet -online version: +ms.date: 08/03/2022 +online version: schema: 2.0.0 --- - # Test-PSScriptFileInfo ## SYNOPSIS - -Tests a .ps1 file at the specified path to ensure it is valid. +Tests the comment-based metadata in a `.ps1` file to ensure it's valid for publication. ## SYNTAX -### AllParameterSets +### __AllParameterSets ``` -Test-PSScriptFileInfo [-FilePath] [] +Test-PSScriptFileInfo [-FilePath] [] ``` ## DESCRIPTION -The Test-PSScriptFileInfo cmdlet tests a .ps1 file at the specified path to ensure it is valid. +This cmdlet tests the comment-based metadata in a `.ps1` file to ensure it's valid for publication +to a repository. ## EXAMPLES ### Example 1: Test a valid script -``` -PS C:\> New-PSScriptFileInfo -FilePath "C:\Users\johndoe\MyScripts\test_script.ps1" -Description "this is a test script" -PS C:\> Test-PSScriptFileInfo -FilePath "C:\Users\johndoe\MyScripts\test_script.ps1" -True -PS C:\> cat "C:\Users\johndoe\MyScripts\test_script.ps1" -<#PSScriptInfo - -.VERSION 1.0.0.0 - -.GUID 6ec3934e-a2e0-495b-9a9c-480e555ad1d1 - -.AUTHOR johndoe - -.COMPANYNAME - -.COPYRIGHT - -.TAGS - -.LICENSEURI - -.PROJECTURI - -.ICONURI - -.EXTERNALMODULEDEPENDENCIES - -.REQUIREDSCRIPTS - -.EXTERNALSCRIPTDEPENDENCIES - -.RELEASENOTES - - -.PRIVATEDATA - - -#> - -<# - -.DESCRIPTION -this is a test script - - -#> +This example creates a new script file then runs `Test-PSScriptFileInfo` to validate the metadata +in the script. +```powershell +New-PSScriptFileInfo -FilePath "C:\MyScripts\test_script.ps1" -Description "this is a test script" +Test-PSScriptFileInfo -FilePath "C:\MyScripts\test_script.ps1" +True ``` -Assume that the script file specified was created by the New-PSScriptFileInfo cmdlet prior to this example and is valid. This example runs the Test-PSScriptFileInfo cmdlet against a script located at the path provided to the 'FilePath' parameter. Since the script is a valid script the cmdlet outputs "True". To see what this valid script looks like we can see the contents of the file. - ### Example 2: Test an invalid script (missing Author) +This example runs the `Test-PSScriptFileInfo` cmdlet against a script file. The script is missing +the required **Author** metadata. The cmdlet writes a warning message and returns `$false`. +`Get-Content` is used to view the contents of the script file. + +```powershell +Test-PSScriptFileInfo -FilePath "C:\MyScripts\invalid_test_script.ps1" +Get-Content "C:\MyScripts\invalid_test_script.ps1" ``` -PS C:\> Test-PSScriptFileInfo -FilePath "C:\Users\johndoe\MyScripts\invalid_test_script.ps1" -WARNING: The .ps1 script file passed in was not valid due to: PSScript file is missing the required Author property -False -PS C:\> cat "C:\Users\johndoe\MyScripts\test_script.ps1" +```Output +WARNING: The .ps1 script file passed in was not valid due to: PSScript file is missing the required +Author property +False <#PSScriptInfo .VERSION 1.0.0.0 @@ -106,18 +71,16 @@ PS C:\> cat "C:\Users\johndoe\MyScripts\test_script.ps1" .ICONURI -.EXTERNALMODULEDEPENDENCIES +.EXTERNALMODULEDEPENDENCIES -.REQUIREDSCRIPTS +.REQUIREDSCRIPTS -.EXTERNALSCRIPTDEPENDENCIES +.EXTERNALSCRIPTDEPENDENCIES .RELEASENOTES - .PRIVATEDATA - #> <# @@ -125,48 +88,44 @@ PS C:\> cat "C:\Users\johndoe\MyScripts\test_script.ps1" .DESCRIPTION this is a test script - #> - ``` -This example runs the Test-PSScriptFileInfo cmdlet against a script located at the path provided to the 'FilePath' parameter. Since the script is not a valid script and is missing the required Author metadata property, the cmdlet writes an informative warning message and outputs "False". To see what this invalid script looks like we can see the contents of the file. - - ## PARAMETERS ### -FilePath -The path that the .ps1 script info file which is to be tested is located at. +The path to `.ps1` script file. ```yaml -Type: String +Type: System.String Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: True Position: 0 -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` - ### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, +-InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, +-WarningAction, and -WarningVariable. For more information, see +[about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None - - ## OUTPUTS -## NOTES +### System.Boolean +## NOTES ## RELATED LINKS +[New-PSScriptFileInfo](New-PSScriptFileInfo.md) diff --git a/help/Uninstall-PSResource.md b/help/Uninstall-PSResource.md index ba8b0073a..466f70ae8 100644 --- a/help/Uninstall-PSResource.md +++ b/help/Uninstall-PSResource.md @@ -1,6 +1,7 @@ --- external help file: PowerShellGet.dll-Help.xml Module Name: PowerShellGet +ms.date: 08/03/2022 online version: schema: 2.0.0 --- @@ -8,68 +9,115 @@ schema: 2.0.0 # Uninstall-PSResource ## SYNOPSIS -Uninstalls a resource (module or script) that has been installed on the machine via PowerShellGet. +Uninstalls a resource that was installed using **PowerShellGet**. ## SYNTAX -### NameParameterSet +### NameParameterSet (Default) + ``` -Uninstall-PSResource [-Name] [-Version ] [-Scope ] [-SkipDependencyCheck] [-WhatIf] [] +Uninstall-PSResource [-Name] [-Version ] [-Prerelease] [-SkipDependencyCheck] + [-Scope ] [-WhatIf] [-Confirm] [] ``` ### InputObjectParameterSet + ``` -Uninstall-PSResource [-InputObject] [-SkipDependencyCheck] [-WhatIf] [] +Uninstall-PSResource [-InputObject] [-Prerelease] [-SkipDependencyCheck] + [-Scope ] [-WhatIf] [-Confirm] [] ``` ## DESCRIPTION -The Uninstall-PSResource cmdlet combines the Uninstall-Module, Uninstall-Script cmdlets from V2. -It uninstalls a package found in a module or script installation path based on the -Name parameter argument. -It does not return an object. -Other parameters allow the returned results to be further filtered. + +This cmdlet combines the functionality of the `Uninstall-Module` and `Uninstall-Script` cmdlets from +**PowerShellGet** v2. The cmdlet searches the package installation paths for resources that have the +**PowerShellGet** XML metadata file. Matching resources are uninstalled from the system. + +By default, the cmdlet checks to see whether the resource being removed is a dependency for another +resource. ## EXAMPLES ### Example 1 + +Uninstall the latest version of the **Az** module. + ```powershell -PS C:\> Uninstall-PSResource Az +Uninstall-PSResource Az ``` -Uninstalls the latest version of the Az module. - ### Example 2 + +Uninstall a specific version of the **Az** module. + ```powershell -PS C:\> Uninstall-PSResource -name Az -version "1.0.0" +Uninstall-PSResource -name Az -version "5.0.0" ``` -Uninstalls version 1.0.0 of the Az module. - ### Example 3 + +Uninstalls all versions of the **Az** module within the specified version range. + ```powershell -PS C:\> Uninstall-PSResource -name Az -version "(1.0.0, 3.0.0)" +Uninstall-PSResource -name Az -version "(5.0.0, 7.5.0)" ``` -Uninstalls all versions within the specified version range. - ### Example 4 + +This example assumes that the following versions of **Az** module are already installed: + +- 4.0.1-preview +- 4.1.0 +- 4.0.2-preview + +The `Uninstall-PSResource` cmdlet removes stable and prerelease version that fall within the version +range specified. Per NuGetVersion rules, a prerelease version is less than a stable version, so +4.0.1-preview is actually less than the 4.0.1 version in the specified range. Therefore, +4.0.1-preview isn't removed. Versions 4.1.0 and 4.0.2-preview are removed because they fall within +the range. + ```powershell -PS C:\> Uninstall-PSResource -name Az -version "[4.0.1, 4.1.0]" +Uninstall-PSResource -name Az -version "[4.0.1, 4.1.0]" ``` -Assume that the following versions are already installed for package Az: 4.0.1-preview, 4.1.0, 4.0.2-preview installed, this will uninstall all versions (stable and prerelease) which fall within the specified version range. Per NuGetVersion rules, a prerelease version is less than a stable version, so 4.0.1-preview is actually less than the 4.0.1 specified version so 4.0.1-preview does not fall within the specified version range and won't be removed. Versions 4.1.0 and 4.0.2-preview do fall in the range and will both be removed. +### Example 5 + +This example assumes that the following versions of **Az** module are already installed: + +- 4.0.1-preview +- 4.1.0 +- 4.0.2-preview + +This is the same as the previous example except the **Prerelease** parameter means that only +prerelease versions are removed. Only version 4.0.2-preview is removed because version 4.0.1-preview +is outside the range and version 4.1.0 isn't a prerelease version. -### Example 4 ```powershell -PS C:\> Uninstall-PSResource -name Az -version "[4.0.1, 4.1.0]" -Prerelease +Uninstall-PSResource -name Az -version "[4.0.1, 4.1.0]" -Prerelease ``` -Assume that the following versions are already installed for package Az: 4.0.1-preview, 4.1.0, 4.0.2-preview installed. This is the same example as above, except the added `-Prerelease` parameter means only prerelease versions which fall within this range will be removed. Again, per NuGetVersion rules, a prerelease version is less than a stable version, so 4.0.1-preview is actually less than the 4.0.1 specified version. Therefore 4.0.1-preview does not fall within the specified version range and won't be removed. Version 4.1.0 does fall in range however it is not a prerelease version so it will remain installed. Version 4.0.2-preview does fall in the range and is prerelease so it will be removed. +## PARAMETERS +### -InputObject -## PARAMETERS +Used for pipeline input. + +```yaml +Type: Microsoft.PowerShell.PowerShellGet.UtilClasses.PSResourceInfo +Parameter Sets: InputObjectParameterSet +Aliases: + +Required: True +Position: Named +Default value: None +Accept pipeline input: True (ByValue) +Accept wildcard characters: False +``` ### -Name -Name of a resource or resources that has been installed. Accepts wild card characters. + +Name of a resource or resources to remove. Wildcards are supported but NuGet only accepts the `*` +character. ```yaml Type: System.String[] @@ -83,22 +131,24 @@ Accept pipeline input: True (ByValue) Accept wildcard characters: True ``` -### -Version -Specifies the version of the resource to be uninstalled. +### -Prerelease + +Indicates that only prerelease version resources should be removed. ```yaml -Type: System.String -Parameter Sets: NameParameterSet +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None -Accept pipeline input: True +Accept pipeline input: False Accept wildcard characters: False ``` ### -Scope + Specifies the scope of the resource to uninstall. ```yaml @@ -115,13 +165,40 @@ Accept wildcard characters: False ``` ### -SkipDependencyCheck -Skips check to see if other resources are dependent on the resource being uninstalled. + +By default, the cmdlet checks to see whether the resource being removed is a dependency for another +resource. Using this parameter skips the dependency test. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -Version + +Specifies the version of the resource to be removed. The value can be an exact version or a version +range using the NuGet versioning syntax. + +For more information about NuGet version ranges, see +[Package versioning](/nuget/concepts/package-versioning#version-ranges). + +PowerShellGet supports all but the _minimum inclusive version_ listed in the NuGet version range +documentation. Using `1.0.0.0` as the version doesn't yield versions 1.0.0.0 and higher (minimum +inclusive range). Instead, the value is considered to be the required version. To search for a +minimum inclusive range, use `[1.0.0.0, ]` as the version range. + +```yaml +Type: System.String +Parameter Sets: NameParameterSet +Aliases: + Required: False Position: Named Default value: None @@ -129,13 +206,14 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -InputObject -Used for pipeline input. +### -Confirm + +Prompts you for confirmation before running the cmdlet. ```yaml -Type: Microsoft.PowerShell.PowerShellGet.UtilClasses.PSResourceInfo +Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) -Aliases: wi +Aliases: cf Required: False Position: Named @@ -145,8 +223,8 @@ Accept wildcard characters: False ``` ### -WhatIf -Shows what would happen if the cmdlet runs. -The cmdlet is not run. + +Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter @@ -155,14 +233,26 @@ Aliases: wi Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, +-InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, +-WarningAction, and -WarningVariable. For more information, see +[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). + +## INPUTS + +## OUTPUTS ## NOTES ## RELATED LINKS + +[Package versioning](/nuget/concepts/package-versioning#version-ranges) + +[Install-PSResource](Install-PSResource.md) diff --git a/help/Unregister-PSResourceRepository.md b/help/Unregister-PSResourceRepository.md index d20f31944..c207918da 100644 --- a/help/Unregister-PSResourceRepository.md +++ b/help/Unregister-PSResourceRepository.md @@ -1,64 +1,95 @@ --- external help file: PowerShellGet.dll-Help.xml Module Name: PowerShellGet -online version: +ms.date: 08/03/2022 +online version: schema: 2.0.0 --- # Unregister-PSResourceRepository ## SYNOPSIS -Un-registers a repository from the repository store. +Removes a registered repository from the local machine. ## SYNTAX -### NameParameterSet +### __AllParameterSets + ``` -Unregister-PSResourceRepository [-Name] [-PassThru][-WhatIf] [-Confirm] [] +Unregister-PSResourceRepository [-Name] [-PassThru] [-WhatIf] [-Confirm] + [] ``` ## DESCRIPTION -The Unregister-PSResourceRepository cmdlet unregisters a repository. + +The cmdlet removes a registered repository from the the local machine. ## EXAMPLES ### Example 1 + +In this example removes the `PSGv3` repository from the local machine. + +```powershell +Get-PSResourceRepository ``` -PS C:\> Get-PSResourceRepository -Name "PoshTestGallery" -PS C:\> Unregister-PSResourceRepository -Name "PoshTestGallery" -PS C:\> Get-PSResourceRepository -Name "PoshTestGallery" -PS C:\> +```Output +Name Uri Trusted Priority +---- --- ------- -------- +PSGallery https://www.powershellgallery.com/api/v2 True 10 +Local file:///D:/PSRepoLocal/ True 20 +PSGv3 https://www.powershellgallery.com/api/v3 True 50 ``` -In this example, we assume the repository "PoshTestGallery" has been previously registered. So when we first run the command to find "PoshTestGallery" it verifies that this repository can be found. Next, we run the command to unregister "PoshTestGallery". Finally, we again run the command to find "PoshTestGallery" but since it was successfully un-registered it cannot be found or retrieved. +```powershell +Unregister-PSResourceRepository -Name PSGv3 +Get-PSResourceRepository +``` + +```Output +Name Uri Trusted Priority +---- --- ------- -------- +PSGallery https://www.powershellgallery.com/api/v2 True 10 +Local file:///D:/PSRepoLocal/ True 20 +``` ### Example 2 + +This example shows how to remove multiple registered repositories in a single command. The **Name** +parameter accepts an array containing the names of the repositories to remove. + +```powershell +Get-PSResourceRepository ``` -PS C:\> Get-PSResourceRepository - Name Uri Trusted Priority - ---- --- ------- -------- - PoshTestGallery https://www.poshtestgallery.com/api/v2 True 40 - PSGallery https://www.powershellgallery.com/api/v2 False 50 - psgettestlocal file:///c:/code/testdir True 50 - -PS C:\> Unregister-PSResourceRepository -Name "PoshTestGallery","psgettestlocal" -PS C:\> Get-PSResourceRepository - Name Uri Trusted Priority - ---- --- ------- -------- - PSGallery https://www.powershellgallery.com/api/v2 False 50 +```Output +Name Uri Trusted Priority +---- --- ------- -------- +PoshTestGallery https://www.poshtestgallery.com/api/v2 True 40 +PSGallery https://www.powershellgallery.com/api/v2 False 50 +psgettestlocal file:///c:/code/testdir True 50 ``` -In this example, the command to find all registered repositories is run and the repositories found are displayed. Next, the command to un-register is run with a list of names ("PoshTestGallery", "psgettestlocal") provided for the `-Name` parameter. Finally, the command to find all registered repositories is run again, but this time we can see that "PoshTestGallery" and "psgettestlocal" are not found and displayed as they have been successfully unregistered. +```powershell +Unregister-PSResourceRepository -Name PoshTestGallery, psgettestlocal +Get-PSResourceRepository +``` + +```Output +Name Uri Trusted Priority +---- --- ------- -------- +PSGallery https://www.powershellgallery.com/api/v2 False 50 +``` ## PARAMETERS ### -Name -This parameter takes a String argument, or an array of String arguments. It is the name of the repository to un-register. + +The name of one or more repositories to remove. ```yaml -Type: String[] +Type: System.String[] Parameter Sets: (All) Aliases: @@ -70,10 +101,11 @@ Accept wildcard characters: False ``` ### -PassThru -Passes the resource installed to the console. + +When specified, outputs a **PSRepositoryInfo** object for each repository that is removed. ```yaml -Type: SwitchParameter +Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: @@ -85,10 +117,11 @@ Accept wildcard characters: False ``` ### -Confirm + Prompts you for confirmation before running the cmdlet. ```yaml -Type: SwitchParameter +Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: cf @@ -100,11 +133,11 @@ Accept wildcard characters: False ``` ### -WhatIf -Shows what would happen if the cmdlet runs. -The cmdlet is not run. + +Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml -Type: SwitchParameter +Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: wi @@ -116,12 +149,25 @@ Accept wildcard characters: False ``` ### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, +-InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, +-WarningAction, and -WarningVariable. For more information, see +[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### System.String[] +## OUTPUTS + +### Microsoft.PowerShell.PowerShellGet.UtilClasses.PSRepositoryInfo + +By default, the cmdlet doesn't return any objects. When the **PassThru** parameter is used, the +cmdlet outputs a **PSRepositoryInfo** object for each repository that is removed. + ## NOTES ## RELATED LINKS + +[Register-PSResourceRepository](Register-PSResourceRepository.md) diff --git a/help/Update-ModuleManifest.md b/help/Update-ModuleManifest.md index 034e7a881..fa92c8339 100644 --- a/help/Update-ModuleManifest.md +++ b/help/Update-ModuleManifest.md @@ -1,6 +1,7 @@ --- external help file: PowerShellGet.dll-Help.xml Module Name: PowerShellGet +ms.date: 08/03/2022 online version: schema: 2.0.0 --- @@ -12,73 +13,82 @@ Updates a module manifest file. ## SYNTAX -### NameParameterSet (Default) +### __AllParameterSets + ``` -Update-ModuleManifest [-Path] [-NestedModules ] [-Guid ] [-Author ] - [-CompanyName ] [-Copyright ] [-RootModule ] [-ModuleVersion ] - [-Description ] [-ProcessorArchitecture ] [-CompatiblePSEditions ] - [-PowerShellVersion ] [-ClrVersion ] [-DotNetFrameworkVersion ] - [-PowerShellHostName ] [-PowerShellHostVersion ] [-RequiredModules ] - [-TypesToProcess ] [-FormatsToProcess ] [-ScriptsToProcess ] - [-RequiredAssemblies ] [-FileList ] [-ModuleList ] [-FunctionsToExport ] - [-AliasesToExport ] [-VariablesToExport ] [-CmdletsToExport ] - [-DscResourcesToExport ] [-PrivateData ] [-Tags ] [-ProjectUri ] - [-LicenseUri ] [-IconUri ] [-ReleaseNotes ] [-Prerelease ] [-HelpInfoUri ] - [-DefaultCommandPrefix ] [-ExternalModuleDependencies ] [-RequireLicenseAcceptance] - [] +Update-ModuleManifest [-Path] [-NestedModules ] [-Guid ] + [-Author ] [-CompanyName ] [-Copyright ] [-RootModule ] + [-ModuleVersion ] [-Description ] [-ProcessorArchitecture ] + [-CompatiblePSEditions ] [-PowerShellVersion ] [-ClrVersion ] + [-DotNetFrameworkVersion ] [-PowerShellHostName ] + [-PowerShellHostVersion ] [-RequiredModules ] [-TypesToProcess ] + [-FormatsToProcess ] [-ScriptsToProcess ] [-RequiredAssemblies ] + [-FileList ] [-ModuleList ] [-FunctionsToExport ] + [-AliasesToExport ] [-VariablesToExport ] [-CmdletsToExport ] + [-DscResourcesToExport ] [-Tags ] [-ProjectUri ] [-LicenseUri ] + [-IconUri ] [-ReleaseNotes ] [-Prerelease ] [-HelpInfoUri ] [-PassThru] + [-DefaultCommandPrefix ] [-ExternalModuleDependencies ] + [-RequireLicenseAcceptance] [-PrivateData ] [] ``` ## DESCRIPTION -The Update-ModuleManifest cmdlet replaces the Update-ModuleManifest cmdlet from V2. -It updates a module manifest based on the `-Path` parameter argument. -It does not return an object. Other parameters allow specific properties of the manifest to be updated. + +This cmdlet updates the data stored in a module manifest file. The parameters allow you to specify +which properties get updated. `Update-ModuleManifest` overwrites any existing values in the module +manifest. + +The cmdlet doesn't return an object. ## EXAMPLES ### Example 1 + +This example changes the **Author** property in the module manifest to `New Author`. + ```powershell -PS C:\> Update-ModuleManifest -Path "C:\MyModules\TestModule" -Author "New Author" +Update-ModuleManifest -Path "C:\MyModules\TestModule" -Author "New Author" ``` -In this example the author property in the module manifest will be updated to "New Author". ### Example 2 +This example changes the **Prerelease** property to `beta2`. + ```powershell -PS C:\> Update-ModuleManifest -Path "C:\MyModules\TestModule" -Prerelease "beta2" +Update-ModuleManifest -Path "C:\MyModules\TestModule" -Prerelease "beta2" ``` -In this example the prerelease property will be updated to "beta2" ### Example 3 +This example updates multiple properties. + ```powershell -PS C:\> Update-ModuleManifest -Path "C:\MyModules\TestModule" -Tags "Windows", "Linux" -Description "A module for managing packages." +Update-ModuleManifest -Path "C:\MyModules\TestModule" -Tags "Windows", "Linux" -Description "A module for managing packages." ``` -In this example the tags and description will be updated to the passed in values. ## PARAMETERS -### -Path -Specifies the path and file name of the module manifest. Enter a path and file name with a .psd1 file name extension, such as `"$PSHOME\Modules\MyModule\MyModule.psd1`. +### -AliasesToExport + +Specifies the aliases that the module exports. Wildcards are permitted. ```yaml -Type: String +Type: System.String[] Parameter Sets: (All) Aliases: -Required: True -Position: 0 +Required: False +Position: Named Default value: None -Accept pipeline input: True -Accept wildcard characters: False +Accept pipeline input: False +Accept wildcard characters: True ``` -### -NestedModules -Specifies script modules (.psm1) and binary modules (.dll) that are imported into the module's session state. The files in the NestedModules key run in the order in which they're listed in the value. +### -Author -Enter each module name as a string or as a hash table with ModuleName and ModuleVersion keys. The hash table can also have an optional GUID key. You can combine strings and hash tables in the parameter value. +Specifies the module author. ```yaml -Type: Object[] +Type: System.String Parameter Sets: (All) Aliases: @@ -89,11 +99,13 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -Guid -Specifies a unique identifier for the module. The GUID can be used to distinguish among modules with the same name. +### -ClrVersion + +Specifies the minimum version of the Common Language Runtime (CLR) of the Microsoft .NET Framework +required by the module. ```yaml -Type: System.Guid +Type: System.Version Parameter Sets: (All) Aliases: @@ -104,11 +116,12 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -Author -Specifies the module author. +### -CmdletsToExport + +Specifies the cmdlets that the module exports. Wildcards are permitted. ```yaml -Type: String +Type: System.String[] Parameter Sets: (All) Aliases: @@ -116,14 +129,15 @@ Required: False Position: Named Default value: None Accept pipeline input: False -Accept wildcard characters: False +Accept wildcard characters: True ``` ### -CompanyName -Specifies the company or vendor who created the module. + +Specifies the company or vendor who created the module. ```yaml -Type: String +Type: System.String Parameter Sets: (All) Aliases: @@ -134,13 +148,16 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -Copyright -Specifies a copyright statement for the module. +### -CompatiblePSEditions + +Specifies the compatible **PSEditions** of the module. For information about **PSEdition**, see +[Modules with compatible PowerShell Editions](/powershell/scripting/gallery/concepts/module-psedition-support). ```yaml -Type: String +Type: System.String[] Parameter Sets: (All) Aliases: +Accepted values: Desktop, Core Required: False Position: Named @@ -149,12 +166,9 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -RootModule -Specifies the primary or root file of the module. Enter the file name of a script (.ps1), a script module (.psm1), a module manifest (.psd1), an assembly (.dll), a cmdlet definition XML file (.cdxml), or a workflow (.xaml). When the module is imported, the members that are exported from the root module file are imported into the caller's session state. - -If a module has a manifest file and no root file has been specified in the RootModule key, the manifest becomes the primary file for the module. And, the module becomes a manifest module (ModuleType = Manifest). +### -Copyright -To export members from .psm1 or .dll files in a module that has a manifest, the names of those files must be specified in the values of the RootModule or NestedModules keys in the manifest. Otherwise, their members aren't exported. +Specifies a copyright statement for the module. ```yaml Type: System.String @@ -168,11 +182,12 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -ModuleVersion -Specifies the version of the module. +### -DefaultCommandPrefix + +Specifies the default command prefix. ```yaml -Type: System.Version +Type: System.String Parameter Sets: (All) Aliases: @@ -184,6 +199,7 @@ Accept wildcard characters: False ``` ### -Description + Specifies a description of the module. ```yaml @@ -198,22 +214,14 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -ProcessorArchitecture -Specifies the processor architecture that the module requires. - -The acceptable values for this parameter are: +### -DotNetFrameworkVersion -* Amd64 -* Arm -* IA64 -* MSIL -* None (unknown or unspecified) -* X86 +Specifies the minimum version of the Microsoft .NET Framework required by the module. ```yaml -Type: System.Reflection.ProcessorArchitecture +Type: System.Version Parameter Sets: (All) -Aliases: +Aliases: Required: False Position: Named @@ -222,27 +230,29 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -CompatiblePSEditions -Specifies the compatible PSEditions of the module. For information about PSEdition, see: https://docs.microsoft.com/en-us/powershell/scripting/gallery/concepts/module-psedition-support +### -DscResourcesToExport + +Specifies the Desired State Configuration (DSC) resources that the module exports. Wildcards are +permitted. ```yaml Type: System.String[] Parameter Sets: (All) Aliases: -Accepted Values: Desktop, Core Required: False Position: Named Default value: None Accept pipeline input: False -Accept wildcard characters: False +Accept wildcard characters: True ``` -### -PowerShellVersion -Specifies the minimum version of PowerShell that will work with this module. For example, you can specify 3.0, 4.0, or 5.0 as the value of this parameter. +### -ExternalModuleDependencies + +Specifies an array of external module dependencies. ```yaml -Type: System.Version +Type: System.String[] Parameter Sets: (All) Aliases: @@ -253,11 +263,12 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -ClrVersion -Specifies the minimum version of the Common Language Runtime (CLR) of the Microsoft .NET Framework that the module requires. +### -FileList + +Specifies all items that are included in the module. ```yaml -Type: System.Version +Type: System.String[] Parameter Sets: (All) Aliases: @@ -268,11 +279,15 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -DotNetFrameworkVersion -Specifies the minimum version of the Microsoft .NET Framework that the module requires. +### -FormatsToProcess + +Specifies the formatting files (`.ps1xml`) that are processed when the module is imported. + +When you import a module, PowerShell runs the `Update-FormatData` cmdlet with the specified files. +Because formatting files aren't scoped, they affect all session states in the session. ```yaml -Type: System.Version +Type: System.String[] Parameter Sets: (All) Aliases: @@ -283,13 +298,12 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -PowerShellHostName -Specifies the name of the PowerShell host program that the module requires. Enter the name of the host program, such as PowerShell ISE Host or ConsoleHost. Wildcards aren't permitted. +### -FunctionsToExport -To find the name of a host program, in the program, type $Host.Name. +Specifies the functions that the module exports. Wildcards are permitted. ```yaml -Type: System.String +Type: System.String[] Parameter Sets: (All) Aliases: @@ -297,14 +311,16 @@ Required: False Position: Named Default value: None Accept pipeline input: False -Accept wildcard characters: False +Accept wildcard characters: True ``` -### -PowerShellHostVersion -Specifies the minimum version of the PowerShell host program that works with the module. Enter a version number, such as 1.1. +### -Guid + +Specifies a unique identifier for the module. The **GUID** is used to distinguish between modules +with the same name. ```yaml -Type: System.Version +Type: System.Guid Parameter Sets: (All) Aliases: @@ -315,11 +331,16 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -RequiredModules -Specifies modules that must be in the global session state. If the required modules aren't in the global session state, PowerShell imports them. If the required modules aren't available, the Import-Module command fails. +### -HelpInfoUri + +Specifies the internet address of the module's HelpInfo XML file. Enter a Uniform Resource +Identifier (URI) that begins with `http:` or `https:`. + +For more information, see +[Updatable Help](/powershell/module/microsoft.powershell.core/about/about_updatable_help). ```yaml -Type: System.Object[] +Type: System.Uri Parameter Sets: (All) Aliases: @@ -330,13 +351,13 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -TypesToProcess -Specifies the type files (.ps1xml) that run when the module is imported. +### -IconUri -When you import the module, PowerShell runs the Update-TypeData cmdlet with the specified files. Because type files aren't scoped, they affect all session states in the session. +Specifies the URI of an icon for the module. The specified icon is displayed on the gallery web page +for the module. ```yaml -Type: System.String[] +Type: System.Uri Parameter Sets: (All) Aliases: @@ -347,14 +368,12 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -FormatsToProcess -Specifies the formatting files (.ps1xml) that run when the module is imported. - -When you import a module, PowerShell runs the Update-FormatData cmdlet with the specified files. Because formatting files aren't scoped, they affect all session states in the session. +### -LicenseUri +Specifies the URL of licensing terms for the module. ```yaml -Type: System.String[] +Type: System.Uri Parameter Sets: (All) Aliases: @@ -365,13 +384,18 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -ScriptsToProcess -Specifies script (.ps1) files that run in the caller's session state when the module is imported. You can use these scripts to prepare an environment, just as you might use a login script. +### -ModuleList -To specify scripts that run in the module's session state, use the NestedModules key. +Specifies an array of modules that are included in the module. + +Enter each module name as a string or as a hashtable with **ModuleName** and **ModuleVersion** keys. +The hashtable can also have an optional **GUID** key. You can combine strings and hashtables in the +parameter value. + +This key is designed to act as a module inventory. ```yaml -Type: System.String[] +Type: System.Object[] Parameter Sets: (All) Aliases: @@ -382,13 +406,12 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -RequiredAssemblies -Specifies the assembly (.dll) files that the module requires. Enter the assembly file names. PowerShell loads the specified assemblies before updating types or formats, importing nested modules, or importing the module file that is specified in the value of the RootModule key. +### -ModuleVersion -Use this parameter to specify all the assemblies that the module requires, including assemblies that must be loaded to update any formatting or type files that are listed in the FormatsToProcess or TypesToProcess keys, even if those assemblies are also listed as binary modules in the NestedModules key. +Specifies the version of the module. ```yaml -Type: System.String[] +Type: System.Version Parameter Sets: (All) Aliases: @@ -399,11 +422,17 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -FileList -Specifies all items that are included in the module. - +### -NestedModules + +Specifies script modules (`.psm1`) and binary modules (`.dll`) that are imported into the module's +session state. The files in the **NestedModules** key run in the order in which they're listed. + +Enter each module name as a string or as a hashtable with **ModuleName** and **ModuleVersion** keys. +The hashtable can also have an optional **GUID** key. You can combine strings and hashtables in the +parameter value. + ```yaml -Type: System.String[] +Type: System.Object[] Parameter Sets: (All) Aliases: @@ -414,15 +443,10 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -ModuleList -Specifies an array of modules that are included in the module. - -Enter each module name as a string or as a hash table with ModuleName and ModuleVersion keys. The hash table can also have an optional GUID key. You can combine strings and hash tables in the parameter value. +### -PassThru -This key is designed to act as a module inventory. The modules that are listed in the value of this key aren't automatically processed. - ```yaml -Type: System.String[] +Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: @@ -433,30 +457,32 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -FunctionsToExport -Specifies the functions that the module exports. Wildcards are permitted. +### -Path + +Specifies the path and filename of the module manifest. Enter filename with a `.psd1` file +extension. -Use this parameter to restrict the functions that are exported by the module. FunctionsToExport can remove functions from the list of exported aliases, but it can't add functions to the list. - ```yaml -Type: System.String[] +Type: System.String Parameter Sets: (All) Aliases: -Required: False -Position: Named +Required: True +Position: 0 Default value: None Accept pipeline input: False -Accept wildcard characters: True +Accept wildcard characters: False ``` -### -AliasesToExport -Specifies the aliases that the module exports. Wildcards are permitted. +### -PowerShellHostName + +Specifies the name of the PowerShell host program that the module requires. Enter the name of the +host program, such as PowerShell ISE Host or ConsoleHost. Wildcards aren't permitted. + +The name of a host program is stored in `$Host.Name`. -Use this parameter to restrict the aliases that are exported by the module. AliasesToExport can remove aliases from the list of exported aliases, but it can't add aliases to the list. - ```yaml -Type: System.String[] +Type: System.String Parameter Sets: (All) Aliases: @@ -464,16 +490,16 @@ Required: False Position: Named Default value: None Accept pipeline input: False -Accept wildcard characters: True +Accept wildcard characters: False ``` -### -VariablesToExport -Specifies the variables that the module exports. Wildcards are permitted. +### -PowerShellHostVersion + +Specifies the minimum version of the PowerShell host program that works with the module. Enter a +version number, such as 1.1. -Use this parameter to restrict the variables that are exported by the module. VariablesToExport can remove variables from the list of exported variables, but it can't add variables to the list. - ```yaml -Type: System.String[] +Type: System.Version Parameter Sets: (All) Aliases: @@ -481,16 +507,16 @@ Required: False Position: Named Default value: None Accept pipeline input: False -Accept wildcard characters: True +Accept wildcard characters: False ``` -### -CmdletsToExport -Specifies the cmdlets that the module exports. Wildcards are permitted. +### -PowerShellVersion + +Specifies the minimum version of PowerShell that works with this module. For example, you can +specify versions such as `5.1` or `7.2`. -Use this parameter to restrict the cmdlets that are exported by the module. CmdletsToExport can remove cmdlets from the list of exported cmdlets, but it can't add cmdlets to the list. - ```yaml -Type: System.String[] +Type: System.Version Parameter Sets: (All) Aliases: @@ -498,14 +524,17 @@ Required: False Position: Named Default value: None Accept pipeline input: False -Accept wildcard characters: True +Accept wildcard characters: False ``` -### -DscResourcesToExport -Specifies the Desired State Configuration (DSC) resources that the module exports. Wildcards are permitted. - +### -Prerelease + +Specifies the prerelease value that is appended to the module version. For example, if +**Prerelease** is `preview` and the **ModuleVersion** is `1.0.0`, the version of the module is +`1.0.0-preview`. + ```yaml -Type: System.String[] +Type: System.String Parameter Sets: (All) Aliases: @@ -513,14 +542,16 @@ Required: False Position: Named Default value: None Accept pipeline input: False -Accept wildcard characters: True +Accept wildcard characters: False ``` ### -PrivateData -Specifies data that is passed to the module when it's imported. - + +Specifies data that is passed to the module when it's imported. This can be any arbitrary values +stored in a hashtable. + ```yaml -Type: Hashtable +Type: System.Collections.Hashtable Parameter Sets: (All) Aliases: @@ -531,11 +562,21 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -Tags -Specifies an array of tags. - +### -ProcessorArchitecture + +Specifies the processor architecture that the module requires. + +The acceptable values for this parameter are: + +- `Amd64` +- `Arm` +- `IA64` +- `MSIL` +- `None` (unknown or unspecified) +- `X86` + ```yaml -Type: System.String[] +Type: System.Reflection.ProcessorArchitecture Parameter Sets: (All) Aliases: @@ -547,10 +588,11 @@ Accept wildcard characters: False ``` ### -ProjectUri -Specifies the URL of a web page about this project. - + +Specifies the URI of a web page about this project. + ```yaml -Type: Uri +Type: System.Uri Parameter Sets: (All) Aliases: @@ -561,11 +603,12 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -LicenseUri -Specifies the URL of licensing terms for the module. - +### -ReleaseNotes + +Specifies a string that contains release notes or comments for the module. + ```yaml -Type: Uri +Type: System.String Parameter Sets: (All) Aliases: @@ -576,11 +619,18 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -IconUri -Specifies the URL of an icon for the module. The specified icon is displayed on the gallery web page for the module. - +### -RequiredAssemblies + +Specifies the assembly (`.dll`) files required by the module. PowerShell loads the specified +assemblies before updating types or formats, importing nested modules, or importing the module file +specified in the **RootModule** key. + +Use **RequiredAssemblies** for assemblies that must be loaded to update any formatting or type files +that are listed in the **FormatsToProcess** or **TypesToProcess** keys, even if those assemblies are +also listed in the **NestedModules** key. + ```yaml -Type: Uri +Type: System.String[] Parameter Sets: (All) Aliases: @@ -591,11 +641,24 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -ReleaseNotes -Specifies a string array that contains release notes or comments that you want available for this version of the script. - +### -RequiredModules + +Specifies modules that must be in the global session state. If the required modules aren't in the +global session state, PowerShell imports them. If the required modules aren't available, the +`Import-Module` command fails. + +The value can be an array containing module names or module specifications. A module specification +is a hashtable that has the following keys. + +- **ModuleName** - Required Specifies the module name. +- **GUID** - Optional Specifies the GUID of the module. +- One of these three version key is Required. These keys can't be used together. + - **ModuleVersion** - Specifies a minimum acceptable version of the module. + - **RequiredVersion** - Specifies an exact, required version of the module. + - **MaximumVersion** - Specifies the maximum acceptable version of the module. + ```yaml -Type: System.String[] +Type: System.Object[] Parameter Sets: (All) Aliases: @@ -606,8 +669,35 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -Prerelease -Specifies the prerelease tag that is appended to the module version. For example, if prerelease is "preview" and the module version is "1.0.0" the version of the module would be "1.0.0-preview". +### -RequireLicenseAcceptance + +Specifies that a license acceptance is required for the module. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) +Aliases: + +Required: False +Position: Named +Default value: False +Accept pipeline input: False +Accept wildcard characters: False +``` + +### -RootModule + +Specifies the primary or root file of the module. Enter the file name of a script (`.ps1`), a script +module (`.psm1`), a module manifest (`.psd1`), an assembly (`.dll`), or a cmdlet definition XML file +(`.cdxml`). When the module is imported, the members exported from the root module are imported into +the caller's session state. + +If a module has a manifest file and no file is specified in the **RootModule** key, the manifest +becomes the primary file for the module. The module is known as a manifest module (**ModuleType** = +`Manifest`). + +To export members from `.psm1` or `.dll` files, the names of those files must be specified in the +values of the **RootModule** or **NestedModules** keys in the manifest. ```yaml Type: System.String @@ -621,15 +711,15 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -HelpInfoUri -Specifies the internet address of the module's HelpInfo XML file. Enter a Uniform Resource Identifier (URI) that begins with http or https. +### -ScriptsToProcess -The HelpInfo XML file supports the Updatable Help feature that was introduced in PowerShell version 3.0. It contains information about the location of the module's downloadable help files and the version numbers of the newest help files for each supported locale. +Specifies script (`.ps1`) files that run in the caller's session state when the module is imported. +You can use these scripts to prepare an environment, just as you might use a login script. -For information about Updatable Help, see: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_updatable_help?view=powershell-7.2. For information about the HelpInfo XML file, see: https://docs.microsoft.com/en-us/powershell/scripting/developer/module/supporting-updatable-help. +To specify scripts that run in the module's session state, use the **NestedModules** key. ```yaml -Type: Uri +Type: System.String[] Parameter Sets: (All) Aliases: @@ -640,11 +730,12 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -DefaultCommandPrefix -Specifies the default command prefix. +### -Tags + +Specifies an array of tags. ```yaml -Type: System.String +Type: System.String[] Parameter Sets: (All) Aliases: @@ -655,8 +746,12 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -ExternalModuleDependencies -Specifies an array of external module dependencies. +### -TypesToProcess + +Specifies the type files (`.ps1xml`) that run when the module is imported. + +When you import the module, PowerShell runs the `Update-TypeData` cmdlet with the specified files. +Because type files aren't scoped, they affect all session states in the session. ```yaml Type: System.String[] @@ -670,11 +765,14 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -RequireLicenseAcceptance -Specifies that a license acceptance is required for the module. +### -VariablesToExport + +Specifies the variables that the module exports. Wildcards are permitted. + +Use this parameter to restrict which variables that are exported by the module. ```yaml -Type: System.Management.Automation.SwitchParameter +Type: System.String[] Parameter Sets: (All) Aliases: @@ -682,11 +780,15 @@ Required: False Position: Named Default value: None Accept pipeline input: False -Accept wildcard characters: False +Accept wildcard characters: True ``` ### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, +-InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, +-WarningAction, and -WarningVariable. For more information, see +[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS @@ -696,4 +798,9 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## NOTES +For a full description of the module manifest file, see +[about_Module_Manifests](/powershell/module/microsoft.powershell.core/about/about_module_manifests). + ## RELATED LINKS + +[New-ModuleManifest](/powershell/module/microsoft.powershell.core/new-modulemanifest) diff --git a/help/Update-PSResource.md b/help/Update-PSResource.md index 1471e002a..bdfa732ad 100644 --- a/help/Update-PSResource.md +++ b/help/Update-PSResource.md @@ -1,6 +1,7 @@ --- external help file: PowerShellGet.dll-Help.xml Module Name: PowerShellGet +ms.date: 08/03/2022 online version: schema: 2.0.0 --- @@ -8,46 +9,63 @@ schema: 2.0.0 # Update-PSResource ## SYNOPSIS -Updates a package already installed on the user's machine. +Downloads and installs the newest version of a package already installed on the local machine. ## SYNTAX -### NameParameterSet (Default) +### __AllParameterSets + ``` -Update-PSResource [-Name] [-Version ] [-Prerelease] [-Repository ] - [-Scope ] [-TrustRepository] [-Credential ] [-Quiet] [-AcceptLicense] [-Force] [-PassThru] [-AuthenticodeCheck] [-SkipDependencyCheck] [-WhatIf] [-Confirm] [] +Update-PSResource [[-Name] ] [-Version ] [-Prerelease] [-Repository ] + [-Scope ] [-TrustRepository] [-Credential ] [-Quiet] [-AcceptLicense] + [-Force] [-PassThru] [-SkipDependencyCheck] [-AuthenticodeCheck] [-WhatIf] [-Confirm] + [] ``` ## DESCRIPTION -The Update-PSResource cmdlet replaces the Update-Module and Update-Script cmdlets from V2. -It updates an already installed package based on the `-Name` parameter argument. -It does not return an object. Other parameters allow the package to be updated to be further filtered. + +`Update-PSResource` downloads and installs the newest version of a package already installed on the +local machine. This cmdlet replaces the `Update-Module` and `Update-Script` cmdlets from +**PowerShellGet** v2. The new version of the resource is installed side-by-side with previous +versions in a new versioned folder. + +By default, `Update-PSResource` installs the latest version of the package and any of its +dependencies without deleting the older versions installed. ## EXAMPLES ### Example 1 -```powershell -PS C:\> Update-PSResource -Name "TestModule" - Name Version Prerelease Description - ---- ------- ---------- ----------- - TestModule 1.2.0 test -PS C:\> Update-PSResource -Name "TestModule" +In this example, the user already has the **TestModule** package installed and they update the +package. -PS C:\> Update-PSResource -Name "TestModule" - Name Version Prerelease Description - ---- ------- ---------- ----------- - TestModule 1.3.0 test - TestModule 1.2.0 test +```powershell +Get-PSResource -Name "TestModule" +``` +```Output +Name Version Prerelease Description +---- ------- ---------- ----------- +TestModule 1.2.0 test ``` -In this example, the user already has the TestModule package installed and they update the package. Update-PSResource will install the latest version of the package without deleting the older version installed. +```powershell +Update-PSResource -Name "TestModule" +``` + +```Output +Name Version Prerelease Description +---- ------- ---------- ----------- +TestModule 1.3.0 test +TestModule 1.2.0 test +``` ## PARAMETERS ### -AcceptLicense -For resources that require a license, AcceptLicense automatically accepts the license agreement during the update. + +For resources that require a license, **AcceptLicense** automatically accepts the license agreement +during the update. ```yaml Type: System.Management.Automation.SwitchParameter @@ -56,47 +74,34 @@ Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` -### -Credential -Specifies optional credentials to be used when accessing a private repository. +### -AuthenticodeCheck + +Validates signed files and catalog files on Windows. ```yaml -Type: System.Management.Automation.PSCredential -Parameter Sets: NameParameterSet +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` -### -Name -Specifies name of a resource or resources to update. - -```yaml -Type: System.String[] -Parameter Sets: NameParameterSet -Aliases: - -Required: True -Position: 0 -Default value: "*" -Accept pipeline input: True (ByPropertyName, ByValue) -Accept wildcard characters: True -``` +### -Credential -### -Prerelease -When specified, allows updating to a prerelease version. +Specifies optional credentials used when accessing a private repository. ```yaml -Type: System.Management.Automation.SwitchParameter -Parameter Sets: NameParameterSet +Type: System.Management.Automation.PSCredential +Parameter Sets: (All) Aliases: Required: False @@ -106,8 +111,10 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -Quiet -Supresses progress information. +### -Force + +When specified, bypasses checks for **TrustRepository** and **AcceptLicense** and updates the +package. ```yaml Type: System.Management.Automation.SwitchParameter @@ -116,45 +123,64 @@ Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` -### -Repository -Specifies one or more repository names to update packages from. -If not specified, search for packages to update will include all currently registered repositories in order of highest priority. +### -Name + +Specifies the name of one or more resources to update. Wildcards are supported but NuGet only +accepts the `*` character. NuGet does not support wildcard searches of local (file-based) +repositories. ```yaml Type: System.String[] -Parameter Sets: NameParameterSet +Parameter Sets: (All) +Aliases: + +Required: False +Position: 0 +Default value: "*" +Accept pipeline input: True (ByPropertyName, ByValue) +Accept wildcard characters: True +``` + +### -PassThru + +When specified, outputs a **PSResourceInfo** object for the saved resource. + +```yaml +Type: System.Management.Automation.SwitchParameter +Parameter Sets: (All) Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` -### -Scope -Specifies the scope of the resource to update. +### -Prerelease + +When specified, allows updating to a prerelease version. ```yaml -Type: Microsoft.PowerShell.PowerShellGet.UtilClasses.ScopeType +Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) Aliases: -Accepted values: CurrentUser, AllUsers Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` -### -TrustRepository -Specifies optional credentials to be used when accessing a private repository. +### -Quiet + +Supresses progress information. ```yaml Type: System.Management.Automation.SwitchParameter @@ -163,42 +189,46 @@ Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` -### -Version -Specifies the version of the resource to be updated to. The value can be an exact version or a version -range using the NuGet versioning syntax. +### -Repository -For more information about NuGet version ranges, see [Package versioning](/nuget/concepts/package-versioning#version-ranges) +Specifies one or more repository names to search. Wildcards are supported. -PowerShellGet supports all but the _minimum inclusive version_ listed in the NuGet version range -documentation. So inputting "1.0.0.0" as the version doesn't yield versions 1.0.0.0 and higher -(minimum inclusive range). Instead, the values is considered as the required version and yields -version 1.0.0.0 only (required version). To use the minimum inclusive range, provide `[1.0.0.0, ]` as -the version range. +If not specified, search includes all registered repositories, in priority order (highest first), +until a repository is found that contains the package. + +Lower **Priority** values have a higher precedence. ```yaml -Type: System.String -Parameter Sets: NameParameterSet +Type: System.String[] +Parameter Sets: (All) Aliases: Required: False Position: Named Default value: None Accept pipeline input: False -Accept wildcard characters: False +Accept wildcard characters: True ``` -### -Force -When specified, bypasses checks for TrustRepository and AcceptLicense and updates the package. +### -Scope + +Specifies the installation scope. Accepted values are: + +- `CurrentUser` +- `AllUsers` + +The default scope is `CurrentUser`, which doesn't require elevation. ```yaml -Type: System.Management.Automation.SwitchParameter +Type: Microsoft.PowerShell.PowerShellGet.UtilClasses.ScopeType Parameter Sets: (All) -Aliases: +Aliases: +Accepted values: CurrentUser, AllUsers Required: False Position: Named @@ -207,8 +237,9 @@ Accept pipeline input: False Accept wildcard characters: False ``` -### -PassThru -Passes the resource updated to the console. +### -SkipDependencyCheck + +Skips the check for resource dependencies. This means that only named resources are updated. ```yaml Type: System.Management.Automation.SwitchParameter @@ -217,30 +248,43 @@ Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` -### -AuthenticodeCheck -Does a check to to validate signed files and catalog files on Windows. + +### -TrustRepository + +Suppress prompts to trust repository. The prompt to trust repository only occurs if the repository +isn't configured as trusted. ```yaml Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) -Aliases: +Aliases: Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` -### -SkipdependencyCheck -Skips the check for resource dependencies, so that only found resources are updated, and not any resources the found resource depends on. +### -Version + +Specifies the version of the resource to be returned. The value can be an exact version or a version +range using the NuGet versioning syntax. + +For more information about NuGet version ranges, see +[Package versioning](/nuget/concepts/package-versioning#version-ranges). + +PowerShellGet supports all but the _minimum inclusive version_ listed in the NuGet version range +documentation. Using `1.0.0.0` as the version doesn't yield versions 1.0.0.0 and higher (minimum +inclusive range). Instead, the value is considered to be the required version. To search for a +minimum inclusive range, use `[1.0.0.0, ]` as the version range. ```yaml -Type: System.Management.Automation.SwitchParameter +Type: System.String Parameter Sets: (All) Aliases: @@ -252,6 +296,7 @@ Accept wildcard characters: False ``` ### -Confirm + Prompts you for confirmation before running the cmdlet. ```yaml @@ -261,14 +306,14 @@ Aliases: cf Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### -WhatIf -Shows what would happen if the cmdlet runs. -The cmdlet is not run. + +Shows what would happen if the cmdlet runs. The cmdlet isn't run. ```yaml Type: System.Management.Automation.SwitchParameter @@ -277,13 +322,17 @@ Aliases: wi Required: False Position: Named -Default value: None +Default value: False Accept pipeline input: False Accept wildcard characters: False ``` ### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). + +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, +-InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, +-WarningAction, and -WarningVariable. For more information, see +[about_CommonParameters](https://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS @@ -291,8 +340,13 @@ This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable ## OUTPUTS +### Microsoft.PowerShell.PowerShellGet.UtilClasses.PSResourceInfo + +By default, the cmdlet doesn't return any objects. When the **PassThru** parameter is used, the +cmdlet outputs a **PSResourceInfo** object for the saved resource. + ## NOTES ## RELATED LINKS -[]() +[Install-PSResource](Install-PSResource.md) diff --git a/help/Update-PSScriptFileInfo.md b/help/Update-PSScriptFileInfo.md index 28fa2957e..e2ea6848c 100644 --- a/help/Update-PSScriptFileInfo.md +++ b/help/Update-PSScriptFileInfo.md @@ -1,36 +1,49 @@ --- external help file: PowerShellGet-help.xml Module Name: PowerShellGet -online version: +ms.date: 08/03/2022 +online version: schema: 2.0.0 --- # Update-PSScriptFileInfo ## SYNOPSIS - -Updates an existing .ps1 file with requested properties and ensures it's valid +This cmdlet updates the comment-based metadata in an existing script `.ps1` file. ## SYNTAX ### __AllParameterSets ``` -Update-PSScriptFileInfo [-FilePath] [-Author ] [-CompanyName ] [-Copyright ] [-Description ] [-ExternalModuleDependencies ] [-ExternalScriptDependencies ] [-Guid ] [-IconUri ] [-LicenseUri ] [-PrivateData ] [-ProjectUri ] [-ReleaseNotes ] [-RemoveSignature] [-RequiredModules ] [-RequiredScripts ] [-Tags ] [-Version ] [] +Update-PSScriptFileInfo [-FilePath] [-Author ] [-CompanyName ] + [-Copyright ] [-Description ] [-ExternalModuleDependencies ] + [-ExternalScriptDependencies ] [-Guid ] [-IconUri ] + [-LicenseUri ] [-PrivateData ] [-ProjectUri ] [-ReleaseNotes ] + [-RemoveSignature] [-RequiredModules ] [-RequiredScripts ] + [-Tags ] [-Version ] [] ``` ## DESCRIPTION -The Update-PSScriptFileInfo cmdlet updates an existing .ps1 file with requested properties and ensures it's valid. +This cmdlet updates the comment-based metadata in an existing script `.ps1` file. This is similar to +`Update-ModuleManifest`. ## EXAMPLES ### Example 1: Update the version of a script +In this example, a script is created with **Version** set to `1.0.0.0`. `Update-PSScriptFileInfo` +changes the **Version**' to `2.0.0.0`. The `Get-Content` cmdlet shows the updated contents of the +script. + +```powershell +New-PSScriptFileInfo -FilePath "C:\Users\johndoe\MyScripts\test_script.ps1" -Version "1.0.0.0" -Description "this is a test script" +Update-PSScriptFileInfo -FilePath "C:\Users\johndoe\MyScripts\test_script.ps1" -Version "2.0.0.0" +Get-Content "C:\Users\johndoe\MyScripts\test_script.ps1" ``` -PS C:\> New-PSScriptFileInfo -FilePath "C:\Users\johndoe\MyScripts\test_script.ps1" -Version "1.0.0.0" -Description "this is a test script" -PS C:\> Update-PSScriptFileInfo -FilePath "C:\Users\johndoe\MyScripts\test_script.ps1" -Version "2.0.0.0" -PS C:\> cat "C:\Users\johndoe\MyScripts\test_script.ps1" + +```Output <#PSScriptInfo .VERSION 2.0.0.0 @@ -51,18 +64,17 @@ PS C:\> cat "C:\Users\johndoe\MyScripts\test_script.ps1" .ICONURI -.EXTERNALMODULEDEPENDENCIES +.EXTERNALMODULEDEPENDENCIES -.REQUIREDSCRIPTS +.REQUIREDSCRIPTS -.EXTERNALSCRIPTDEPENDENCIES +.EXTERNALSCRIPTDEPENDENCIES .RELEASENOTES .PRIVATEDATA - #> <# @@ -70,28 +82,24 @@ PS C:\> cat "C:\Users\johndoe\MyScripts\test_script.ps1" .DESCRIPTION this is a test script - #> ``` -In this example a script is created by running the New-PSScriptFileInfo cmdlet with version specified as 1.0.0.0. To update the script's version to 2.0.0.0, the Update-PSScriptFileInfo cmdlet is run with 'Version' specified as "2.0.0.0". Given that the cmdlet completed running without errors and by looking at the contents of the updated file we see the version was updated to 2.0.0.0. - ## PARAMETERS ### -Author -The author of the script. +The name of the author of the script. ```yaml -Type: String +Type: System.String Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` @@ -101,14 +109,13 @@ Accept wildcard characters: False The name of the company owning the script. ```yaml -Type: String +Type: System.String Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` @@ -118,14 +125,13 @@ Accept wildcard characters: False The copyright information for the script. ```yaml -Type: String +Type: System.String Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` @@ -135,14 +141,13 @@ Accept wildcard characters: False The description of the script. ```yaml -Type: String +Type: System.String Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` @@ -152,14 +157,13 @@ Accept wildcard characters: False The list of external module dependencies taken by this script. ```yaml -Type: String[] +Type: System.String[] Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` @@ -169,82 +173,77 @@ Accept wildcard characters: False The list of external script dependencies taken by this script. ```yaml -Type: String[] +Type: System.String[] Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -FilePath -The path the .ps1 script info file will be created at. +The filename and location of the script. ```yaml -Type: String +Type: System.String Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: True Position: 0 -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Guid -The GUID for the script. +The unique identifier for the script in GUID format. ```yaml -Type: Guid +Type: System.Guid Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -IconUri -The Uri for the icon associated with the script. +A Uniform Resource Identifier (URI) pointing to the icon associated with the script. ```yaml -Type: String +Type: System.String Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -LicenseUri -The Uri for the license associated with the script. +The URI pointing to the license agreement file associated with the script. ```yaml -Type: String +Type: System.String Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` @@ -254,31 +253,29 @@ Accept wildcard characters: False The private data associated with the script. ```yaml -Type: String +Type: System.String Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -ProjectUri -The Uri for the project associated with the script. +The URI pointing to the project site associated with the script. ```yaml -Type: String +Type: System.String Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` @@ -288,48 +285,54 @@ Accept wildcard characters: False The release notes for the script. ```yaml -Type: String[] +Type: System.String Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RemoveSignature -Remove signature from signed .ps1 (if present) thereby allowing update of script to happen. User should re-sign the updated script afterwards. +Removes the signature from a signed `.ps1` file, allowing you to update the script. You should +re-sign the after updating the file. ```yaml -Type: SwitchParameter +Type: System.Management.Automation.SwitchParameter Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -RequiredModules -The list of modules required by the script. +The parameter takes an array of module specification hashtables. A module specification is a +hashtable that has the following keys. + +- **ModuleName** - Required Specifies the module name. +- **GUID** - Optional Specifies the GUID of the module. +- One of these three version key is Required. These keys can't be used together. + - **ModuleVersion** - Specifies a minimum acceptable version of the module. + - **RequiredVersion** - Specifies an exact, required version of the module. + - **MaximumVersion** - Specifies the maximum acceptable version of the module. ```yaml -Type: Hashtable[] +Type: System.Collections.Hashtable[] Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` @@ -339,31 +342,30 @@ Accept wildcard characters: False The list of scripts required by the script. ```yaml -Type: String[] +Type: System.String[] Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` ### -Tags -The tags associated with the script. +The tags associated with the script. Tag values are strings that should not contain spaces. For more +information, see [Tag details][1]. ```yaml -Type: String[] +Type: System.String[] Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` @@ -373,34 +375,42 @@ Accept wildcard characters: False The version of the script. ```yaml -Type: String +Type: System.String Parameter Sets: (All) -Aliases: -Accepted values: +Aliases: Required: False Position: Named -Default value: +Default value: None Accept pipeline input: False Accept wildcard characters: False ``` - ### CommonParameters -This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, -InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, -WarningAction, and -WarningVariable. For more information, see [about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). +This cmdlet supports the common parameters: -Debug, -ErrorAction, -ErrorVariable, +-InformationAction, -InformationVariable, -OutVariable, -OutBuffer, -PipelineVariable, -Verbose, +-WarningAction, and -WarningVariable. For more information, see +[about_CommonParameters](http://go.microsoft.com/fwlink/?LinkID=113216). ## INPUTS ### None +## OUTPUTS +### System.Object -## OUTPUTS +## NOTES -### None +## RELATED LINKS +[PowerShellGallery Publishing Guidelines and Best Practices][2] +[Package manifest values that impact the PowerShell Gallery UI][3] -## NOTES + +[1]: /powershell/scripting/gallery/concepts/package-manifest-affecting-ui#tag-details +[2]: /powershell/scripting/gallery/concepts/publishing-guidelines +[3]: /powershell/scripting/gallery/concepts/package-manifest-affecting-ui diff --git a/help/en-US/PowerShellGet.dll-Help.xml b/help/en-US/PowerShellGet.dll-Help.xml index 6eb948e70..0afb8205c 100644 --- a/help/en-US/PowerShellGet.dll-Help.xml +++ b/help/en-US/PowerShellGet.dll-Help.xml @@ -1933,7 +1933,7 @@ Priority - Specifies the priority ranking of the repository. Repositories with higher ranking priority are searched before a lower ranking priority one, when searching for a repository item across multiple registered repositories. Valid priority values range from 0 to 50, such that a lower numeric value (i.e 10) corresponds to a higher priority ranking than a higher numeric value (i.e 40). Has default value of 50. + Specifies the priority ranking of the repository. Repositories with higher ranking priority are searched before a lower ranking priority one, when searching for a repository item across multiple registered repositories. Valid priority values range from 0 to 100, such that a lower numeric value (i.e 10) corresponds to a higher priority ranking than a higher numeric value (i.e 40). Has default value of 50. Int32 @@ -2406,7 +2406,7 @@ PS C:\> Get-PSResourceRepository False - IncludeXML + IncludeXml Includes the PowerShellGet metadata XML (used to verify that PowerShellGet has installed a module). @@ -2594,7 +2594,7 @@ PS C:\> Get-PSResourceRepository False - IncludeXML + IncludeXml Includes the PowerShellGet metadata XML (used to verify that PowerShellGet has installed a module). @@ -2745,7 +2745,7 @@ PS C:\> Get-PSResourceRepository -------------------------- Example 4 -------------------------- - PS C:\> Save-PSResource Az -IncludeXML + PS C:\> Save-PSResource Az -IncludeXml Saves the Az module and includes the PowerShellGet XML metadata @@ -2788,7 +2788,7 @@ PS C:\> Get-PSResourceRepository Priority - Specifies the priority ranking of the repository, such that repositories with higher ranking priority are searched before a lower ranking priority one, when searching for a repository item across multiple registered repositories. Valid priority values range from 0 to 50, such that a lower numeric value (i.e 10) corresponds to a higher priority ranking than a higher numeric value (i.e 40). + Specifies the priority ranking of the repository, such that repositories with higher ranking priority are searched before a lower ranking priority one, when searching for a repository item across multiple registered repositories. Valid priority values range from 0 to 100, such that a lower numeric value (i.e 10) corresponds to a higher priority ranking than a higher numeric value (i.e 40). System.Int32 @@ -2884,7 +2884,7 @@ PS C:\> Get-PSResourceRepository Priority - Specifies the priority ranking of the repository, such that repositories with higher ranking priority are searched before a lower ranking priority one, when searching for a repository item across multiple registered repositories. Valid priority values range from 0 to 50, such that a lower numeric value (i.e 10) corresponds to a higher priority ranking than a higher numeric value (i.e 40). + Specifies the priority ranking of the repository, such that repositories with higher ranking priority are searched before a lower ranking priority one, when searching for a repository item across multiple registered repositories. Valid priority values range from 0 to 100, such that a lower numeric value (i.e 10) corresponds to a higher priority ranking than a higher numeric value (i.e 40). System.Int32 @@ -3026,7 +3026,7 @@ PS C:\> Set-PSResourceRepository -Name "PSGallery" -Priority 25 -Trusted -Pas ---- --- ------- -------- PSGallery https://www.powershellgallery.com/api/v2 True 25 - This example first checks if the PSGallery repository has been registered. We wish to set the `-Priority` and `-Trusted` values of this repository by running the Set-PSResourceRepository cmdlet with the `-Priority` parameter set to a value between 0 and 50 and by using the `-Trusted` parameter switch. We run the Get-PSResourceRepository cmdlet again to ensure that the `-Priority` and `-Trusted` values of the repository were changed. An important note here is that just for the default PSGallery repository, the `-Uri` value can't be changed/set. We also use the `-PassThru` parameter to see the changed repository. + This example first checks if the PSGallery repository has been registered. We wish to set the `-Priority` and `-Trusted` values of this repository by running the Set-PSResourceRepository cmdlet with the `-Priority` parameter set to a value between 0 and 100 and by using the `-Trusted` parameter switch. We run the Get-PSResourceRepository cmdlet again to ensure that the `-Priority` and `-Trusted` values of the repository were changed. An important note here is that just for the default PSGallery repository, the `-Uri` value can't be changed/set. We also use the `-PassThru` parameter to see the changed repository. diff --git a/src/code/GetPSResource.cs b/src/code/GetPSResource.cs index 453555d53..6a167eca1 100644 --- a/src/code/GetPSResource.cs +++ b/src/code/GetPSResource.cs @@ -14,6 +14,7 @@ namespace Microsoft.PowerShell.PowerShellGet.Cmdlets /// Returns a single resource or multiple resource. /// [Cmdlet(VerbsCommon.Get, "PSResource")] + [OutputType(typeof(PSResourceInfo))] public sealed class GetPSResource : PSCmdlet { #region Members diff --git a/src/code/GetPSResourceRepository.cs b/src/code/GetPSResourceRepository.cs index 54eaa8ecb..8000c5445 100644 --- a/src/code/GetPSResourceRepository.cs +++ b/src/code/GetPSResourceRepository.cs @@ -16,6 +16,7 @@ namespace Microsoft.PowerShell.PowerShellGet.Cmdlets /// It returns PSRepositoryInfo objects which describe each resource item found. /// [Cmdlet(VerbsCommon.Get, "PSResourceRepository")] + [OutputType(typeof(PSRepositoryInfo))] public sealed class GetPSResourceRepository : PSCmdlet { #region Parameters diff --git a/src/code/InstallHelper.cs b/src/code/InstallHelper.cs index 515cdd762..75f6d54f2 100644 --- a/src/code/InstallHelper.cs +++ b/src/code/InstallHelper.cs @@ -47,7 +47,7 @@ internal class InstallHelper : PSCmdlet private bool _trustRepository; private PSCredential _credential; private bool _asNupkg; - private bool _includeXML; + private bool _includeXml; private bool _noClobber; private bool _authenticodeCheck; private bool _savePkg; @@ -78,14 +78,14 @@ public List InstallPackages( bool noClobber, PSCredential credential, bool asNupkg, - bool includeXML, + bool includeXml, bool skipDependencyCheck, bool authenticodeCheck, bool savePkg, List pathsToInstallPkg) { _cmdletPassedIn.WriteVerbose(string.Format("Parameters passed in >>> Name: '{0}'; Version: '{1}'; Prerelease: '{2}'; Repository: '{3}'; " + - "AcceptLicense: '{4}'; Quiet: '{5}'; Reinstall: '{6}'; TrustRepository: '{7}'; NoClobber: '{8}'; AsNupkg: '{9}'; IncludeXML '{10}'; SavePackage '{11}'", + "AcceptLicense: '{4}'; Quiet: '{5}'; Reinstall: '{6}'; TrustRepository: '{7}'; NoClobber: '{8}'; AsNupkg: '{9}'; IncludeXml '{10}'; SavePackage '{11}'", string.Join(",", names), versionRange != null ? (versionRange.OriginalString != null ? versionRange.OriginalString : string.Empty) : string.Empty, prerelease.ToString(), @@ -96,7 +96,7 @@ public List InstallPackages( trustRepository.ToString(), noClobber.ToString(), asNupkg.ToString(), - includeXML.ToString(), + includeXml.ToString(), savePkg.ToString())); _versionRange = versionRange; @@ -110,7 +110,7 @@ public List InstallPackages( _noClobber = noClobber; _credential = credential; _asNupkg = asNupkg; - _includeXML = includeXML; + _includeXml = includeXml; _savePkg = savePkg; _pathsToInstallPkg = pathsToInstallPkg; @@ -155,6 +155,7 @@ private List ProcessRepositories( var findHelper = new FindHelper(_cancellationToken, _cmdletPassedIn); List allPkgsInstalled = new List(); + bool sourceTrusted = true; foreach (var repo in listOfRepositories) { @@ -166,7 +167,6 @@ private List ProcessRepositories( // Source is only trusted if it's set at the repository level to be trusted, -TrustRepository flag is true, -Force flag is true // OR the user issues trust interactively via console. - var sourceTrusted = true; if (repo.Trusted == false && !trustRepository && !_force) { _cmdletPassedIn.WriteVerbose("Checking if untrusted repository should be used"); @@ -246,9 +246,9 @@ private List ProcessRepositories( // At this only package names left were those which could not be found in registered repositories foreach (string pkgName in _pkgNamesToInstall) { - var message = String.Format("Package '{0}' with requested version range {1} could not be installed as it was not found in any registered repositories", - pkgName, - _versionRange.ToString()); + string message = !sourceTrusted ? $"Package '{pkgName}' with requested version range '{_versionRange.ToString()}' could not be found in any trusted repositories" : + $"Package '{pkgName}' with requested version range '{_versionRange.ToString()}' could not be installed as it was not found in any registered repositories"; + var ex = new ArgumentException(message); var ResourceNotFoundError = new ErrorRecord(ex, "ResourceNotFoundError", ErrorCategory.ObjectNotFound, null); _cmdletPassedIn.WriteError(ResourceNotFoundError); @@ -557,7 +557,7 @@ private List InstallPackage( // Delete the extra nupkg related files that are not needed and not part of the module/script DeleteExtraneousFiles(pkgIdentity, tempDirNameVersion); - if (_includeXML) + if (_includeXml) { CreateMetadataXMLFile(tempDirNameVersion, installPath, pkg, isModule); } @@ -774,7 +774,7 @@ private void DeleteExtraneousFiles(PackageIdentity pkgIdentity, string dirNameVe var nupkgSHAToDelete = Path.Combine(dirNameVersion, pkgIdString + ".nupkg.sha512"); var nuspecToDelete = Path.Combine(dirNameVersion, pkgIdentity.Id + ".nuspec"); var nupkgToDelete = Path.Combine(dirNameVersion, pkgIdString + ".nupkg"); - var nupkgMetadataToDelete = Path.Combine(dirNameVersion, pkgIdString + ".nupkg.metadata"); + var nupkgMetadataToDelete = Path.Combine(dirNameVersion, ".nupkg.metadata"); var contentTypesToDelete = Path.Combine(dirNameVersion, "[Content_Types].xml"); var relsDirToDelete = Path.Combine(dirNameVersion, "_rels"); var packageDirToDelete = Path.Combine(dirNameVersion, "package"); diff --git a/src/code/InstallPSResource.cs b/src/code/InstallPSResource.cs index cb9bb3510..4149a2ba5 100644 --- a/src/code/InstallPSResource.cs +++ b/src/code/InstallPSResource.cs @@ -524,7 +524,7 @@ private void ProcessInstallHelper(string[] pkgNames, VersionRange pkgVersion, bo noClobber: NoClobber, credential: pkgCredential, asNupkg: false, - includeXML: true, + includeXml: true, skipDependencyCheck: SkipDependencyCheck, authenticodeCheck: AuthenticodeCheck, savePkg: false, diff --git a/src/code/PSRepositoryInfo.cs b/src/code/PSRepositoryInfo.cs index d5fbebb25..39b42aadd 100644 --- a/src/code/PSRepositoryInfo.cs +++ b/src/code/PSRepositoryInfo.cs @@ -44,7 +44,7 @@ public PSRepositoryInfo(string name, Uri uri, int priority, bool trusted, PSCred /// /// the priority of the repository /// - [ValidateRange(0, 50)] + [ValidateRange(0, 100)] public int Priority { get; } /// diff --git a/src/code/PSScriptMetadata.cs b/src/code/PSScriptMetadata.cs index f5cadb1ed..8ce8d0360 100644 --- a/src/code/PSScriptMetadata.cs +++ b/src/code/PSScriptMetadata.cs @@ -254,7 +254,7 @@ value continued string keyName = ""; string value = ""; - for (int i = 1; i < commentLines.Length; i++) + for (int i = 0; i < commentLines.Length; i++) { string line = commentLines[i]; diff --git a/src/code/PublishPSResource.cs b/src/code/PublishPSResource.cs index 2854da350..9c3064e98 100644 --- a/src/code/PublishPSResource.cs +++ b/src/code/PublishPSResource.cs @@ -123,6 +123,10 @@ public PSCredential ProxyCredential { public const string PSDataFileExt = ".psd1"; public const string PSScriptFileExt = ".ps1"; private const string PSScriptInfoCommentString = "<#PSScriptInfo"; + private string pathToScriptFileToPublish = string.Empty; + private string pathToModuleManifestToPublish = string.Empty; + private string pathToModuleDirToPublish = string.Empty; + private ResourceType resourceType = ResourceType.None; #endregion @@ -136,22 +140,51 @@ protected override void BeginProcessing() // This is to create a better experience for those who have just installed v3 and want to get up and running quickly RepositorySettings.CheckRepositoryStore(); - string resolvedPath = SessionState.Path.GetResolvedPSPathFromPSPath(Path).First().Path; + string resolvedPath = string.Empty; + try + { + resolvedPath = SessionState.Path.GetResolvedPSPathFromPSPath(Path).First().Path; + } + catch (MethodInvocationException) + { + // path does not exist + ThrowTerminatingError( + new ErrorRecord( + new ArgumentException( + "The path to the resource to publish does not exist, point to an existing path or file of the module or script to publish."), + "SourcePathDoesNotExist", + ErrorCategory.InvalidArgument, + this)); + } - if (Directory.Exists(resolvedPath) || - (File.Exists(resolvedPath) && resolvedPath.EndsWith(PSScriptFileExt, StringComparison.OrdinalIgnoreCase))) + // Condition 1: path is to the root directory of the module to be published + // Condition 2: path is to the .psd1 or .ps1 of the module/script to be published + _path = resolvedPath; + if (Directory.Exists(resolvedPath)) { - // condition 1: we point to a folder when publishing a module - // condition 2: we point to a .ps1 file directly when publishing a script, but not to .psd1 file (for publishing a module) - _path = resolvedPath; + pathToModuleDirToPublish = resolvedPath; + resourceType = ResourceType.Module; } - else + else if (resolvedPath.EndsWith(PSDataFileExt, StringComparison.OrdinalIgnoreCase)) + { + pathToModuleManifestToPublish = resolvedPath; + resourceType = ResourceType.Module; + } + else if (resolvedPath.EndsWith(PSScriptFileExt, StringComparison.OrdinalIgnoreCase)) + { + pathToScriptFileToPublish = resolvedPath; + resourceType = ResourceType.Script; + } + else if (string.IsNullOrEmpty(resolvedPath)) { // unsupported file path - var exMessage = string.Format("Either the path to the resource to publish does not exist or is not in the correct format, for scripts point to .ps1 file and for modules point to folder containing .psd1"); - var ex = new ArgumentException(exMessage); - var InvalidSourcePathError = new ErrorRecord(ex, "InvalidSourcePath", ErrorCategory.InvalidArgument, null); - ThrowTerminatingError(InvalidSourcePathError); + ThrowTerminatingError( + new ErrorRecord( + new ArgumentException( + "The path to the resource to publish is not in the correct format, point to a path or file of the module or script to publish."), + "InvalidSourcePath", + ErrorCategory.InvalidArgument, + this)); } if (!String.IsNullOrEmpty(DestinationPath)) @@ -182,25 +215,19 @@ protected override void BeginProcessing() protected override void EndProcessing() { // Returns the name of the file or the name of the directory, depending on path - var pkgFileOrDir = new DirectoryInfo(_path); - bool isScript = _path.EndsWith(PSScriptFileExt, StringComparison.OrdinalIgnoreCase); - if (!ShouldProcess(string.Format("Publish resource '{0}' from the machine", _path))) { WriteVerbose("ShouldProcess is set to false."); return; } - string resourceFilePath; Hashtable parsedMetadata; - if (isScript) + if (resourceType == ResourceType.Script) { - resourceFilePath = pkgFileOrDir.FullName; - // Check that script metadata is valid if (!TryParseScriptMetadata( out parsedMetadata, - resourceFilePath, + pathToScriptFileToPublish, out ErrorRecord[] errors)) { foreach (ErrorRecord err in errors) @@ -211,19 +238,37 @@ protected override void EndProcessing() return; } - // remove '.ps1' extension from file name - _pkgName = pkgFileOrDir.Name.Remove(pkgFileOrDir.Name.Length - 4); + _pkgName = System.IO.Path.GetFileNameWithoutExtension(pathToScriptFileToPublish); } else { - _pkgName = pkgFileOrDir.Name; - resourceFilePath = System.IO.Path.Combine(_path, _pkgName + PSDataFileExt); + // parsedMetadata needs to be initialized for modules, will later be passed in to create nuspec parsedMetadata = new Hashtable(); + if (!string.IsNullOrEmpty(pathToModuleManifestToPublish)) + { + _pkgName = System.IO.Path.GetFileNameWithoutExtension(pathToModuleManifestToPublish); + } + else { + // directory + // search for module manifest + List childFiles = new DirectoryInfo(pathToModuleDirToPublish).EnumerateFiles().ToList(); + + foreach (FileInfo file in childFiles) + { + if (file.Name.EndsWith(PSDataFileExt, StringComparison.OrdinalIgnoreCase)) + { + pathToModuleManifestToPublish = file.FullName; + _pkgName = System.IO.Path.GetFileNameWithoutExtension(file.Name); + + break; + } + } + } // Validate that there's a module manifest - if (!File.Exists(resourceFilePath)) + if (!File.Exists(pathToModuleManifestToPublish)) { - var message = String.Format("No file with a .psd1 extension was found in {0}. Please specify a path to a valid modulemanifest.", resourceFilePath); + var message = String.Format("No file with a .psd1 extension was found in {0}. Please specify a path to a valid modulemanifest.", _path); var ex = new ArgumentException(message); var moduleManifestNotFound = new ErrorRecord(ex, "moduleManifestNotFound", ErrorCategory.ObjectNotFound, null); WriteError(moduleManifestNotFound); @@ -236,6 +281,7 @@ protected override void EndProcessing() try { Utils.ValidateModuleManifest(resourceFilePath, out errorMsgs); + } finally { if (errorMsgs.Length > 0) @@ -251,22 +297,19 @@ protected override void EndProcessing() // Create a temp folder to push the nupkg to and delete it later string outputDir = System.IO.Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString()); - if (!Directory.Exists(outputDir)) + try { - try - { - Directory.CreateDirectory(outputDir); - } - catch (Exception e) - { - var ex = new ArgumentException(e.Message); - var ErrorCreatingTempDir = new ErrorRecord(ex, "ErrorCreatingTempDir", ErrorCategory.InvalidData, null); - WriteError(ErrorCreatingTempDir); - - return; - } + Directory.CreateDirectory(outputDir); } + catch (Exception e) + { + var ex = new ArgumentException(e.Message); + var ErrorCreatingTempDir = new ErrorRecord(ex, "ErrorCreatingTempDir", ErrorCategory.InvalidData, null); + WriteError(ErrorCreatingTempDir); + return; + } + try { // Create a nuspec @@ -277,8 +320,7 @@ protected override void EndProcessing() { nuspec = CreateNuspec( outputDir: outputDir, - filePath: resourceFilePath, - isScript: isScript, + filePath: (resourceType == ResourceType.Script) ? pathToScriptFileToPublish : pathToModuleManifestToPublish, parsedMetadataHash: parsedMetadata, requiredModules: out dependencies); } @@ -333,34 +375,48 @@ protected override void EndProcessing() } } - if (isScript) + if (resourceType == ResourceType.Script) { // copy the script file to the temp directory File.Copy(_path, System.IO.Path.Combine(outputDir, _pkgName + PSScriptFileExt), true); } else { - // Create subdirectory structure in temp folder - foreach (string dir in System.IO.Directory.GetDirectories(_path, "*", System.IO.SearchOption.AllDirectories)) + try { - var dirName = dir.Substring(_path.Length).Trim(_PathSeparators); - System.IO.Directory.CreateDirectory(System.IO.Path.Combine(outputDir, dirName)); - } + // If path is pointing to a file, get the parent directory, otherwise assumption is that path is pointing to the root directory + string rootModuleDir = !string.IsNullOrEmpty(pathToModuleManifestToPublish) ? new FileInfo(_path).Directory.FullName : _path; - // Copy files over to temp folder - foreach (string fileNamePath in System.IO.Directory.GetFiles(_path, "*", System.IO.SearchOption.AllDirectories)) - { - var fileName = fileNamePath.Substring(_path.Length).Trim(_PathSeparators); + // Create subdirectory structure in temp folder + foreach (string dir in System.IO.Directory.GetDirectories(rootModuleDir, "*", System.IO.SearchOption.AllDirectories)) + { + DirectoryInfo dirInfo = new DirectoryInfo(dir); + System.IO.Directory.CreateDirectory(System.IO.Path.Combine(outputDir, dirInfo.Name)); + } - // The user may have a .nuspec defined in the module directory - // If that's the case, we will not use that file and use the .nuspec that is generated via PSGet - // The .nuspec that is already in in the output directory is the one that was generated via the CreateNuspec method - var newFilePath = System.IO.Path.Combine(outputDir, fileName); - if (!File.Exists(newFilePath)) + // Copy files over to temp folder + foreach (string fileNamePath in System.IO.Directory.GetFiles(rootModuleDir, "*", System.IO.SearchOption.AllDirectories)) { - System.IO.File.Copy(fileNamePath, newFilePath); + FileInfo fileInfo = new FileInfo(fileNamePath); + + var newFilePath = System.IO.Path.Combine(outputDir, fileInfo.Name); + // The user may have a .nuspec defined in the module directory + // If that's the case, we will not use that file and use the .nuspec that is generated via PSGet + // The .nuspec that is already in in the output directory is the one that was generated via the CreateNuspec method + if (!File.Exists(newFilePath)) + { + System.IO.File.Copy(fileNamePath, newFilePath); + } } } + catch (Exception e) + { + ThrowTerminatingError(new ErrorRecord( + new ArgumentException("Error occured while creating directory to publish: " + e.Message), + "ErrorCreatingDirectoryToPublish", + ErrorCategory.InvalidOperation, + this)); + } } var outputNupkgDir = System.IO.Path.Combine(outputDir, "nupkg"); @@ -418,7 +474,6 @@ protected override void EndProcessing() private string CreateNuspec( string outputDir, string filePath, - bool isScript, Hashtable parsedMetadataHash, out Hashtable requiredModules) { @@ -427,7 +482,7 @@ private string CreateNuspec( // A script will already have the metadata parsed into the parsedMetadatahash, // a module will still need the module manifest to be parsed. - if (!isScript) + if (resourceType == ResourceType.Module) { // Use the parsed module manifest data as 'parsedMetadataHash' instead of the passed-in data. if (!Utils.TryReadManifestFile( @@ -544,7 +599,7 @@ private string CreateNuspec( metadataElementsDictionary.Add("copyright", parsedMetadataHash["copyright"].ToString().Trim()); } - string tags = isScript ? "PSScript" : "PSModule"; + string tags = (resourceType == ResourceType.Script) ? "PSScript" : "PSModule"; if (parsedMetadataHash.ContainsKey("tags")) { if (parsedMetadataHash["tags"] != null) @@ -884,17 +939,9 @@ private bool CheckDependenciesExist(Hashtable dependencies, string repositoryNam FindHelper findHelper = new FindHelper(_cancellationToken, this); bool depPrerelease = depVersion.Contains("-"); - var foundDependencies = findHelper.FindByResourceName( - name: depName, - type: ResourceType.Module, - version: depVersion, - prerelease: depPrerelease, - tag: null, - repository: new[] { repositoryName }, - credential: Credential, - includeDependencies: false); - - if (foundDependencies.Count is 0) + var repository = new[] { repositoryName }; + var dependencyFound = findHelper.FindByResourceName(depName, ResourceType.Module, depVersion, depPrerelease, null, repository, Credential, false); + if (dependencyFound == null || !dependencyFound.Any()) { var message = String.Format("Dependency '{0}' was not found in repository '{1}'. Make sure the dependency is published to the repository before publishing this module.", dependency, repositoryName); var ex = new ArgumentException(message); @@ -904,7 +951,6 @@ private bool CheckDependenciesExist(Hashtable dependencies, string repositoryNam return false; } } - return true; } diff --git a/src/code/RegisterPSResourceRepository.cs b/src/code/RegisterPSResourceRepository.cs index 6564f4d18..871be13e3 100644 --- a/src/code/RegisterPSResourceRepository.cs +++ b/src/code/RegisterPSResourceRepository.cs @@ -20,7 +20,8 @@ namespace Microsoft.PowerShell.PowerShellGet.Cmdlets [Cmdlet(VerbsLifecycle.Register, "PSResourceRepository", DefaultParameterSetName = NameParameterSet, - SupportsShouldProcess = true)] + SupportsShouldProcess = true, + ConfirmImpact = ConfirmImpact.Low)] public sealed class RegisterPSResourceRepository : PSCmdlet { @@ -28,8 +29,8 @@ class RegisterPSResourceRepository : PSCmdlet private readonly string PSGalleryRepoName = "PSGallery"; private readonly string PSGalleryRepoUri = "https://www.powershellgallery.com/api/v2"; - private const int defaultPriority = 50; - private const bool defaultTrusted = false; + private const int DefaultPriority = 50; + private const bool DefaultTrusted = false; private const string NameParameterSet = "NameParameterSet"; private const string PSGalleryParameterSet = "PSGalleryParameterSet"; private const string RepositoriesParameterSet = "RepositoriesParameterSet"; @@ -76,13 +77,13 @@ class RegisterPSResourceRepository : PSCmdlet /// /// Specifies the priority ranking of the repository, such that repositories with higher ranking priority are searched /// before a lower ranking priority one, when searching for a repository item across multiple registered repositories. - /// Valid priority values range from 0 to 50, such that a lower numeric value (i.e 10) corresponds + /// Valid priority values range from 0 to 100, such that a lower numeric value (i.e 10) corresponds /// to a higher priority ranking than a higher numeric value (i.e 40). Has default value of 50. /// [Parameter(ParameterSetName = NameParameterSet)] [Parameter(ParameterSetName = PSGalleryParameterSet)] - [ValidateRange(0, 50)] - public int Priority { get; set; } = defaultPriority; + [ValidateRange(0, 100)] + public int Priority { get; set; } = DefaultPriority; /// /// Specifies vault and secret names as PSCredentialInfo for the repository. @@ -104,10 +105,16 @@ class RegisterPSResourceRepository : PSCmdlet public PSCredential ProxyCredential { get; set; } /// - /// When specified, displays the succcessfully registered repository and its information + /// When specified, displays the succcessfully registered repository and its information. /// [Parameter] public SwitchParameter PassThru { get; set; } + + /// + /// When specified, will overwrite information for any existing repository with the same name. + /// + [Parameter] + public SwitchParameter Force { get; set; } #endregion @@ -143,7 +150,16 @@ protected override void ProcessRecord() try { - items.Add(NameParameterSetHelper(Name, _uri, Priority, Trusted, CredentialInfo)); + items.Add(RepositorySettings.AddRepository(Name, _uri, Priority, Trusted, CredentialInfo, Force, this, out string errorMsg)); + + if (!string.IsNullOrEmpty(errorMsg)) + { + ThrowTerminatingError(new ErrorRecord( + new PSInvalidOperationException(errorMsg), + "ErrorInNameParameterSet", + ErrorCategory.InvalidArgument, + this)); + } } catch (Exception e) { @@ -200,71 +216,30 @@ protected override void ProcessRecord() } } - private PSRepositoryInfo AddToRepositoryStoreHelper(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, PSCredentialInfo repoCredentialInfo) - { - // remove trailing and leading whitespaces, and if Name is just whitespace Name should become null now and be caught by following condition - repoName = repoName.Trim(' '); - if (String.IsNullOrEmpty(repoName) || repoName.Contains("*")) - { - throw new ArgumentException("Name cannot be null/empty, contain asterisk or be just whitespace"); - } - - if (repoUri == null || !(repoUri.Scheme == System.Uri.UriSchemeHttp || repoUri.Scheme == System.Uri.UriSchemeHttps || repoUri.Scheme == System.Uri.UriSchemeFtp || repoUri.Scheme == System.Uri.UriSchemeFile)) - { - throw new ArgumentException("Invalid Uri, must be one of the following Uri schemes: HTTPS, HTTP, FTP, File Based"); - } - - if (repoCredentialInfo != null) - { - bool isSecretManagementModuleAvailable = Utils.IsSecretManagementModuleAvailable(repoName, this); - - if (repoCredentialInfo.Credential != null) - { - if (!isSecretManagementModuleAvailable) - { - ThrowTerminatingError(new ErrorRecord( - new PSInvalidOperationException($"Microsoft.PowerShell.SecretManagement module is not found, but is required for saving PSResourceRepository {repoName}'s Credential in a vault."), - "RepositoryCredentialSecretManagementUnavailableModule", - ErrorCategory.ResourceUnavailable, - this)); - } - else - { - Utils.SaveRepositoryCredentialToSecretManagementVault(repoName, repoCredentialInfo, this); - } - } - - if (!isSecretManagementModuleAvailable) - { - WriteWarning($"Microsoft.PowerShell.SecretManagement module cannot be found. Make sure it is installed before performing PSResource operations in order to successfully authenticate to PSResourceRepository \"{repoName}\" with its CredentialInfo."); - } - } - - WriteVerbose("All required values to add to repository provided, calling internal Add() API now"); - if (!ShouldProcess(repoName, "Register repository to repository store")) - { - return null; - } - - return RepositorySettings.Add(repoName, repoUri, repoPriority, repoTrusted, repoCredentialInfo); - } - - private PSRepositoryInfo NameParameterSetHelper(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, PSCredentialInfo repoCredentialInfo) - { - if (repoName.Equals("PSGallery", StringComparison.OrdinalIgnoreCase)) - { - WriteVerbose("Provided Name (NameParameterSet) but with invalid value of PSGallery"); - throw new ArgumentException("Cannot register PSGallery with -Name parameter. Try: Register-PSResourceRepository -PSGallery"); - } - - return AddToRepositoryStoreHelper(repoName, repoUri, repoPriority, repoTrusted, repoCredentialInfo); - } private PSRepositoryInfo PSGalleryParameterSetHelper(int repoPriority, bool repoTrusted) { Uri psGalleryUri = new Uri(PSGalleryRepoUri); WriteVerbose("(PSGallerySet) internal name and uri values for Add() API are hardcoded and validated, priority and trusted values, if passed in, also validated"); - return AddToRepositoryStoreHelper(PSGalleryRepoName, psGalleryUri, repoPriority, repoTrusted, repoCredentialInfo: null); + var addedRepo = RepositorySettings.AddToRepositoryStore(PSGalleryRepoName, + psGalleryUri, + repoPriority, + repoTrusted, + repoCredentialInfo: null, + Force, + this, + out string errorMsg); + + if (!string.IsNullOrEmpty(errorMsg)) + { + ThrowTerminatingError(new ErrorRecord( + new PSInvalidOperationException(errorMsg), + "RepositoryCredentialSecretManagementUnavailableModule", + ErrorCategory.ResourceUnavailable, + this)); + } + + return addedRepo; } private List RepositoriesParameterSetHelper() @@ -288,8 +263,8 @@ private List RepositoriesParameterSetHelper() { WriteVerbose("(RepositoriesParameterSet): on repo: PSGallery. Registers PSGallery repository"); reposAddedFromHashTable.Add(PSGalleryParameterSetHelper( - repo.ContainsKey("Priority") ? (int)repo["Priority"] : defaultPriority, - repo.ContainsKey("Trusted") ? (bool)repo["Trusted"] : defaultTrusted)); + repo.ContainsKey("Priority") ? (int)repo["Priority"] : DefaultPriority, + repo.ContainsKey("Trusted") ? (bool)repo["Trusted"] : DefaultTrusted)); } catch (Exception e) { @@ -315,7 +290,7 @@ private List RepositoriesParameterSetHelper() private PSRepositoryInfo RepoValidationHelper(Hashtable repo) { - if (!repo.ContainsKey("Name") || String.IsNullOrEmpty(repo["Name"].ToString())) + if (!repo.ContainsKey("Name") || repo["Name"] == null || String.IsNullOrWhiteSpace(repo["Name"].ToString())) { WriteError(new ErrorRecord( new PSInvalidOperationException("Repository name cannot be null"), @@ -335,7 +310,7 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) return null; } - if (!repo.ContainsKey("Uri") || String.IsNullOrEmpty(repo["Uri"].ToString())) + if (!repo.ContainsKey("Uri") || repo["Uri"] == null || String.IsNullOrEmpty(repo["Uri"].ToString())) { WriteError(new ErrorRecord( new PSInvalidOperationException("Repository Uri cannot be null"), @@ -368,11 +343,25 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) try { WriteVerbose(String.Format("(RepositoriesParameterSet): on repo: {0}. Registers Name based repository", repo["Name"])); - return NameParameterSetHelper(repo["Name"].ToString(), + var addedRepo = RepositorySettings.AddRepository(repo["Name"].ToString(), repoUri, - repo.ContainsKey("Priority") ? Convert.ToInt32(repo["Priority"].ToString()) : defaultPriority, - repo.ContainsKey("Trusted") ? Convert.ToBoolean(repo["Trusted"].ToString()) : defaultTrusted, - repoCredentialInfo); + repo.ContainsKey("Priority") ? Convert.ToInt32(repo["Priority"].ToString()) : DefaultPriority, + repo.ContainsKey("Trusted") ? Convert.ToBoolean(repo["Trusted"].ToString()) : DefaultTrusted, + repoCredentialInfo, + Force, + this, + out string errorMsg); + + if (!string.IsNullOrEmpty(errorMsg)) + { + ThrowTerminatingError(new ErrorRecord( + new PSInvalidOperationException(errorMsg), + "RegisterRepositoryError", + ErrorCategory.ResourceUnavailable, + this)); + } + + return addedRepo; } catch (Exception e) { diff --git a/src/code/RepositorySettings.cs b/src/code/RepositorySettings.cs index dec5d2d15..47c6185d5 100644 --- a/src/code/RepositorySettings.cs +++ b/src/code/RepositorySettings.cs @@ -24,8 +24,8 @@ internal static class RepositorySettings // The repository store file's location is currently only at '%LOCALAPPDATA%\PowerShellGet' for the user account. private const string PSGalleryRepoName = "PSGallery"; private const string PSGalleryRepoUri = "https://www.powershellgallery.com/api/v2"; - private const int defaultPriority = 50; - private const bool defaultTrusted = false; + private const int DefaultPriority = 50; + private const bool DefaultTrusted = false; private const string RepositoryFileName = "PSResourceRepository.xml"; private static readonly string RepositoryPath = Path.Combine(Environment.GetFolderPath( Environment.SpecialFolder.LocalApplicationData), "PowerShellGet"); @@ -60,7 +60,7 @@ public static void CheckRepositoryStore() // Add PSGallery to the newly created store Uri psGalleryUri = new Uri(PSGalleryRepoUri); - Add(PSGalleryRepoName, psGalleryUri, defaultPriority, defaultTrusted, repoCredentialInfo: null); + Add(PSGalleryRepoName, psGalleryUri, DefaultPriority, DefaultTrusted, repoCredentialInfo: null, force: false); } // Open file (which should exist now), if cannot/is corrupted then throw error @@ -74,12 +74,159 @@ public static void CheckRepositoryStore() } } + public static PSRepositoryInfo AddRepository(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, PSCredentialInfo repoCredentialInfo, bool force, PSCmdlet cmdletPassedIn, out string errorMsg) + { + errorMsg = String.Empty; + if (repoName.Equals("PSGallery", StringComparison.OrdinalIgnoreCase)) + { + errorMsg = "Cannot register PSGallery with -Name parameter. Try: Register-PSResourceRepository -PSGallery"; + return null; + } + + return AddToRepositoryStore(repoName, repoUri, repoPriority, repoTrusted, repoCredentialInfo, force, cmdletPassedIn, out errorMsg); + } + + + public static PSRepositoryInfo AddToRepositoryStore(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, PSCredentialInfo repoCredentialInfo, bool force, PSCmdlet cmdletPassedIn, out string errorMsg) + { + errorMsg = string.Empty; + // remove trailing and leading whitespaces, and if Name is just whitespace Name should become null now and be caught by following condition + repoName = repoName.Trim(' '); + if (String.IsNullOrEmpty(repoName) || repoName.Contains("*")) + { + throw new ArgumentException("Name cannot be null/empty, contain asterisk or be just whitespace"); + } + + if (repoUri == null || !(repoUri.Scheme == System.Uri.UriSchemeHttp || repoUri.Scheme == System.Uri.UriSchemeHttps || repoUri.Scheme == System.Uri.UriSchemeFtp || repoUri.Scheme == System.Uri.UriSchemeFile)) + { + errorMsg = "Invalid Uri, must be one of the following Uri schemes: HTTPS, HTTP, FTP, File Based"; + return null; + } + + if (repoCredentialInfo != null) + { + bool isSecretManagementModuleAvailable = Utils.IsSecretManagementModuleAvailable(repoName, cmdletPassedIn); + + if (repoCredentialInfo.Credential != null) + { + if (!isSecretManagementModuleAvailable) + { + errorMsg = $"Microsoft.PowerShell.SecretManagement module is not found, but is required for saving PSResourceRepository {repoName}'s Credential in a vault."; + return null; + } + else + { + Utils.SaveRepositoryCredentialToSecretManagementVault(repoName, repoCredentialInfo, cmdletPassedIn); + } + } + + if (!isSecretManagementModuleAvailable) + { + cmdletPassedIn.WriteWarning($"Microsoft.PowerShell.SecretManagement module cannot be found. Make sure it is installed before performing PSResource operations in order to successfully authenticate to PSResourceRepository \"{repoName}\" with its CredentialInfo."); + } + } + + if (!cmdletPassedIn.ShouldProcess(repoName, "Register repository to repository store")) + { + return null; + } + + if (!string.IsNullOrEmpty(errorMsg)) + { + return null; + } + + var repo = RepositorySettings.Add(repoName, repoUri, repoPriority, repoTrusted, repoCredentialInfo, force); + + return repo; + } + + + public static PSRepositoryInfo UpdateRepositoryStore(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, bool isSet, int defaultPriority, PSCredentialInfo repoCredentialInfo, PSCmdlet cmdletPassedIn, out string errorMsg) + { + errorMsg = string.Empty; + if (repoUri != null && !(repoUri.Scheme == System.Uri.UriSchemeHttp || repoUri.Scheme == System.Uri.UriSchemeHttps || repoUri.Scheme == System.Uri.UriSchemeFtp || repoUri.Scheme == System.Uri.UriSchemeFile)) + { + errorMsg = "Invalid Uri, Uri must be one of the following schemes: HTTPS, HTTP, FTP, File Based"; + return null; + } + + // check repoName can't contain * or just be whitespace + // remove trailing and leading whitespaces, and if Name is just whitespace Name should become null now and be caught by following condition + repoName = repoName.Trim(); + if (String.IsNullOrEmpty(repoName) || repoName.Contains("*")) + { + errorMsg = "Name cannot be null or empty, or contain wildcards"; + return null; + } + + // check PSGallery Uri is not trying to be set + if (repoName.Equals("PSGallery", StringComparison.OrdinalIgnoreCase) && repoUri != null) + { + errorMsg = "The PSGallery repository has a predefined Uri. Setting the -Uri parameter for this repository is not allowed. Please run 'Register-PSResourceRepository -PSGallery' to register the PowerShell Gallery."; + return null; + } + + // check PSGallery CredentialInfo is not trying to be set + if (repoName.Equals("PSGallery", StringComparison.OrdinalIgnoreCase) && repoCredentialInfo != null) + { + errorMsg = "Setting the -CredentialInfo parameter for PSGallery is not allowed. Run 'Register-PSResourceRepository -PSGallery' to register the PowerShell Gallery."; + return null; + } + + // determine trusted value to pass in (true/false if set, null otherwise, hence the nullable bool variable) + bool? _trustedNullable = isSet ? new bool?(repoTrusted) : new bool?(); + + if (repoCredentialInfo != null) + { + bool isSecretManagementModuleAvailable = Utils.IsSecretManagementModuleAvailable(repoName, cmdletPassedIn); + + if (repoCredentialInfo.Credential != null) + { + if (!isSecretManagementModuleAvailable) + { + errorMsg = $"Microsoft.PowerShell.SecretManagement module is not found, but is required for saving PSResourceRepository {repoName}'s Credential in a vault."; + return null; + } + else + { + Utils.SaveRepositoryCredentialToSecretManagementVault(repoName, repoCredentialInfo, cmdletPassedIn); + } + } + + if (!isSecretManagementModuleAvailable) + { + cmdletPassedIn.WriteWarning($"Microsoft.PowerShell.SecretManagement module cannot be found. Make sure it is installed before performing PSResource operations in order to successfully authenticate to PSResourceRepository \"{repoName}\" with its CredentialInfo."); + } + } + + // determine if either 1 of 4 values are attempting to be set: Uri, Priority, Trusted, CredentialInfo. + // if none are (i.e only Name parameter was provided, write error) + if (repoUri == null && repoPriority == defaultPriority && _trustedNullable == null && repoCredentialInfo == null) + { + errorMsg = "Must set Uri, Priority, Trusted or CredentialInfo parameter"; + return null; + } + + if (!cmdletPassedIn.ShouldProcess(repoName, "Set repository's value(s) in repository store")) + { + return null; + } + + if (!string.IsNullOrEmpty(errorMsg)) + { + return null; + } + + return Update(repoName, repoUri, repoPriority, _trustedNullable, repoCredentialInfo, cmdletPassedIn, out errorMsg); + } + /// /// Add a repository to the store /// Returns: PSRepositoryInfo containing information about the repository just added to the repository store /// /// - public static PSRepositoryInfo Add(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, PSCredentialInfo repoCredentialInfo) + public static PSRepositoryInfo Add(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, PSCredentialInfo repoCredentialInfo, bool force) { try { @@ -87,7 +234,22 @@ public static PSRepositoryInfo Add(string repoName, Uri repoUri, int repoPriorit XDocument doc = LoadXDocument(FullRepositoryPath); if (FindRepositoryElement(doc, repoName) != null) { - throw new PSInvalidOperationException(String.Format("The PSResource Repository '{0}' already exists.", repoName)); + if (!force) + { + throw new PSInvalidOperationException(String.Format("The PSResource Repository '{0}' already exists.", repoName)); + } + + // Delete the existing repository before overwriting it (otherwire multiple repos with the same name will be added) + List removedRepositories = RepositorySettings.Remove(new string[] { repoName }, out string[] errorList); + + // Need to load the document again because of changes after removing + doc = LoadXDocument(FullRepositoryPath); + + if (errorList.Count() > 0) + { + throw new PSInvalidOperationException($"The PSResource Repository '{repoName}' cannot be overwritten: ${errorList.FirstOrDefault()}"); + } + } // Else, keep going @@ -126,8 +288,9 @@ public static PSRepositoryInfo Add(string repoName, Uri repoUri, int repoPriorit /// Updates a repository name, Uri, priority, installation policy, or credential information /// Returns: void /// - public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPriority, bool? repoTrusted, PSCredentialInfo repoCredentialInfo) + public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPriority, bool? repoTrusted, PSCredentialInfo repoCredentialInfo, PSCmdlet cmdletPassedIn, out string errorMsg) { + errorMsg = string.Empty; PSRepositoryInfo updatedRepo; try { @@ -136,7 +299,9 @@ public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPrio XElement node = FindRepositoryElement(doc, repoName); if (node == null) { - throw new ArgumentException("Cannot find the repository because it does not exist. Try registering the repository using 'Register-PSResourceRepository'"); + bool repoIsTrusted = !(repoTrusted == null || repoTrusted == false); + repoPriority = repoPriority < 0 ? DefaultPriority : repoPriority; + return AddToRepositoryStore(repoName, repoUri, repoPriority, repoIsTrusted, repoCredentialInfo, force:true, cmdletPassedIn, out errorMsg); } // Check that repository node we are attempting to update has all required attributes: Name, Url (or Uri), Priority, Trusted. @@ -144,19 +309,22 @@ public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPrio if (node.Attribute("Priority") == null) { - throw new ArgumentException("Repository element does not contain neccessary 'Priority' attribute, in file located at path: {0}. Fix this in your file and run again.", FullRepositoryPath); + errorMsg = $"Repository element does not contain neccessary 'Priority' attribute, in file located at path: {FullRepositoryPath}. Fix this in your file and run again."; + return null; } if (node.Attribute("Trusted") == null) { - throw new ArgumentException("Repository element does not contain neccessary 'Trusted' attribute, in file located at path: {0}. Fix this in your file and run again.", FullRepositoryPath); + errorMsg = $"Repository element does not contain neccessary 'Trusted' attribute, in file located at path: {FullRepositoryPath}. Fix this in your file and run again."; + return null; } bool urlAttributeExists = node.Attribute("Url") != null; bool uriAttributeExists = node.Attribute("Uri") != null; if (!urlAttributeExists && !uriAttributeExists) { - throw new ArgumentException("Repository element does not contain neccessary 'Url' attribute (or alternatively 'Uri' attribute), in file located at path: {0}. Fix this in your file and run again.", FullRepositoryPath); + errorMsg = $"Repository element does not contain neccessary 'Url' attribute (or alternatively 'Uri' attribute), in file located at path: {FullRepositoryPath}. Fix this in your file and run again."; + return null; } // Else, keep going @@ -176,7 +344,8 @@ public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPrio // Create Uri from node Uri attribute to create PSRepositoryInfo item to return. if (!Uri.TryCreate(node.Attribute("Url").Value, UriKind.Absolute, out thisUrl)) { - throw new PSInvalidOperationException(String.Format("Unable to read incorrectly formatted Url for repo {0}", repoName)); + errorMsg = $"Unable to read incorrectly formatted Url for repo {repoName}"; + return null; } } else @@ -185,7 +354,8 @@ public static PSRepositoryInfo Update(string repoName, Uri repoUri, int repoPrio node.Attribute("Uri").Value = repoUri.AbsoluteUri; if (!Uri.TryCreate(node.Attribute("Uri").Value, UriKind.Absolute, out thisUrl)) { - throw new PSInvalidOperationException(String.Format("Unable to read incorrectly formatted Uri for repo {0}", repoName)); + errorMsg = $"Unable to read incorrectly formatted Uri for repo {repoName}"; + return null; } } } diff --git a/src/code/SavePSResource.cs b/src/code/SavePSResource.cs index 73b6d1c19..3f2b2ce26 100644 --- a/src/code/SavePSResource.cs +++ b/src/code/SavePSResource.cs @@ -17,7 +17,7 @@ namespace Microsoft.PowerShell.PowerShellGet.Cmdlets /// The Save-PSResource cmdlet saves a resource to a machine. /// It returns nothing. /// - [Cmdlet(VerbsData.Save, "PSResource", DefaultParameterSetName = "NameParameterSet", SupportsShouldProcess = true)] + [Cmdlet(VerbsData.Save, "PSResource", DefaultParameterSetName = "NameParameterSet", SupportsShouldProcess = true, ConfirmImpact = ConfirmImpact.Low)] public sealed class SavePSResource : PSCmdlet { #region Members @@ -76,7 +76,7 @@ public sealed class SavePSResource : PSCmdlet /// Saves the metadata XML file with the resource /// [Parameter] - public SwitchParameter IncludeXML { get; set; } + public SwitchParameter IncludeXml { get; set; } /// /// The destination where the resource is to be installed. Works for all resource types. @@ -91,8 +91,12 @@ public string Path set { string resolvedPath = string.Empty; - if (!string.IsNullOrEmpty(value)) + if (string.IsNullOrEmpty(value)) { + // If the user does not specify a path to save to, use the user's current working directory + resolvedPath = SessionState.Path.GetResolvedPSPathFromPSPath(SessionState.Path.CurrentFileSystemLocation.Path).First().Path; + } + else { resolvedPath = SessionState.Path.GetResolvedPSPathFromPSPath(value).First().Path; } @@ -155,12 +159,6 @@ protected override void BeginProcessing() // This is to create a better experience for those who have just installed v3 and want to get up and running quickly RepositorySettings.CheckRepositoryStore(); - // If the user does not specify a path to save to, use the user's current working directory - if (string.IsNullOrWhiteSpace(_path)) - { - _path = SessionState.Path.CurrentLocation.Path; - } - _installHelper = new InstallHelper(cmdletPassedIn: this); } @@ -264,7 +262,7 @@ private void ProcessSaveHelper(string[] pkgNames, bool pkgPrerelease, string[] p credential: Credential, noClobber: false, asNupkg: AsNupkg, - includeXML: IncludeXML, + includeXml: IncludeXml, skipDependencyCheck: SkipDependencyCheck, authenticodeCheck: AuthenticodeCheck, savePkg: true, diff --git a/src/code/SetPSResourceRepository.cs b/src/code/SetPSResourceRepository.cs index 2ada5bdee..7f874a56e 100644 --- a/src/code/SetPSResourceRepository.cs +++ b/src/code/SetPSResourceRepository.cs @@ -34,7 +34,7 @@ public sealed class SetPSResourceRepository : PSCmdlet /// /// Specifies the name of the repository to be set. /// - [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ParameterSetName = NameParameterSet)] + [Parameter(Mandatory = true, Position = 0, ValueFromPipeline = true, ValueFromPipelineByPropertyName = true, ParameterSetName = NameParameterSet)] [ArgumentCompleter(typeof(RepositoryNameCompleter))] [ValidateNotNullOrEmpty] public string Name { get; set; } @@ -74,12 +74,12 @@ public SwitchParameter Trusted /// /// Specifies the priority ranking of the repository, such that repositories with higher ranking priority are searched /// before a lower ranking priority one, when searching for a repository item across multiple registered repositories. - /// Valid priority values range from 0 to 50, such that a lower numeric value (i.e 10) corresponds + /// Valid priority values range from 0 to 100, such that a lower numeric value (i.e 10) corresponds /// to a higher priority ranking than a higher numeric value (i.e 40). /// [Parameter(ParameterSetName = NameParameterSet)] [ValidateNotNullOrEmpty] - [ValidateRange(0, 50)] + [ValidateRange(0, 100)] public int Priority { get; set; } = DefaultPriority; /// @@ -89,7 +89,7 @@ public SwitchParameter Trusted public PSCredentialInfo CredentialInfo { get; set; } /// - /// When specified, displays the successfully registered repository and its information + /// When specified, displays the successfully registered repository and its information. /// [Parameter] public SwitchParameter PassThru { get; set; } @@ -121,7 +121,24 @@ protected override void ProcessRecord() case NameParameterSet: try { - items.Add(UpdateRepositoryStoreHelper(Name, _uri, Priority, Trusted, CredentialInfo)); + items.Add(RepositorySettings.UpdateRepositoryStore(Name, + _uri, + Priority, + Trusted, + isSet, + DefaultPriority, + CredentialInfo, + this, + out string errorMsg)); + + if (!string.IsNullOrEmpty(errorMsg)) + { + ThrowTerminatingError(new ErrorRecord( + new PSInvalidOperationException(errorMsg), + "ErrorInNameParameterSet", + ErrorCategory.InvalidArgument, + this)); + } } catch (Exception e) { @@ -162,77 +179,6 @@ protected override void ProcessRecord() } } - private PSRepositoryInfo UpdateRepositoryStoreHelper(string repoName, Uri repoUri, int repoPriority, bool repoTrusted, PSCredentialInfo repoCredentialInfo) - { - if (repoUri != null && !(repoUri.Scheme == System.Uri.UriSchemeHttp || repoUri.Scheme == System.Uri.UriSchemeHttps || repoUri.Scheme == System.Uri.UriSchemeFtp || repoUri.Scheme == System.Uri.UriSchemeFile)) - { - throw new ArgumentException("Invalid Uri, must be one of the following Uri schemes: HTTPS, HTTP, FTP, File Based"); - } - - // check repoName can't contain * or just be whitespace - // remove trailing and leading whitespaces, and if Name is just whitespace Name should become null now and be caught by following condition - repoName = repoName.Trim(); - if (String.IsNullOrEmpty(repoName) || repoName.Contains("*")) - { - throw new ArgumentException("Name cannot be null/empty, contain asterisk or be just whitespace"); - } - - // check PSGallery Uri is not trying to be set - if (repoName.Equals("PSGallery", StringComparison.OrdinalIgnoreCase) && repoUri != null) - { - throw new ArgumentException("The PSGallery repository has a pre-defined Uri. Setting the -Uri parameter for this repository is not allowed, instead try running 'Register-PSResourceRepository -PSGallery'."); - } - - // check PSGallery CredentialInfo is not trying to be set - if (repoName.Equals("PSGallery", StringComparison.OrdinalIgnoreCase) && repoCredentialInfo != null) - { - throw new ArgumentException("The PSGallery repository does not require authentication. Setting the -CredentialInfo parameter for this repository is not allowed, instead try running 'Register-PSResourceRepository -PSGallery'."); - } - - // determine trusted value to pass in (true/false if set, null otherwise, hence the nullable bool variable) - bool? _trustedNullable = isSet ? new bool?(repoTrusted) : new bool?(); - - if (repoCredentialInfo != null) - { - bool isSecretManagementModuleAvailable = Utils.IsSecretManagementModuleAvailable(repoName, this); - - if (repoCredentialInfo.Credential != null) - { - if (!isSecretManagementModuleAvailable) - { - ThrowTerminatingError(new ErrorRecord( - new PSInvalidOperationException($"Microsoft.PowerShell.SecretManagement module is not found, but is required for saving PSResourceRepository {repoName}'s Credential in a vault."), - "RepositoryCredentialSecretManagementUnavailableModule", - ErrorCategory.ResourceUnavailable, - this)); - } - else - { - Utils.SaveRepositoryCredentialToSecretManagementVault(repoName, repoCredentialInfo, this); - } - } - - if (!isSecretManagementModuleAvailable) - { - WriteWarning($"Microsoft.PowerShell.SecretManagement module cannot be found. Make sure it is installed before performing PSResource operations in order to successfully authenticate to PSResourceRepository \"{repoName}\" with its CredentialInfo."); - } - } - - // determine if either 1 of 4 values are attempting to be set: Uri, Priority, Trusted, CredentialInfo. - // if none are (i.e only Name parameter was provided, write error) - if (repoUri == null && repoPriority == DefaultPriority && _trustedNullable == null && repoCredentialInfo == null) - { - throw new ArgumentException("Either Uri, Priority, Trusted or CredentialInfo parameters must be requested to be set"); - } - - WriteVerbose("All required values to set repository provided, calling internal Update() API now"); - if (!ShouldProcess(repoName, "Set repository's value(s) in repository store")) - { - return null; - } - return RepositorySettings.Update(repoName, repoUri, repoPriority, _trustedNullable, repoCredentialInfo); - } - private List RepositoriesParameterSetHelper() { List reposUpdatedFromHashtable = new List(); @@ -305,11 +251,26 @@ private PSRepositoryInfo RepoValidationHelper(Hashtable repo) try { - return UpdateRepositoryStoreHelper(repo["Name"].ToString(), + var updatedRepo = RepositorySettings.UpdateRepositoryStore(repo["Name"].ToString(), repoUri, repo.ContainsKey("Priority") ? Convert.ToInt32(repo["Priority"].ToString()) : DefaultPriority, repoTrusted, - repoCredentialInfo); + isSet, + DefaultPriority, + repoCredentialInfo, + this, + out string errorMsg); + + if (!string.IsNullOrEmpty(errorMsg)) + { + WriteError(new ErrorRecord( + new PSInvalidOperationException(errorMsg), + "ErrorSettingRepository", + ErrorCategory.InvalidData, + this)); + } + + return updatedRepo; } catch (Exception e) { diff --git a/src/code/UpdatePSResource.cs b/src/code/UpdatePSResource.cs index 5ca79d529..bce9ed295 100644 --- a/src/code/UpdatePSResource.cs +++ b/src/code/UpdatePSResource.cs @@ -183,7 +183,7 @@ protected override void ProcessRecord() credential: Credential, noClobber: false, asNupkg: false, - includeXML: true, + includeXml: true, skipDependencyCheck: SkipDependencyCheck, authenticodeCheck: AuthenticodeCheck, savePkg: false, diff --git a/src/code/Utils.cs b/src/code/Utils.cs index 32292d87f..1ddbdb226 100644 --- a/src/code/Utils.cs +++ b/src/code/Utils.cs @@ -616,14 +616,15 @@ public static string GetInstalledPackageName(string pkgPath) return new DirectoryInfo(pkgPath).Parent.Name; } - public static List GetAllResourcePaths( + // Find all potential resource paths + public static List GetPathsFromEnvVarAndScope( PSCmdlet psCmdlet, - ScopeType? scope = null) + ScopeType? scope) { GetStandardPlatformPaths( - psCmdlet, - out string myDocumentsPath, - out string programFilesPath); + psCmdlet, + out string myDocumentsPath, + out string programFilesPath); List resourcePaths = new List(); @@ -646,6 +647,15 @@ public static List GetAllResourcePaths( resourcePaths.Add(Path.Combine(programFilesPath, "Scripts")); } + return resourcePaths; + } + + public static List GetAllResourcePaths( + PSCmdlet psCmdlet, + ScopeType? scope = null) + { + List resourcePaths = GetPathsFromEnvVarAndScope(psCmdlet, scope); + // resourcePaths should now contain, eg: // ./PowerShell/Scripts // ./PowerShell/Modules @@ -692,26 +702,10 @@ public static List GetAllResourcePaths( // Find all potential installation paths given a scope public static List GetAllInstallationPaths( PSCmdlet psCmdlet, - ScopeType scope) + ScopeType? scope) { - GetStandardPlatformPaths( - psCmdlet, - out string myDocumentsPath, - out string programFilesPath); - - // The default user scope is CurrentUser - var installationPaths = new List(); - if (scope == ScopeType.AllUsers) - { - installationPaths.Add(Path.Combine(programFilesPath, "Modules")); - installationPaths.Add(Path.Combine(programFilesPath, "Scripts")); - } - else - { - installationPaths.Add(Path.Combine(myDocumentsPath, "Modules")); - installationPaths.Add(Path.Combine(myDocumentsPath, "Scripts")); - } - + List installationPaths = GetPathsFromEnvVarAndScope(psCmdlet, scope); + installationPaths = installationPaths.Distinct(StringComparer.InvariantCultureIgnoreCase).ToList(); installationPaths.ForEach(dir => psCmdlet.WriteVerbose(string.Format("All paths to search: '{0}'", dir))); diff --git a/test/InstallPSResource.Tests.ps1 b/test/InstallPSResource.Tests.ps1 index e2666efb0..bef8111ae 100644 --- a/test/InstallPSResource.Tests.ps1 +++ b/test/InstallPSResource.Tests.ps1 @@ -173,6 +173,13 @@ Describe 'Test Install-PSResource for Module' { $pkg.Version | Should -Be "5.0.0.0" } + It "Install resource under specified in PSModulePath" { + Install-PSResource -Name $testModuleName -Repository $PSGalleryName -TrustRepository + $pkg = Get-PSResource $testModuleName + $pkg.Name | Should -Be $testModuleName + ($env:PSModulePath).Contains($pkg.InstalledLocation) + } + # Windows only It "Install resource under CurrentUser scope - Windows only" -Skip:(!(Get-IsWindows)) { Install-PSResource -Name $testModuleName -Repository $PSGalleryName -TrustRepository -Scope CurrentUser diff --git a/test/PublishPSResource.Tests.ps1 b/test/PublishPSResource.Tests.ps1 index f2368978c..f1b1baf22 100644 --- a/test/PublishPSResource.Tests.ps1 +++ b/test/PublishPSResource.Tests.ps1 @@ -67,6 +67,9 @@ Describe "Test Publish-PSResource" { $pkgsToDelete = Join-Path -Path "$script:repositoryPath2" -ChildPath "*" Remove-Item $pkgsToDelete -Recurse + + $pkgsToDelete = Join-Path -Path $script:PublishModuleBase -ChildPath "*" + Remove-Item $pkgsToDelete -Recurse -ErrorAction SilentlyContinue } It "Publish a module with -Path to the highest priority repo" { @@ -89,6 +92,52 @@ Describe "Test Publish-PSResource" { (Get-ChildItem $script:repositoryPath2).FullName | Should -Be $expectedPath } + It "Publish a module with -Path pointing to a module directory (parent directory has same name)" { + $version = "1.0.0" + New-ModuleManifest -Path (Join-Path -Path $script:PublishModuleBase -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" + + Publish-PSResource -Path $script:PublishModuleBase -Repository $testRepository2 + + $expectedPath = Join-Path -Path $script:repositoryPath2 -ChildPath "$script:PublishModuleName.$version.nupkg" + (Get-ChildItem $script:repositoryPath2).FullName | Should -Be $expectedPath + } + + It "Publish a module with -Path pointing to a module directory (parent directory has different name)" { + $version = "1.0.0" + $newModuleRoot = Join-Path -Path $script:PublishModuleBase -ChildPath "NewTestParentDirectory" + New-Item -Path $newModuleRoot -ItemType Directory + New-ModuleManifest -Path (Join-Path -Path $newModuleRoot -ChildPath "$script:PublishModuleName.psd1") -ModuleVersion $version -Description "$script:PublishModuleName module" + + Publish-PSResource -Path $newModuleRoot -Repository $testRepository2 + + $expectedPath = Join-Path -Path $script:repositoryPath2 -ChildPath "$script:PublishModuleName.$version.nupkg" + (Get-ChildItem $script:repositoryPath2).FullName | Should -Be $expectedPath + } + + It "Publish a module with -Path pointing to a .psd1 (parent directory has same name)" { + $version = "1.0.0" + $manifestPath = Join-Path -Path $script:PublishModuleBase -ChildPath "$script:PublishModuleName.psd1" + New-ModuleManifest -Path $manifestPath -ModuleVersion $version -Description "$script:PublishModuleName module" + + Publish-PSResource -Path $manifestPath -Repository $testRepository2 + + $expectedPath = Join-Path -Path $script:repositoryPath2 -ChildPath "$script:PublishModuleName.$version.nupkg" + (Get-ChildItem $script:repositoryPath2).FullName | Should -Be $expectedPath + } + + It "Publish a module with -Path pointing to a .psd1 (parent directory has different name)" { + $version = "1.0.0" + $newModuleRoot = Join-Path -Path $script:PublishModuleBase -ChildPath "NewTestParentDirectory" + New-Item -Path $newModuleRoot -ItemType Directory + $manifestPath = Join-Path -Path $newModuleRoot -ChildPath "$script:PublishModuleName.psd1" + New-ModuleManifest -Path $manifestPath -ModuleVersion $version -Description "$script:PublishModuleName module" + + Publish-PSResource -Path $manifestPath -Repository $testRepository2 + + $expectedPath = Join-Path -Path $script:repositoryPath2 -ChildPath "$script:PublishModuleName.$version.nupkg" + (Get-ChildItem $script:repositoryPath2).FullName | Should -Be $expectedPath + } + It "Publish a module with dependencies" { # Create dependency module $dependencyVersion = "2.0.0" diff --git a/test/RegisterPSResourceRepository.Tests.ps1 b/test/RegisterPSResourceRepository.Tests.ps1 index acaeca848..4853495ac 100644 --- a/test/RegisterPSResourceRepository.Tests.ps1 +++ b/test/RegisterPSResourceRepository.Tests.ps1 @@ -234,23 +234,94 @@ Describe "Test Register-PSResourceRepository" { $res3.Name | Should -Be $TestRepoName3 } - $testCases2 = @{Type = "-Name is not specified"; IncorrectHashTable = @{Uri = $tmpDir1Path}; ErrorId = "NullNameForRepositoriesParameterSetRegistration,Microsoft.PowerShell.PowerShellGet.Cmdlets.RegisterPSResourceRepository"}, - @{Type = "-Name is PSGallery"; IncorrectHashTable = @{Name = $PSGalleryName; Uri = $tmpDir1Path}; ErrorId = "PSGalleryProvidedAsNameRepoPSet,Microsoft.PowerShell.PowerShellGet.Cmdlets.RegisterPSResourceRepository"}, - @{Type = "-Uri not specified"; IncorrectHashTable = @{Name = $TestRepoName1}; ErrorId = "NullUriForRepositoriesParameterSetRegistration,Microsoft.PowerShell.PowerShellGet.Cmdlets.RegisterPSResourceRepository"}, - @{Type = "-Uri is not valid scheme"; IncorrectHashTable = @{Name = $TestRepoName1; Uri="www.google.com"}; ErrorId = "InvalidUri,Microsoft.PowerShell.PowerShellGet.Cmdlets.RegisterPSResourceRepository"} + It "not register incorrectly formatted -Name type repo among correct ones, where incorrect one is missing -Name" { + $correctHashtable1 = @{Name = $TestRepoName2; Uri = $tmpDir2Path; Trusted = $True} + $correctHashtable2 = @{Name = $TestRepoName3; Uri = $tmpDir3Path; Trusted = $True; Priority = 20} + $correctHashtable3 = @{PSGallery = $True; Priority = 30}; + $IncorrectHashTable = @{Uri = $tmpDir1Path}; + + $arrayOfHashtables = $correctHashtable1, $correctHashtable2, $IncorrectHashTable, $correctHashtable3 + Unregister-PSResourceRepository -Name $PSGalleryName + Register-PSResourceRepository -Repository $arrayOfHashtables -ErrorVariable err -ErrorAction SilentlyContinue + + $ErrorId = "NullNameForRepositoriesParameterSetRegistration,Microsoft.PowerShell.PowerShellGet.Cmdlets.RegisterPSResourceRepository" + $err.Count | Should -Not -Be 0 + $err[0].FullyQualifiedErrorId | Should -Be $ErrorId + + $res = Get-PSResourceRepository -Name $TestRepoName2 + $res.Name | Should -Be $TestRepoName2 + + $res2 = Get-PSResourceRepository -Name $TestRepoName3 + $res2.Name | Should -Be $TestRepoName3 + + $res3 = Get-PSResourceRepository -Name $PSGalleryName + $res3.Name | Should -Be $PSGalleryName + $res3.Priority | Should -Be 30 + } + + It "not register incorrectly formatted -Name type repo among correct ones, where incorrect type has -Name of PSGallery" { + $correctHashtable1 = @{Name = $TestRepoName2; Uri = $tmpDir2Path; Trusted = $True} + $correctHashtable2 = @{Name = $TestRepoName3; Uri = $tmpDir3Path; Trusted = $True; Priority = 20} + $correctHashtable3 = @{PSGallery = $True; Priority = 30}; + $IncorrectHashTable = @{Name = $PSGalleryName; Uri = $tmpDir1Path}; + + $arrayOfHashtables = $correctHashtable1, $correctHashtable2, $IncorrectHashTable, $correctHashtable3 + Unregister-PSResourceRepository -Name $PSGalleryName + Register-PSResourceRepository -Repository $arrayOfHashtables -ErrorVariable err -ErrorAction SilentlyContinue + + $ErrorId = "PSGalleryProvidedAsNameRepoPSet,Microsoft.PowerShell.PowerShellGet.Cmdlets.RegisterPSResourceRepository" + $err.Count | Should -Not -Be 0 + $err[0].FullyQualifiedErrorId | Should -Be $ErrorId + + $res = Get-PSResourceRepository -Name $TestRepoName2 + $res.Name | Should -Be $TestRepoName2 + + $res2 = Get-PSResourceRepository -Name $TestRepoName3 + $res2.Name | Should -Be $TestRepoName3 - It "not register incorrectly formatted Name type repo among correct ones when incorrect type is " -TestCases $testCases2 { - param($Type, $IncorrectHashTable, $ErrorId) + $res3 = Get-PSResourceRepository -Name $PSGalleryName + $res3.Name | Should -Be $PSGalleryName + $res3.Priority | Should -Be 30 + } + It "not register incorrectly formatted Name type repo among correct ones when incorrect type is -Uri not specified" { $correctHashtable1 = @{Name = $TestRepoName2; Uri = $tmpDir2Path; Trusted = $True} $correctHashtable2 = @{Name = $TestRepoName3; Uri = $tmpDir3Path; Trusted = $True; Priority = 20} $correctHashtable3 = @{PSGallery = $True; Priority = 30}; + $IncorrectHashTable = @{Name = $TestRepoName1}; $arrayOfHashtables = $correctHashtable1, $correctHashtable2, $IncorrectHashTable, $correctHashtable3 Unregister-PSResourceRepository -Name $PSGalleryName Register-PSResourceRepository -Repository $arrayOfHashtables -ErrorVariable err -ErrorAction SilentlyContinue + + $ErrorId = "NullUriForRepositoriesParameterSetRegistration,Microsoft.PowerShell.PowerShellGet.Cmdlets.RegisterPSResourceRepository" $err.Count | Should -Not -Be 0 - $err[0].FullyQualifiedErrorId | Should -BeExactly $ErrorId + $err[0].FullyQualifiedErrorId | Should -Be $ErrorId + + $res = Get-PSResourceRepository -Name $TestRepoName2 + $res.Name | Should -Be $TestRepoName2 + + $res2 = Get-PSResourceRepository -Name $TestRepoName3 + $res2.Name | Should -Be $TestRepoName3 + + $res3 = Get-PSResourceRepository -Name $PSGalleryName + $res3.Name | Should -Be $PSGalleryName + $res3.Priority | Should -Be 30 + } + + It "not register incorrectly formatted Name type repo among correct ones when incorrect type is -Uri is not valid scheme" { + $correctHashtable1 = @{Name = $TestRepoName2; Uri = $tmpDir2Path; Trusted = $True} + $correctHashtable2 = @{Name = $TestRepoName3; Uri = $tmpDir3Path; Trusted = $True; Priority = 20} + $correctHashtable3 = @{PSGallery = $True; Priority = 30}; + $IncorrectHashTable = @{Name = $TestRepoName1; Uri="www.google.com"}; + + $arrayOfHashtables = $correctHashtable1, $correctHashtable2, $IncorrectHashTable, $correctHashtable3 + Unregister-PSResourceRepository -Name $PSGalleryName + Register-PSResourceRepository -Repository $arrayOfHashtables -ErrorVariable err -ErrorAction SilentlyContinue + + $ErrorId = "InvalidUri,Microsoft.PowerShell.PowerShellGet.Cmdlets.RegisterPSResourceRepository" + $err.Count | Should -Not -Be 0 + $err[0].FullyQualifiedErrorId | Should -Be $ErrorId $res = Get-PSResourceRepository -Name $TestRepoName2 $res.Name | Should -Be $TestRepoName2 @@ -273,6 +344,17 @@ Describe "Test Register-PSResourceRepository" { $res.Priority | Should -Be 50 } + It "should update a repository if -Force is used" { + Register-PSResourceRepository -Name $TestRepoName1 -Uri "./" + Register-PSResourceRepository -Name $TestRepoName1 -Uri "./" -Priority 3 -Force + $res = Get-PSResourceRepository -Name $TestRepoName1 + + $res.Name | Should -Be $TestRepoName1 + $Res.Uri.LocalPath | Should -Contain $relativeCurrentPath + $res.Trusted | Should -Be False + $res.Priority | Should -Be 3 + } + It "should register local file share NuGet based repository" { Register-PSResourceRepository -Name "localFileShareTestRepo" -Uri "\\hcgg.rest.of.domain.name\test\ITxx\team\NuGet\" $res = Get-PSResourceRepository -Name "localFileShareTestRepo" @@ -290,7 +372,7 @@ Describe "Test Register-PSResourceRepository" { } It "throws error if CredentialInfo is passed in with Credential property without SecretManagement module setup" { - { Register-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path -Trusted -Priority 20 -CredentialInfo $credentialInfo2 } | Should -Throw -ErrorId "RepositoryCredentialSecretManagementUnavailableModule" + { Register-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path -Trusted -Priority 20 -CredentialInfo $credentialInfo2 } | Should -Throw -ErrorId "ErrorInNameParameterSet,Microsoft.PowerShell.PowerShellGet.Cmdlets.RegisterPSResourceRepository" $res = Get-PSResourceRepository -Name $TestRepoName1 -ErrorAction Ignore $res | Should -BeNullOrEmpty diff --git a/test/SavePSResource.Tests.ps1 b/test/SavePSResource.Tests.ps1 index b9ddac47d..2d5e2e27f 100644 --- a/test/SavePSResource.Tests.ps1 +++ b/test/SavePSResource.Tests.ps1 @@ -217,7 +217,7 @@ Describe 'Test Save-PSResource for PSResources' { } It "Save module and include XML metadata file" { - Save-PSResource -Name $testModuleName -Version "1.0.0" -Repository $PSGalleryName -Path $SaveDir -IncludeXML -TrustRepository + Save-PSResource -Name $testModuleName -Version "1.0.0" -Repository $PSGalleryName -Path $SaveDir -IncludeXml -TrustRepository $pkgDir = Get-ChildItem -Path $SaveDir | Where-Object Name -eq $testModuleName $pkgDir | Should -Not -BeNullOrEmpty $pkgDirVersion = Get-ChildItem -Path $pkgDir.FullName diff --git a/test/SetPSResourceRepository.Tests.ps1 b/test/SetPSResourceRepository.Tests.ps1 index 25eb1c820..cc8661258 100644 --- a/test/SetPSResourceRepository.Tests.ps1 +++ b/test/SetPSResourceRepository.Tests.ps1 @@ -69,6 +69,17 @@ Describe "Test Set-PSResourceRepository" { $res.CredentialInfo | Should -BeNullOrEmpty } + It "set repository given pipeline input ValueFromPipelineByPropertyName passed in" { + Register-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path + Get-PSResourceRepository -Name $TestRepoName1 | Set-PSResourceRepository -Trusted + $res = Get-PSResourceRepository -Name $TestRepoName1 + $res.Name | Should -Be $TestRepoName1 + $Res.Uri.LocalPath | Should -Contain $tmpDir1Path + $res.Priority | Should -Be 50 + $res.Trusted | Should -Be True + $res.CredentialInfo | Should -BeNullOrEmpty + } + It "set repository given Name and CredentialInfo parameters" { Register-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path Set-PSResourceRepository -Name $TestRepoName1 -CredentialInfo $credentialInfo1 @@ -98,8 +109,8 @@ Describe "Test Set-PSResourceRepository" { {Set-PSResourceRepository -Name $Name -Priority 25 -ErrorAction Stop} | Should -Throw -ErrorId "$ErrorId,Microsoft.PowerShell.PowerShellGet.Cmdlets.SetPSResourceRepository" } - $testCases2 = @{Type = "contains *"; Name = "test*Repository2"; ErrorId = "ErrorSettingIndividualRepoFromRepositories"}, - @{Type = "is whitespace"; Name = " "; ErrorId = "ErrorSettingIndividualRepoFromRepositories"}, + $testCases2 = @{Type = "contains *"; Name = "test*Repository2"; ErrorId = "ErrorSettingRepository"}, + @{Type = "is whitespace"; Name = " "; ErrorId = "ErrorSettingRepository"}, @{Type = "is null"; Name = $null; ErrorId = "NullNameForRepositoriesParameterSetRepo"} It "not set repository and write error given Name (RepositoriesParameterSet)" -TestCases $testCases2 { param($Type, $Name, $ErrorId) @@ -194,7 +205,7 @@ Describe "Test Set-PSResourceRepository" { Set-PSResourceRepository -Repository $arrayOfHashtables -ErrorVariable err -ErrorAction SilentlyContinue $err.Count | Should -Not -Be 0 - $err[0].FullyQualifiedErrorId | Should -BeExactly "ErrorSettingIndividualRepoFromRepositories,Microsoft.PowerShell.PowerShellGet.Cmdlets.SetPSResourceRepository" + $err[0].FullyQualifiedErrorId | Should -BeExactly "ErrorSettingRepository,Microsoft.PowerShell.PowerShellGet.Cmdlets.SetPSResourceRepository" $res = Get-PSResourceRepository -Name $TestRepoName1 $Res.Uri.LocalPath | Should -Contain $tmpDir1Path @@ -224,7 +235,7 @@ Describe "Test Set-PSResourceRepository" { Set-PSResourceRepository -Repository $arrayOfHashtables -ErrorVariable err -ErrorAction SilentlyContinue $err.Count | Should -Not -Be 0 - $err[0].FullyQualifiedErrorId | Should -BeExactly "ErrorSettingIndividualRepoFromRepositories,Microsoft.PowerShell.PowerShellGet.Cmdlets.SetPSResourceRepository" + $err[0].FullyQualifiedErrorId | Should -BeExactly "ErrorSettingRepository,Microsoft.PowerShell.PowerShellGet.Cmdlets.SetPSResourceRepository" $res = Get-PSResourceRepository -Name $TestRepoName1 $Res.Uri.LocalPath | Should -Contain $tmpDir1Path @@ -241,6 +252,17 @@ Describe "Test Set-PSResourceRepository" { $Res.Uri.LocalPath | Should -Contain "\\hcgg.rest.of.domain.name\test\ITxx\team\NuGet\" } + It "set repository should register repository if it does not already exist" { + $testRepoName = "NewForceTestRepo" + Set-PSResourceRepository -Name $testRepoName -Uri $tmpDir1Path -PassThru + + $res = Get-PSResourceRepository -Name $testRepoName + $res.Name | Should -Be $testRepoName + $Res.Uri.LocalPath | Should -Contain $tmpDir1Path + $res.Priority | Should -Be 50 + $res.Trusted | Should -Be False + } + It "set repository and see updated repository with -PassThru" { Register-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path $res = Set-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir2Path -PassThru @@ -263,7 +285,7 @@ Describe "Test Set-PSResourceRepository" { { Register-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path Set-PSResourceRepository -Name $TestRepoName1 -Uri $tmpDir1Path -CredentialInfo $credentialInfo2 - } | Should -Throw -ErrorId "RepositoryCredentialSecretManagementUnavailableModule" + } | Should -Throw -ErrorId "ErrorInNameParameterSet,Microsoft.PowerShell.PowerShellGet.Cmdlets.SetPSResourceRepository" $res = Get-PSResourceRepository -Name $TestRepoName1 -ErrorAction Ignore $res.CredentialInfo | Should -BeNullOrEmpty diff --git a/test/TestPSScriptFileInfo.Tests.ps1 b/test/TestPSScriptFileInfo.Tests.ps1 index 30adae47b..eb1079c22 100644 --- a/test/TestPSScriptFileInfo.Tests.ps1 +++ b/test/TestPSScriptFileInfo.Tests.ps1 @@ -57,4 +57,18 @@ Describe "Test Test-PSScriptFileInfo" { Test-PSScriptFileInfo $scriptFilePath | Should -Be $false } + + It "determine script without empty lines in PSScriptInfo comment content is valid" { + $scriptName = "ScriptWithoutEmptyLinesInMetadata.ps1" + $scriptFilePath = Join-Path $script:testScriptsFolderPath -ChildPath $scriptName + + Test-PSScriptFileInfo $scriptFilePath | Should -Be $true + } + + It "determine script without empty lines between comment blocks is valid" { + $scriptName = "ScriptWithoutEmptyLinesBetweenCommentBlocks.ps1" + $scriptFilePath = Join-Path $script:testScriptsFolderPath -ChildPath $scriptName + + Test-PSScriptFileInfo $scriptFilePath | Should -Be $true + } } diff --git a/test/testFiles/testScripts/ScriptWithoutEmptyLinesBetweenCommentBlocks.ps1 b/test/testFiles/testScripts/ScriptWithoutEmptyLinesBetweenCommentBlocks.ps1 new file mode 100644 index 000000000..8d8d2aa88 --- /dev/null +++ b/test/testFiles/testScripts/ScriptWithoutEmptyLinesBetweenCommentBlocks.ps1 @@ -0,0 +1,24 @@ + +<#PSScriptInfo +.VERSION 1.0 +.GUID 3951be04-bd06-4337-8dc3-a620bf539fbd +.AUTHOR annavied +.COMPANYNAME +.COPYRIGHT +.TAGS +.LICENSEURI +.PROJECTURI +.ICONURI +.EXTERNALMODULEDEPENDENCIES +.REQUIREDSCRIPTS +.EXTERNALSCRIPTDEPENDENCIES +.RELEASENOTES +.PRIVATEDATA +#> +<# + +.DESCRIPTION + this is a test for a script that will be published remotely + +#> +Param() diff --git a/test/testFiles/testScripts/ScriptWithoutEmptyLinesInMetadata.ps1 b/test/testFiles/testScripts/ScriptWithoutEmptyLinesInMetadata.ps1 new file mode 100644 index 000000000..2b28db61f --- /dev/null +++ b/test/testFiles/testScripts/ScriptWithoutEmptyLinesInMetadata.ps1 @@ -0,0 +1,23 @@ + +<#PSScriptInfo +.VERSION 1.0 +.GUID 3951be04-bd06-4337-8dc3-a620bf539fbd +.AUTHOR annavied +.COMPANYNAME +.COPYRIGHT +.TAGS +.LICENSEURI +.PROJECTURI +.ICONURI +.EXTERNALMODULEDEPENDENCIES +.REQUIREDSCRIPTS +.EXTERNALSCRIPTDEPENDENCIES +.RELEASENOTES +.PRIVATEDATA +#> + +<# +.DESCRIPTION + this is a test for a script that will be published remotely +#> +Param() From 8493987ba65b1f6184bc021775e76df2c1e25957 Mon Sep 17 00:00:00 2001 From: Amber Erickson Date: Mon, 15 Aug 2022 07:58:34 -0700 Subject: [PATCH 2/8] Update moduleManifest variable path --- src/code/PublishPSResource.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/code/PublishPSResource.cs b/src/code/PublishPSResource.cs index 9c3064e98..12a20cd5c 100644 --- a/src/code/PublishPSResource.cs +++ b/src/code/PublishPSResource.cs @@ -280,7 +280,7 @@ protected override void EndProcessing() string[] errorMsgs = null; try { - Utils.ValidateModuleManifest(resourceFilePath, out errorMsgs); + Utils.ValidateModuleManifest(pathToModuleManifestToPublish, out errorMsgs); } finally { From c1e5c1ecb0909731153754fca17ff7cb03d75e90 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Mon, 15 Aug 2022 15:13:15 -0700 Subject: [PATCH 3/8] Update src/code/PublishPSResource.cs Co-authored-by: Paul Higinbotham --- src/code/PublishPSResource.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/code/PublishPSResource.cs b/src/code/PublishPSResource.cs index 12a20cd5c..83ab8479d 100644 --- a/src/code/PublishPSResource.cs +++ b/src/code/PublishPSResource.cs @@ -268,7 +268,8 @@ protected override void EndProcessing() // Validate that there's a module manifest if (!File.Exists(pathToModuleManifestToPublish)) { - var message = String.Format("No file with a .psd1 extension was found in {0}. Please specify a path to a valid modulemanifest.", _path); + var message = String.Format("No file with a .psd1 extension was found in {0}. Please specify a path to a valid modulemanifest.", pathToModuleManifestToPublish); + var ex = new ArgumentException(message); var moduleManifestNotFound = new ErrorRecord(ex, "moduleManifestNotFound", ErrorCategory.ObjectNotFound, null); WriteError(moduleManifestNotFound); From c1af4049f4b655d298b58c23aa945f309267f7b8 Mon Sep 17 00:00:00 2001 From: alerickson <25858831+alerickson@users.noreply.github.com> Date: Mon, 15 Aug 2022 15:14:47 -0700 Subject: [PATCH 4/8] Update src/code/PublishPSResource.cs Co-authored-by: Paul Higinbotham --- src/code/PublishPSResource.cs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/code/PublishPSResource.cs b/src/code/PublishPSResource.cs index 83ab8479d..225103f32 100644 --- a/src/code/PublishPSResource.cs +++ b/src/code/PublishPSResource.cs @@ -379,7 +379,8 @@ protected override void EndProcessing() if (resourceType == ResourceType.Script) { // copy the script file to the temp directory - File.Copy(_path, System.IO.Path.Combine(outputDir, _pkgName + PSScriptFileExt), true); + File.Copy(pathToScriptFileToPublish, System.IO.Path.Combine(outputDir, _pkgName + PSScriptFileExt), true); + } else { From e2a7a5fe008a8a4b724274eaacd3889027ccb6c8 Mon Sep 17 00:00:00 2001 From: Amber Erickson Date: Mon, 15 Aug 2022 15:18:07 -0700 Subject: [PATCH 5/8] Incorporate first part of new code review suggestions --- src/code/PublishPSResource.cs | 52 +++++++++++++++++------------------ 1 file changed, 25 insertions(+), 27 deletions(-) diff --git a/src/code/PublishPSResource.cs b/src/code/PublishPSResource.cs index 12a20cd5c..b0751dfdc 100644 --- a/src/code/PublishPSResource.cs +++ b/src/code/PublishPSResource.cs @@ -4,11 +4,11 @@ using Microsoft.PowerShell.PowerShellGet.UtilClasses; using MoreLinq; using MoreLinq.Extensions; -using NuGet.Commands; -using NuGet.Common; -using NuGet.Configuration; -using NuGet.Packaging; -using NuGet.Versioning; +using NuGet.Commands; // pack and PUSH +//using NuGet.Common; // only the logger +using NuGet.Configuration; // PUSH +using NuGet.Packaging; // pack +using NuGet.Versioning; // can keep using System; using System.Collections; using System.Collections.Generic; @@ -115,7 +115,7 @@ public PSCredential ProxyCredential { #region Members - private string _path; + private string resolvedPath; private CancellationToken _cancellationToken; private NuGetVersion _pkgVersion; private string _pkgName; @@ -140,7 +140,6 @@ protected override void BeginProcessing() // This is to create a better experience for those who have just installed v3 and want to get up and running quickly RepositorySettings.CheckRepositoryStore(); - string resolvedPath = string.Empty; try { resolvedPath = SessionState.Path.GetResolvedPSPathFromPSPath(Path).First().Path; @@ -159,8 +158,18 @@ protected override void BeginProcessing() // Condition 1: path is to the root directory of the module to be published // Condition 2: path is to the .psd1 or .ps1 of the module/script to be published - _path = resolvedPath; - if (Directory.Exists(resolvedPath)) + if (string.IsNullOrEmpty(resolvedPath)) + { + // unsupported file path + ThrowTerminatingError( + new ErrorRecord( + new ArgumentException( + "The path to the resource to publish is not in the correct format, point to a path or file of the module or script to publish."), + "InvalidSourcePath", + ErrorCategory.InvalidArgument, + this)); + } + else if (Directory.Exists(resolvedPath)) { pathToModuleDirToPublish = resolvedPath; resourceType = ResourceType.Module; @@ -175,17 +184,6 @@ protected override void BeginProcessing() pathToScriptFileToPublish = resolvedPath; resourceType = ResourceType.Script; } - else if (string.IsNullOrEmpty(resolvedPath)) - { - // unsupported file path - ThrowTerminatingError( - new ErrorRecord( - new ArgumentException( - "The path to the resource to publish is not in the correct format, point to a path or file of the module or script to publish."), - "InvalidSourcePath", - ErrorCategory.InvalidArgument, - this)); - } if (!String.IsNullOrEmpty(DestinationPath)) { @@ -215,7 +213,7 @@ protected override void BeginProcessing() protected override void EndProcessing() { // Returns the name of the file or the name of the directory, depending on path - if (!ShouldProcess(string.Format("Publish resource '{0}' from the machine", _path))) + if (!ShouldProcess(string.Format("Publish resource '{0}' from the machine", resolvedPath))) { WriteVerbose("ShouldProcess is set to false."); return; @@ -268,7 +266,7 @@ protected override void EndProcessing() // Validate that there's a module manifest if (!File.Exists(pathToModuleManifestToPublish)) { - var message = String.Format("No file with a .psd1 extension was found in {0}. Please specify a path to a valid modulemanifest.", _path); + var message = String.Format("No file with a .psd1 extension was found in {0}. Please specify a path to a valid modulemanifest.", resolvedPath); var ex = new ArgumentException(message); var moduleManifestNotFound = new ErrorRecord(ex, "moduleManifestNotFound", ErrorCategory.ObjectNotFound, null); WriteError(moduleManifestNotFound); @@ -378,14 +376,14 @@ protected override void EndProcessing() if (resourceType == ResourceType.Script) { // copy the script file to the temp directory - File.Copy(_path, System.IO.Path.Combine(outputDir, _pkgName + PSScriptFileExt), true); + File.Copy(resolvedPath, System.IO.Path.Combine(outputDir, _pkgName + PSScriptFileExt), true); } else { try { // If path is pointing to a file, get the parent directory, otherwise assumption is that path is pointing to the root directory - string rootModuleDir = !string.IsNullOrEmpty(pathToModuleManifestToPublish) ? new FileInfo(_path).Directory.FullName : _path; + string rootModuleDir = !string.IsNullOrEmpty(pathToModuleManifestToPublish) ? new FileInfo(resolvedPath).Directory.FullName : resolvedPath; // Create subdirectory structure in temp folder foreach (string dir in System.IO.Directory.GetDirectories(rootModuleDir, "*", System.IO.SearchOption.AllDirectories)) @@ -968,7 +966,7 @@ private bool PackNupkg(string outputDir, string outputNupkgDir, string nuspecFil Path = nuspecFile, Exclude = System.Array.Empty(), Symbols = false, - Logger = NullLogger.Instance + Logger = null }, MSBuildProjectFactory.ProjectCreator, builder); @@ -1015,7 +1013,7 @@ private bool PushNupkg(string outputNupkgDir, string repoName, string repoUri, o string publishLocation = repoUri.EndsWith("/v2", StringComparison.OrdinalIgnoreCase) ? repoUri + "/package" : repoUri; var settings = NuGet.Configuration.Settings.LoadDefaultSettings(null, null, null); - ILogger log = new NuGetLogger(); + // ILogger log = new NuGetLogger(); var success = false; try { @@ -1032,7 +1030,7 @@ private bool PushNupkg(string outputNupkgDir, string repoName, string repoUri, o noSymbols: false, noServiceEndpoint: false, // enable server endpoint skipDuplicate: false, // if true-- if a package and version already exists, skip it and continue with the next package in the push, if any. - logger: log // nuget logger + logger: null // nuget logger ).GetAwaiter().GetResult(); } catch (HttpRequestException e) From 126dbe7e093aba3ec927f0a3269dd71f34072a9f Mon Sep 17 00:00:00 2001 From: Amber Erickson Date: Mon, 15 Aug 2022 15:35:05 -0700 Subject: [PATCH 6/8] Accidentally commented out using directives, adding back in --- src/code/PublishPSResource.cs | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/src/code/PublishPSResource.cs b/src/code/PublishPSResource.cs index f9beb2250..09a481280 100644 --- a/src/code/PublishPSResource.cs +++ b/src/code/PublishPSResource.cs @@ -4,11 +4,10 @@ using Microsoft.PowerShell.PowerShellGet.UtilClasses; using MoreLinq; using MoreLinq.Extensions; -using NuGet.Commands; // pack and PUSH -//using NuGet.Common; // only the logger -using NuGet.Configuration; // PUSH -using NuGet.Packaging; // pack -using NuGet.Versioning; // can keep +using NuGet.Commands; +using NuGet.Configuration; +using NuGet.Packaging; +using NuGet.Versioning; using System; using System.Collections; using System.Collections.Generic; @@ -408,6 +407,8 @@ protected override void EndProcessing() System.IO.File.Copy(fileNamePath, newFilePath); } } + + } catch (Exception e) { From aafbff7299756084da56449446bee37287805064 Mon Sep 17 00:00:00 2001 From: Amber Erickson Date: Mon, 15 Aug 2022 15:37:48 -0700 Subject: [PATCH 7/8] Variable refactor (code review suggestion) --- src/code/PublishPSResource.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/code/PublishPSResource.cs b/src/code/PublishPSResource.cs index 09a481280..c3f23d3d5 100644 --- a/src/code/PublishPSResource.cs +++ b/src/code/PublishPSResource.cs @@ -384,7 +384,7 @@ protected override void EndProcessing() try { // If path is pointing to a file, get the parent directory, otherwise assumption is that path is pointing to the root directory - string rootModuleDir = !string.IsNullOrEmpty(pathToModuleManifestToPublish) ? new FileInfo(resolvedPath).Directory.FullName : resolvedPath; + string rootModuleDir = !string.IsNullOrEmpty(pathToModuleManifestToPublish) ? System.IO.Path.GetDirectoryName(pathToModuleManifestToPublish) : pathToModuleDirToPublish; // Create subdirectory structure in temp folder foreach (string dir in System.IO.Directory.GetDirectories(rootModuleDir, "*", System.IO.SearchOption.AllDirectories)) From c7e36892135bc6dbc4500ec27077d71885dd3cab Mon Sep 17 00:00:00 2001 From: Amber Erickson Date: Mon, 15 Aug 2022 16:15:59 -0700 Subject: [PATCH 8/8] Add NuGet logger back in --- src/code/PublishPSResource.cs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/code/PublishPSResource.cs b/src/code/PublishPSResource.cs index c3f23d3d5..714516e70 100644 --- a/src/code/PublishPSResource.cs +++ b/src/code/PublishPSResource.cs @@ -5,6 +5,7 @@ using MoreLinq; using MoreLinq.Extensions; using NuGet.Commands; +using NuGet.Common; using NuGet.Configuration; using NuGet.Packaging; using NuGet.Versioning; @@ -969,7 +970,7 @@ private bool PackNupkg(string outputDir, string outputNupkgDir, string nuspecFil Path = nuspecFile, Exclude = System.Array.Empty(), Symbols = false, - Logger = null + Logger = NullLogger.Instance }, MSBuildProjectFactory.ProjectCreator, builder); @@ -1016,7 +1017,6 @@ private bool PushNupkg(string outputNupkgDir, string repoName, string repoUri, o string publishLocation = repoUri.EndsWith("/v2", StringComparison.OrdinalIgnoreCase) ? repoUri + "/package" : repoUri; var settings = NuGet.Configuration.Settings.LoadDefaultSettings(null, null, null); - // ILogger log = new NuGetLogger(); var success = false; try { @@ -1033,7 +1033,7 @@ private bool PushNupkg(string outputNupkgDir, string repoName, string repoUri, o noSymbols: false, noServiceEndpoint: false, // enable server endpoint skipDuplicate: false, // if true-- if a package and version already exists, skip it and continue with the next package in the push, if any. - logger: null // nuget logger + logger: NullLogger.Instance // nuget logger ).GetAwaiter().GetResult(); } catch (HttpRequestException e)