├── Test
├── run-tests.ps1
├── PSModule
│ ├── PSModule.IntegrationTest.Tests.ps1
│ ├── PSModule.Get.Tests.ps1
│ └── PSModule.Set.and.Test.Tests.ps1
├── NugetPackage
│ ├── NugetPackage.IntegrationTest.Tests.ps1
│ ├── NugetPackage.Test.Tests.ps1
│ ├── NugetPackage.Get.Tests.ps1
│ └── NugetPackage.Set.Tests.ps1
├── PackageManagement
│ ├── PackageManagement.Test.Tests.ps1
│ ├── PackageManagement.Set.Tests.ps1
│ └── PackageManagement.Get.Tests.ps1
├── PackageManagementSource
│ └── OneGetSource.Get.Set.Test.Tests.ps1
└── OneGetTestHelper.ps1
├── DSCResources
├── MSFT_NugetPackage
│ ├── MSFT_NugetPackage.psm1
│ ├── MSFT_NugetPackage.schema.mof
│ ├── MSFT_NugetPackage.schema.mfl
│ └── MSFT_NugetPackage.strings.psd1
├── MSFT_PackageManagementSource
│ ├── MSFT_PackageManagementSource.psm1
│ ├── MSFT_PackageManagementSource.schema.mof
│ ├── MSFT_PackageManagementSource.schema.mfl
│ └── MSFT_PackageManagementSource.strings.psd1
├── MSFT_PackageManagement
│ ├── MSFT_PackageManagement.schema.mof
│ ├── MSFT_PackageManagement.schema.mfl
│ ├── MSFT_PackageManagement.strings.psd1
│ └── MSFT_PackageManagement.psm1
├── MSFT_PSModule
│ ├── MSFT_PSModule.schema.mof
│ ├── MSFT_PSModule.schema.mfl
│ ├── MSFT_PSModule.strings.psd1
│ └── MSFT_PSModule.psm1
├── OneGetHelper.strings.psd1
└── OneGetHelper.psm1
├── LICENSE.txt
├── Examples
├── Sample_PSModule.ps1
├── Sample_Install_Package.ps1
├── Sample_Install_Pester.ps1
├── Sample_NuGet_InstallPackage.ps1
└── Sample_Install_Package_Using_NuGet.ps1
├── appveyor.yml
├── PackageManagementProviderResource.psd1
└── README.md
/Test/run-tests.ps1:
--------------------------------------------------------------------------------
1 | cd "$PSScriptRoot"
2 | invoke-pester
3 |
--------------------------------------------------------------------------------
/DSCResources/MSFT_NugetPackage/MSFT_NugetPackage.psm1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PowerShell/PackageManagementProviderResource/HEAD/DSCResources/MSFT_NugetPackage/MSFT_NugetPackage.psm1
--------------------------------------------------------------------------------
/DSCResources/MSFT_PackageManagementSource/MSFT_PackageManagementSource.psm1:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/PowerShell/PackageManagementProviderResource/HEAD/DSCResources/MSFT_PackageManagementSource/MSFT_PackageManagementSource.psm1
--------------------------------------------------------------------------------
/DSCResources/MSFT_PackageManagementSource/MSFT_PackageManagementSource.schema.mof:
--------------------------------------------------------------------------------
1 |
2 | [ClassVersion("1.0.0.0"),FriendlyName("PackageManagementSource")]
3 | class MSFT_PackageManagementSource : OMI_BaseResource
4 | {
5 | [Key] string Name;
6 | [Required] String ProviderName;
7 | [Required] String SourceUri;
8 | [Write,ValueMap{"Present", "Absent"},Values{"Present", "Absent"}] String Ensure;
9 | [Write,EmbeddedInstance("MSFT_Credential")] String SourceCredential;
10 | [Write,ValueMap{"Trusted", "Untrusted"},Values{"Trusted", "Untrusted"}] String InstallationPolicy;
11 | };
12 |
--------------------------------------------------------------------------------
/DSCResources/MSFT_PackageManagement/MSFT_PackageManagement.schema.mof:
--------------------------------------------------------------------------------
1 |
2 | [ClassVersion("1.0.0.0"),FriendlyName("PackageManagement")]
3 | class MSFT_PackageManagement : OMI_BaseResource
4 | {
5 | [Key] string Name;
6 | [Write] string RequiredVersion;
7 | [Write] string MinimumVersion;
8 | [Write] string MaximumVersion;
9 | [Write] string Source;
10 | [Write,EmbeddedInstance("MSFT_Credential")] String SourceCredential;
11 | [Write] String ProviderName;
12 | [Write, EmbeddedInstance("MSFT_KeyValuePair")] String AdditionalParameters[];
13 | [Write,ValueMap{"Present", "Absent"},Values{"Present", "Absent"}] String Ensure;
14 | };
15 |
--------------------------------------------------------------------------------
/DSCResources/MSFT_PSModule/MSFT_PSModule.schema.mof:
--------------------------------------------------------------------------------
1 |
2 | [ClassVersion("1.0.0.0"),FriendlyName("PSModule")]
3 | class MSFT_PSModule : OMI_BaseResource
4 | {
5 | [Key] String Name;
6 | [Write,ValueMap{"Present", "Absent"},Values{"Present", "Absent"}] String Ensure;
7 | [Write] String Repository;
8 | [Write,ValueMap{"Trusted", "Untrusted"},Values{"Trusted", "Untrusted"}] String InstallationPolicy;
9 | [Write] String RequiredVersion;
10 | [Write] String MaximumVersion;
11 | [Write] String MinimumVersion;
12 | [Read] string Description;
13 | [Read] String InstalledVersion;
14 | [Read] String Guid;
15 | [Read] String ModuleBase;
16 | [Read] String ModuleType;
17 | [Read] String Author;
18 | };
19 |
--------------------------------------------------------------------------------
/DSCResources/MSFT_NugetPackage/MSFT_NugetPackage.schema.mof:
--------------------------------------------------------------------------------
1 |
2 | [ClassVersion("1.0.0.0"),FriendlyName("NugetPackage")]
3 | class MSFT_NugetPackage : OMI_BaseResource
4 | {
5 | [Key] String Name;
6 | [Required] String DestinationPath;
7 | [Write,ValueMap{"Present", "Absent"},Values{"Present", "Absent"}] String Ensure;
8 | [Write,ValueMap{"Trusted", "Untrusted"},Values{"Trusted", "Untrusted"}] String InstallationPolicy;
9 | [Write] String RequiredVersion;
10 | [Write] String MaximumVersion;
11 | [Write] String MinimumVersion;
12 | [Write] String Source;
13 | [Write,EmbeddedInstance("MSFT_Credential")] String SourceCredential;
14 | [Read] string Description;
15 | [Read] String InstalledVersion;
16 | [Read] String SoftwareIdentity;
17 | };
18 |
--------------------------------------------------------------------------------
/DSCResources/MSFT_PackageManagement/MSFT_PackageManagement.schema.mfl:
--------------------------------------------------------------------------------
1 | #pragma namespace("\\\\.\\root\\default")
2 | instance of __namespace{ name="MS_409";};
3 | #pragma namespace("\\\\.\\root\\default\\MS_409")
4 |
5 | [AMENDMENT, LOCALE("MS_409")]
6 | class MSFT_PackageManagementSource : OMI_BaseResource
7 | {
8 | [Key,Description("The name of the package source.\n") : Amended] string Name;
9 | [Description("The name of the package provider.\n") : Amended] String ProviderName;
10 | [Description("The Uri location of the package source.\n") : Amended] String SourceUri;
11 | [Description("Whether the package source is to be registered or unregistered.\nPresent {default} \nAbsent \n") : Amended] String Ensure;
12 | [Description("The credential used to access repository of package source.\n") : Amended] String SourceCredential;
13 | [Description("Whether the package is trusted or untrusted.\nTrusted {default} \nUntrusted \n") : Amended] String InstallationPolicy;
14 | };
15 |
--------------------------------------------------------------------------------
/DSCResources/MSFT_PackageManagementSource/MSFT_PackageManagementSource.schema.mfl:
--------------------------------------------------------------------------------
1 | #pragma namespace("\\\\.\\root\\default")
2 | instance of __namespace{ name="MS_409";};
3 | #pragma namespace("\\\\.\\root\\default\\MS_409")
4 |
5 | [AMENDMENT, LOCALE("MS_409")]
6 | class MSFT_PackageManagementSource : OMI_BaseResource
7 | {
8 | [Key,Description("The name of the package source.\n") : Amended] string Name;
9 | [Description("The name of the package provider.\n") : Amended] String ProviderName;
10 | [Description("The Uri location of the package source.\n") : Amended] String SourceUri;
11 | [Description("Whether the package source is to be registered or unregistered.\nPresent {default} \nAbsent \n") : Amended] String Ensure;
12 | [Description("The credential used to access repository of package source.\n") : Amended] String SourceCredential;
13 | [Description("Whether the package is trusted or untrusted.\nTrusted {default} \nUntrusted \n") : Amended] String InstallationPolicy;
14 | };
15 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | The MIT License (MIT)
2 |
3 | Copyright (c) 2015 Microsoft Corporation.
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in
13 | all copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 | THE SOFTWARE.
22 |
--------------------------------------------------------------------------------
/DSCResources/OneGetHelper.strings.psd1:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (c) Microsoft Corporation.
3 | #
4 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10 | # THE SOFTWARE.
11 | #
12 | # culture="en-US"
13 | ConvertFrom-StringData @'
14 | ###PSLOC
15 | InValidUri=InValid Uri: '{0}'. A sample valid uri: https://www.powershellgallery.com/api/v2/.
16 | PathDoesNotExist=Path: '{0}' does not exist
17 | VersionError=MinimumVersion should be less than the maximumVersion. The MinimumVersion or maximumVersion cannot be used with the RequiredVersion in the same command.
18 | UnexpectedArgument=Unexpected argument type: '{0}'
19 | SourceNotFound=Source '{0}' not found. Please make sure you register it.
20 | CallingFunction="Call a function '{0}'".
21 | ###PSLOC
22 | '@
23 |
--------------------------------------------------------------------------------
/DSCResources/MSFT_PackageManagement/MSFT_PackageManagement.strings.psd1:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (c) Microsoft Corporation.
3 | #
4 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10 | # THE SOFTWARE.
11 | #
12 | ConvertFrom-StringData @'
13 | ###PSLOC
14 | StartGetPackage=Begin invoking Get-package {0} using PSModulePath {1}.
15 | PackageFound=Package '{0}' found.
16 | PackageNotFound=Package '{0}' not found.
17 | MultiplePackagesFound=More than one package found for package '{0}'.
18 | StartTestPackage=Test-TargetResource calling Get-TargetResource using {0}.
19 | InDesiredState=Resource {0} is in the desired state. Required Ensure is {1} and actual Ensure is {2}
20 | NotInDesiredState=Resource {0} is not in the desired state. Required Ensure is {1} and actual Ensure is {2}
21 | StartSetPackage=Set-TargetResource calling Test-TargetResource using {0}.
22 | InstallPackageInSet=Calling Install-Package using {0}.
23 | ###PSLOC
24 |
25 | '@
26 |
27 |
--------------------------------------------------------------------------------
/DSCResources/MSFT_NugetPackage/MSFT_NugetPackage.schema.mfl:
--------------------------------------------------------------------------------
1 | #pragma namespace("\\\\.\\root\\default")
2 | instance of __namespace{ name="MS_409";};
3 | #pragma namespace("\\\\.\\root\\default\\MS_409")
4 |
5 | [AMENDMENT, LOCALE("MS_409")]
6 | class MSFT_NugetPackage : OMI_BaseResource
7 | {
8 | [Key,Description("Name of the package.\n") : Amended] String Name;
9 | [Description("The destination path of the package.\n") : Amended] String DestinationPath;
10 | [Description("Whether the package to be installed or uninstalled.\nPresent {default} \nAbsent \n") : Amended] String Ensure;
11 | [Description("Whether the package is trusted or untrusted.\nTrusted {default} \nUntrusted \n") : Amended] String InstallationPolicy;
12 | [Description("The required version of the package.\n") : Amended] String RequiredVersion;
13 | [Description("The maximum version of the package.\n") : Amended] String MaximumVersion;
14 | [Description("The minimum version of the package.\n") : Amended] String MinimumVersion;
15 | [Description("The Uri or name of the package source.\n") : Amended] String Source;
16 | [Description("The credential used to access repository of package source.\n") : Amended] String SourceCredential;
17 | [Description("The description of the package.\n") : Amended] string Description;
18 | [Description("The version of the installed package.\n") : Amended] String InstalledVersion;
19 | [Description("The identity of the installed package\n") : Amended] String SoftwareIdentity;
20 | };
21 |
--------------------------------------------------------------------------------
/DSCResources/MSFT_PSModule/MSFT_PSModule.schema.mfl:
--------------------------------------------------------------------------------
1 | #pragma namespace("\\\\.\\root\\default")
2 | instance of __namespace{ name="MS_409";};
3 | #pragma namespace("\\\\.\\root\\default\\MS_409")
4 |
5 | [AMENDMENT, LOCALE("MS_409")]
6 | class MSFT_PSModule : OMI_BaseResource
7 | {
8 | [Key,Description("Name of the module\n") : Amended] String Name;
9 | [Description("Whether the module is to be installed or uninstalled.\nPresent {default} \nAbsent \n") : Amended] String Ensure;
10 | [Description("The name of the module source where the module can be found.\n") : Amended] String Repository;
11 | [Description("Whether the package is trusted or untrusted.\nTrusted {default} \nUntrusted \n") : Amended] String InstallationPolicy;
12 | [Description("The required version of the module.\n") : Amended] String RequiredVersion;
13 | [Description("The minimum version of the module.\n") : Amended] String MinimumVersion;
14 | [Description("The maximum version of the module.\n") : Amended] String MaximumVersion;
15 | [Description("The brief description of the module.\n") : Amended] string Description;
16 | [Description("The version of the module that is installed.\n") : Amended] String InstalledVersion;
17 | [Description("The identifier of the module.\n") : Amended] String Guid;
18 | [Description("The base location where the module is installed.\n") : Amended] String ModuleBase;
19 | [Description("The type of the module.\n") : Amended] String ModuleType;
20 | [Description("The author of the module.\n") : Amended] String Author;
21 | };
22 |
--------------------------------------------------------------------------------
/Examples/Sample_PSModule.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (c) Microsoft Corporation.
3 | #
4 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10 | # THE SOFTWARE.
11 | #
12 | configuration Sample_PSModule
13 | {
14 | param
15 | (
16 | #Target nodes to apply the configuration
17 | [string[]]$NodeName = 'localhost',
18 |
19 | #The name of the module
20 | [Parameter(Mandatory)]
21 | [string]$Name,
22 |
23 | #The required version of the module
24 | [string]$RequiredVersion,
25 |
26 | #Repository name
27 | [string]$Repository,
28 |
29 | #Whether you trust the repository
30 | [string]$InstallationPolicy
31 | )
32 |
33 |
34 | Import-DscResource -Module PackageManagementProviderResource
35 |
36 | Node $NodeName
37 | {
38 | #Install a package from the Powershell gallery
39 | PSModule MyPSModule
40 | {
41 | Ensure = "present"
42 | Name = $Name
43 | RequiredVersion = "0.2.16.3"
44 | Repository = "PSGallery"
45 | InstallationPolicy="trusted"
46 | }
47 | }
48 | }
49 |
50 |
51 | #Compile it
52 | Sample_PSModule -Name "xjea"
53 |
54 | #Run it
55 | Start-DscConfiguration -path .\Sample_PSModule -wait -Verbose -force
56 |
--------------------------------------------------------------------------------
/DSCResources/MSFT_PackageManagementSource/MSFT_PackageManagementSource.strings.psd1:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (c) Microsoft Corporation.
3 | #
4 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10 | # THE SOFTWARE.
11 | #
12 | ConvertFrom-StringData @'
13 | ###PSLOC
14 | StartGetPackageSource=Begin invoking Get-packageSource {0}
15 | StartRegisterPackageSource=Begin invoking Register-Packagesource {0}
16 | StartUnRegisterPackageSource=Begin invoking UnRegister-Packagesource {0}
17 | PackageSourceFound=Package source '{0}' found
18 | PackageSourceNotFound=Package source '{0}' not found
19 | RegisteredSuccess=Successfully registered the package source {0}
20 | UnRegisteredSuccess=Successfully unregistered the package source {0}
21 | RegisterFailed=Failed to register the package source {0}. Message:{1}
22 | UnRegisterFailed=Failed to register the package source {0}. Message:{1}
23 | InDesiredState=Resource {0} is in the desired state. Required Ensure is {1} and actual Ensure is {2}
24 | NotInDesiredState=Resource {0} is not in the desired state. Required Ensure is {1} and actual Ensure is {2}
25 | NotInDesiredStateDuetoLocationMismatch=Resource {0} is not in the desired state. Required location is {1} and registered is {2}
26 | NotInDesiredStateDuetoPolicyMismatch=Resource {0} is not in the desired state. Required installation policy is {1} and registered is {2}
27 | InstallationPolicyWarning=Begin registering '{0}' to source location '{1}' with '{2}' policy"
28 | ###PSLOC
29 |
30 | '@
31 |
32 |
--------------------------------------------------------------------------------
/Test/PSModule/PSModule.IntegrationTest.Tests.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (c) Microsoft Corporation.
3 | #
4 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10 | # THE SOFTWARE.
11 | #
12 |
13 | $CurrentDirectory = Split-Path -Parent $MyInvocation.MyCommand.Path
14 |
15 | . "$CurrentDirectory\..\OneGetTestHelper.ps1"
16 |
17 | # Calling the setup function
18 | SetupPSModuleTest
19 |
20 | Describe -Name "PSModule Integration Test" -Tags "RI" {
21 |
22 | BeforeEach {
23 | }
24 |
25 | AfterEach {
26 | }
27 |
28 | It "Start-DSC & Get-DSCconfiguration:Check Present" {
29 |
30 | # Compile the sample configuration to MOF and run Start-DscConfiguration
31 | $module=Get-Module -Name "PackageManagementProviderResource" -ListAvailable
32 | & "$($module.ModuleBase)\Examples\Sample_PSModule.ps1"
33 |
34 | $getResult = Get-DscConfiguration
35 |
36 | # Validate the returned results
37 |
38 | $getResult.Ensure | should be "Present"
39 | $getResult.Name | should be "xjea"
40 | $getResult.InstalledVersion | should be "0.2.16.3"
41 | $getResult.InstallationPolicy | should be "Untrusted"
42 | $getResult.ModuleType | should be "Manifest"
43 |
44 |
45 | # Check if the module exists. Source here is the installed path
46 |
47 | Test-Path $getResult.ModuleBase | should be $true
48 |
49 | # Calling Test to validate if it is true
50 | $testResult = Test-DscConfiguration
51 |
52 | $testResult | should be $true
53 | }
54 | }
55 |
56 |
57 |
--------------------------------------------------------------------------------
/Test/NugetPackage/NugetPackage.IntegrationTest.Tests.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (c) Microsoft Corporation.
3 | #
4 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10 | # THE SOFTWARE.
11 | #
12 |
13 | $CurrentDirectory = Split-Path -Parent $MyInvocation.MyCommand.Path
14 |
15 | . "$CurrentDirectory\..\OneGetTestHelper.ps1"
16 |
17 | # Calling the setup function
18 | SetupNugetTest
19 |
20 | Describe -Name "NugetPackage Integration Test" -Tags "RI" {
21 |
22 |
23 | BeforeEach {
24 |
25 | }
26 |
27 | AfterEach {
28 |
29 | }
30 |
31 | It "Start-DSC, Get-Dscconfiguration: Check Present" {
32 |
33 | # Compile the sample configuration to MOF and run Start-DscConfiguration
34 | $module=Get-Module -Name "PackageManagementProviderResource" -ListAvailable
35 | & "$($module.ModuleBase)\Examples\Sample_NuGet_InstallPackage.ps1"
36 |
37 | $getResult = Get-DscConfiguration
38 |
39 | # Validate the returned results
40 | $getResult[0].Ensure | should be "Present"
41 | $getResult[0].Name | should be "Mynuget"
42 | $getResult[0].ProviderName | should be "Nuget"
43 | $getResult[0].SourceUri | should be "http://nuget.org/api/v2/"
44 | $getResult[0].InstallationPolicy | should be "Trusted"
45 |
46 | $getResult[1].Ensure | should be "Present"
47 | $getResult[1].Name | should be "Jquery.2.0.1"
48 | $getResult[1].InstalledVersion | should be "2.0.1"
49 | $getResult[1].SoftwareIdentity | should not BeNullOrEmpty
50 |
51 | # Check if the module exists. Source here is the installed path
52 |
53 | Test-Path $getResult[1].Source | should be $true
54 |
55 | # Calling Test to validate if it is true
56 | $testResult = Test-DscConfiguration
57 |
58 | $testResult | should be $true
59 | }
60 |
61 | }
62 |
63 |
64 |
--------------------------------------------------------------------------------
/Examples/Sample_Install_Package.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (c) Microsoft Corporation.
3 | #
4 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10 | # THE SOFTWARE.
11 | #
12 |
13 | # This sample configuration does the following
14 | # 1. Registers PowerShellGallery if it is not already
15 | # 2. Downloads GistProvider OneGet provider using Install-Package
16 | # 3. Downloads a Gist from source DFinke using Gist Provider
17 | configuration Sample_Install_Package
18 | {
19 | param
20 | (
21 | #Target nodes to apply the configuration
22 | [string[]]$NodeName = 'localhost'
23 | )
24 |
25 |
26 | Import-DscResource -Module PackageManagementProviderResource
27 |
28 | Node $NodeName
29 | {
30 | #register package source
31 | PackageManagementSource PSGallery
32 | {
33 |
34 | Ensure = "Present"
35 | Name = "psgallery"
36 | ProviderName= "PowerShellGet"
37 | SourceUri = "https://www.powershellgallery.com/api/v2/"
38 | InstallationPolicy ="Trusted"
39 | }
40 |
41 | #Install a package from the Powershell gallery
42 | PackageManagement GistProvider
43 | {
44 | Ensure = "present"
45 | Name = "gistprovider"
46 | Source = "PSGallery"
47 | DependsOn = "[PackageManagementSource]PSGallery"
48 | }
49 |
50 | PackageManagement PowerShellTeamOSSUpdateInfo
51 | {
52 | Ensure = "present"
53 | Name = "Get-PSTOss.ps1"
54 | ProviderName = "Gist"
55 | Source = "dfinke"
56 | DependsOn = "[PackageManagement]GistProvider"
57 | }
58 | }
59 | }
60 |
61 |
62 | #Compile it
63 | Sample_Install_Package
64 |
65 | #Run it
66 | Start-DscConfiguration -path .\Sample_Install_Package -wait -Verbose -force
67 |
--------------------------------------------------------------------------------
/Examples/Sample_Install_Pester.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (c) Microsoft Corporation.
3 | #
4 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10 | # THE SOFTWARE.
11 | #
12 | # DSC configuration for NuGet
13 |
14 | configuration Sample_InstallPester
15 | {
16 | param
17 | (
18 | #Target nodes to apply the configuration
19 | [string[]]$NodeName = 'localhost',
20 |
21 | #Name of the package to be installed
22 | [Parameter(Mandatory)]
23 | [string]$Name,
24 |
25 | #Destination path for the package
26 | [Parameter(Mandatory)]
27 | [string]$DestinationPath,
28 |
29 | #Version of the package to be installed
30 | [string]$RequiredVersion,
31 |
32 | #Source location where the package download from
33 | [string]$Source,
34 |
35 | #Whether the source is Trusted or Untrusted
36 | [string]$InstallationPolicy
37 | )
38 |
39 | Import-DscResource -Module PackageManagementProviderResource
40 |
41 | Node $NodeName
42 | {
43 |
44 | #register package source
45 | PackageManagementSource SourceRepository
46 | {
47 |
48 | Ensure = "Present"
49 | Name = "Mynuget"
50 | ProviderName= "Nuget"
51 | SourceUri = "http://nuget.org/api/v2/"
52 | InstallationPolicy ="Trusted"
53 | }
54 |
55 | #Install a package from Nuget repository
56 | NugetPackage Nuget
57 | {
58 | Ensure = "present"
59 | Name = $Name
60 | DestinationPath = $DestinationPath
61 | DependsOn = "[PackageManagementSource]SourceRepository"
62 | InstallationPolicy="Trusted"
63 | }
64 | }
65 | }
66 |
67 |
68 | #Compile it
69 | Sample_InstallPester -Name "Pester" -DestinationPath "$env:HomeDrive\test\test"
70 |
71 | #Run it
72 | Start-DscConfiguration -path .\Sample_InstallPester -wait -Verbose -force
73 |
--------------------------------------------------------------------------------
/DSCResources/MSFT_NugetPackage/MSFT_NugetPackage.strings.psd1:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (c) Microsoft Corporation.
3 | #
4 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10 | # THE SOFTWARE.
11 | #
12 | ConvertFrom-StringData @'
13 | ###PSLOC
14 | FailtoUninstall=Failed to uninstall the package '{0}'. Message: {1}
15 | FailtoInstall=Failed to install the package '{0}'. Message: {1}
16 | PackageNotFound=Package '{0}' not found in the node
17 | PackageNotFoundInRepository=Package '{0}' not found in the repository. Message: {1}
18 | StartGetPackage=Begin invoking get-package '{0}'
19 | StartFindPackage=Begin invoking find-package '{0}'
20 | StartInstallPackage=Begin invoking install-package '{0}' version '{1}' from '{2}' source
21 | StartUnInstallPackage=Begin invoking uninstall-package '{0}'
22 | InstalledSuccess=Successfully installed the package '{0}'
23 | UnInstalledSuccess=Successfully uninstalled the package '{0}'
24 | PackageFound=found package '{0}'
25 | InDesiredState=Resource '{0}' is in the desired state. Required Ensure is '{1}' and actual Ensure is '{2}'
26 | NotInDesiredState=Resource '{0}' is not in the desired state. Required Ensure is '{1}' and actual Ensure is '{2}'
27 | NotInDesiredStateVersionMismatch=Resource '{0}' is not in the desired state. Required version is '{1}' but installed is '{2}'
28 | StartGetPackageSource=Begin invoking Get-packageSource '{0}'
29 | MultiplePackageFound=Total: '{0}' packages found with the same name. Please use 'RequiredVersion' for filtering. Message: {1}
30 | InstallationPolicyWarning=You are installing the module '{0}' from an untrusted repository '{1}'. Your current InstallationPolicy is '{2}'. If you trust the repository, set the policy to "Trusted". "Untrusted" otherwise.
31 | InstallationPolicyFailed=Failed in the installation policy. Your current InstallationPolicy is '{0}' and the repository is '{1}'. If you trust the repository, set the policy to "Trusted". "Untrusted" otherwise.
32 | ###PSLOC
33 |
34 | '@
35 |
36 |
--------------------------------------------------------------------------------
/Examples/Sample_NuGet_InstallPackage.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (c) Microsoft Corporation.
3 | #
4 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10 | # THE SOFTWARE.
11 | #
12 | # DSC configuration for NuGet
13 |
14 | configuration Sample_NuGet_InstallPackage
15 | {
16 | param
17 | (
18 | #Target nodes to apply the configuration
19 | [string[]]$NodeName = 'localhost',
20 |
21 | #Name of the package to be installed
22 | [Parameter(Mandatory)]
23 | [string]$Name,
24 |
25 | #Destination path for the package
26 | [Parameter(Mandatory)]
27 | [string]$DestinationPath,
28 |
29 | #Version of the package to be installed
30 | [string]$RequiredVersion,
31 |
32 | #Source location where the package download from
33 | [string]$Source,
34 |
35 | #Whether the source is Trusted or Untrusted
36 | [string]$InstallationPolicy
37 | )
38 |
39 | Import-DscResource -Module PackageManagementProviderResource
40 |
41 | Node $NodeName
42 | {
43 |
44 | #register package source
45 | PackageManagementSource SourceRepository
46 | {
47 |
48 | Ensure = "Present"
49 | Name = "MyNuget"
50 | ProviderName= "Nuget"
51 | SourceUri = "http://nuget.org/api/v2/"
52 | InstallationPolicy ="Trusted"
53 | }
54 |
55 | #Install a package from Nuget repository
56 | NugetPackage Nuget
57 | {
58 | Ensure = "Present"
59 | Name = $Name
60 | DestinationPath = $DestinationPath
61 | RequiredVersion = "2.0.1"
62 | DependsOn = "[PackageManagementSource]SourceRepository"
63 | }
64 | }
65 | }
66 |
67 |
68 | #Compile it
69 | Sample_NuGet_InstallPackage -Name "JQuery" -DestinationPath "$env:HomeDrive\test\test"
70 |
71 | #Run it
72 | Start-DscConfiguration -path .\Sample_NuGet_InstallPackage -wait -Verbose -force
73 |
--------------------------------------------------------------------------------
/DSCResources/MSFT_PSModule/MSFT_PSModule.strings.psd1:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (c) Microsoft Corporation.
3 | #
4 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10 | # THE SOFTWARE.
11 | #
12 | ConvertFrom-StringData @'
13 | ###PSLOC
14 | FailtoUninstall=Failed to uninstall the module '{0}'. Message: {1}
15 | FailtoInstall=Failed to install the module '{0}'. Message: {1}
16 | InDesiredState=Resource '{0}' is in the desired state
17 | NotInDesiredState=Resource '{0}' is not in the desired state
18 | ModuleFound=Module '{0}' found in the node
19 | ModuleNotFound=Module '{0}' not found in the node
20 | ModuleWithRightPropertyNotFound=Module '{0}' with the right version or other properties not found in the node. Message: {1}
21 | ModuleNotFoundInRepository=Module '{0}' with the right version or other properties not found in the repository. Message: {1}
22 | StartGetModule=Begin invoking get-module '{0}'
23 | StartFindModule=Begin invoking find-module '{0}'
24 | StartInstallModule=Begin invoking install-module '{0}' version '{1}' from '{2}' repository
25 | StartUnInstallModule=Begin invoking uninstall of the module '{0}'
26 | InstalledSuccess=Successfully installed the module '{0}'
27 | UnInstalledSuccess=Successfully uninstalled the module '{0}'
28 | VersionMismatch=The installed Module '{0}' has the version: '{1}'
29 | RepositoryMismatch=The installed Module '{0}' is from '{1}' repository
30 | FoundModulePath=Found the module path:'{0}'
31 | MultipleModuleFound=Total: '{0}' modules found with the same name. Please use RequiredVersion for filtering. Message: {1}
32 | InstallationPolicyWarning=You are installing the module '{0}' from an untrusted repository' {1}'. Your current InstallationPolicy is '{2}'. If you trust the repository, set the policy to "Trusted". "Untrusted" otherwise.
33 | InstallationPolicyFailed=Failed in the installation policy. Your current InstallationPolicy is '{0}' and the repository is '{1}'. If you trust the repository, set the policy to "Trusted". "Untrusted" otherwise.
34 | ###PSLOC
35 |
36 | '@
37 |
38 |
--------------------------------------------------------------------------------
/Examples/Sample_Install_Package_Using_NuGet.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (c) Microsoft Corporation.
3 | #
4 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10 | # THE SOFTWARE.
11 | #
12 |
13 | # DSC configuration example for generice PackageManagement DSC resource
14 | # which uses NuGet Provider
15 |
16 | configuration Sample_Install_Package_Using_NuGet
17 | {
18 | param
19 | (
20 | #Target nodes to apply the configuration
21 | [string[]]$NodeName = 'localhost',
22 |
23 | #Name of the package to be installed
24 | [Parameter(Mandatory)]
25 | [string]$Name,
26 |
27 | #Destination path for the package
28 | [Parameter(Mandatory)]
29 | [string]$DestinationPath,
30 |
31 | #Version of the package to be installed
32 | [string]$RequiredVersion,
33 |
34 | #Source location where the package download from
35 | [string]$Source,
36 |
37 | #Whether the source is Trusted or Untrusted
38 | [string]$InstallationPolicy
39 | )
40 |
41 | Import-DscResource -Module PackageManagementProviderResource
42 |
43 | Node $NodeName
44 | {
45 |
46 | #register package source
47 | PackageManagementSource SourceRepository
48 | {
49 |
50 | Ensure = "Present"
51 | Name = "MyNuget"
52 | ProviderName= "Nuget"
53 | SourceUri = "http://nuget.org/api/v2/"
54 | InstallationPolicy ="Trusted"
55 | }
56 |
57 | #Install a package from Nuget repository
58 | PackageManagement NugetPackage
59 | {
60 | Ensure = "Present"
61 | Name = $Name
62 | AdditionalParameters = @{"Destination" = $DestinationPath}
63 | RequiredVersion = "2.0.1"
64 | DependsOn = "[PackageManagementSource]SourceRepository"
65 | }
66 | }
67 | }
68 |
69 |
70 | #Compile it
71 | Sample_Install_Package_Using_NuGet -Name "JQuery" -DestinationPath "$env:HomeDrive\test\test"
72 |
73 | #Run it
74 | Start-DscConfiguration -path .\Sample_Install_Package_Using_NuGet -wait -Verbose -force
75 |
--------------------------------------------------------------------------------
/appveyor.yml:
--------------------------------------------------------------------------------
1 |
2 | #---------------------------------#
3 | # environment configuration #
4 | #---------------------------------#
5 | # This is necessary to use WMF5
6 | os: WMF 5
7 | version: 1.1.{build}.0
8 | install:
9 | - cinst -y pester
10 | - git clone https://github.com/PowerShell/DscResource.Tests
11 |
12 | - ps: Push-Location
13 | - cd DscResource.Tests
14 | - ps: Import-Module .\TestHelper.psm1 -force
15 | - ps: Pop-Location
16 |
17 |
18 | #---------------------------------#
19 | # build configuration #
20 | #---------------------------------#
21 |
22 | build_script:
23 |
24 | - ps: New-Item -Path "$Env:ProgramFiles\AppVeyor\BuildAgent\Modules\PackageManagementProviderResource" -ItemType Directory -Force
25 |
26 | - ps: Copy-Item -Recurse "$env:APPVEYOR_BUILD_FOLDER\*" "$Env:ProgramFiles\AppVeyor\BuildAgent\Modules\PackageManagementProviderResource" -Force -Verbose
27 |
28 | - ps: Get-Module PackageManagementProviderResource -ListAvailable
29 |
30 | - ps: Write-Verbose -Verbose "$env:PSModulepath"
31 |
32 |
33 | #---------------------------------#
34 | # test configuration #
35 | #---------------------------------#
36 |
37 | test_script:
38 | - ps: |
39 | Push-Location
40 | cd $env:APPVEYOR_BUILD_FOLDER
41 | $testResultsFile = ".\TestsResults.xml"
42 | $res = Invoke-Pester -OutputFormat NUnitXml -OutputFile $testResultsFile -PassThru
43 | (New-Object 'System.Net.WebClient').UploadFile("https://ci.appveyor.com/api/testresults/nunit/$($env:APPVEYOR_JOB_ID)", (Resolve-Path $testResultsFile))
44 | if ($res.FailedCount -gt 0) {
45 | throw "$($res.FailedCount) tests failed."
46 | }
47 | Pop-Location
48 |
49 |
50 | #---------------------------------#
51 | # deployment configuration #
52 | #---------------------------------#
53 |
54 | # scripts to run before deployment
55 | deploy_script:
56 | - ps: |
57 | # Creating project artifact
58 | $stagingDirectory = (Resolve-Path ..).Path
59 | $manifest = Join-Path $pwd "PackageManagementProviderResource.psd1"
60 | (Get-Content $manifest -Raw).Replace("1.8.0.0", $env:APPVEYOR_BUILD_VERSION) | Out-File $manifest
61 | $zipFilePath = Join-Path $stagingDirectory "$(Split-Path $pwd -Leaf).zip"
62 | Add-Type -assemblyname System.IO.Compression.FileSystem
63 | [System.IO.Compression.ZipFile]::CreateFromDirectory($pwd, $zipFilePath)
64 |
65 | # Creating NuGet package artifact
66 | New-Nuspec -packageName $env:APPVEYOR_PROJECT_NAME -version $env:APPVEYOR_BUILD_VERSION -author "Microsoft" -owners "Microsoft" -licenseUrl "https://github.com/PowerShell/DscResources/blob/master/LICENSE" -projectUrl "https://github.com/$($env:APPVEYOR_REPO_NAME)" -packageDescription $env:APPVEYOR_PROJECT_NAME -tags "DesiredStateConfiguration DSC DSCResourceKit" -destinationPath .
67 | nuget pack ".\$($env:APPVEYOR_PROJECT_NAME).nuspec" -outputdirectory .
68 | $nuGetPackageName = $env:APPVEYOR_PROJECT_NAME + "." + $env:APPVEYOR_BUILD_VERSION + ".nupkg"
69 | $nuGetPackagePath = (Get-ChildItem $nuGetPackageName).FullName
70 |
71 | @(
72 | # You can add other artifacts here
73 | $zipFilePath,
74 | $nuGetPackagePath
75 | ) | % {
76 | Write-Host "Pushing package $_ as Appveyor artifact"
77 | Push-AppveyorArtifact $_
78 | }
79 |
--------------------------------------------------------------------------------
/PackageManagementProviderResource.psd1:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (c) Microsoft Corporation.
3 | #
4 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10 | # THE SOFTWARE.
11 | #
12 |
13 | @{
14 |
15 | # Script module or binary module file associated with this manifest.
16 | # RootModule = ''
17 |
18 | # Version number of this module.
19 | ModuleVersion = '1.0.3'
20 |
21 | # Supported PSEditions
22 | # CompatiblePSEditions = @()
23 |
24 | # ID used to uniquely identify this module
25 | GUID = '50615c4b-72be-42a7-81e1-8c8747238ce8'
26 |
27 | # Author of this module
28 | Author = 'Microsoft Corporation'
29 |
30 | # Company or vendor of this module
31 | CompanyName = 'Microsoft Corporation'
32 |
33 | # Copyright statement for this module
34 | Copyright = '(c) Microsoft Corporation. All rights reserved.'
35 |
36 | # Description of the functionality provided by this module
37 | Description = 'Module with DSC resources for the package management.'
38 |
39 | # Minimum version of the Windows PowerShell engine required by this module
40 | # PowerShellVersion = ''
41 |
42 | # Name of the Windows PowerShell host required by this module
43 | # PowerShellHostName = ''
44 |
45 | # Minimum version of the Windows PowerShell host required by this module
46 | # PowerShellHostVersion = ''
47 |
48 | # Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
49 | # DotNetFrameworkVersion = ''
50 |
51 | # Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
52 | # CLRVersion = ''
53 |
54 | # Processor architecture (None, X86, Amd64) required by this module
55 | # ProcessorArchitecture = ''
56 |
57 | # Modules that must be imported into the global environment prior to importing this module
58 | # RequiredModules = @()
59 |
60 | # Assemblies that must be loaded prior to importing this module
61 | # RequiredAssemblies = @()
62 |
63 | # Script files (.ps1) that are run in the caller's environment prior to importing this module.
64 | # ScriptsToProcess = @()
65 |
66 | # Type files (.ps1xml) to be loaded when importing this module
67 | # TypesToProcess = @()
68 |
69 | # Format files (.ps1xml) to be loaded when importing this module
70 | # FormatsToProcess = @()
71 |
72 | # Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
73 | # NestedModules = @()
74 |
75 | # Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
76 | FunctionsToExport = @()
77 |
78 | # Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
79 | CmdletsToExport = @()
80 |
81 | # Variables to export from this module
82 | # VariablesToExport = @()
83 |
84 | # Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
85 | AliasesToExport = @()
86 |
87 | # DSC resources to export from this module
88 | # DscResourcesToExport = @()
89 |
90 | # List of all modules packaged with this module
91 | # ModuleList = @()
92 |
93 | # List of all files packaged with this module
94 | # FileList = @()
95 |
96 | # Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
97 | PrivateData = @{
98 |
99 | PSData = @{
100 |
101 | # Tags applied to this module. These help with module discovery in online galleries.
102 | # Tags = @()
103 |
104 | # A URL to the license for this module.
105 | # LicenseUri = ''
106 |
107 | # A URL to the main website for this project.
108 | ProjectUri = 'https://github.com/PowerShell/PackageManagementProviderResource'
109 |
110 | # A URL to an icon representing this module.
111 | # IconUri = ''
112 |
113 | # ReleaseNotes of this module
114 | ReleaseNotes = '1. Fixed issue related to PSModule provider not being discovered. GitHub issue link: https://github.com/PowerShell/PackageManagementProviderResource/issues/13.
115 | 2. Added a new DSC Resource PackageManagement -> A generic PackageManagement provider that lets you download and install packages from any source.
116 | This provider uses Install-Package & Get-Package cmdlets. You may have to use PackageManagementSource DSC resource to register non-default sources.
117 | 3. Added tests for this new DSC Resource'
118 |
119 | # External dependent modules of this module
120 | # ExternalModuleDependencies = ''
121 |
122 | } # End of PSData hashtable
123 |
124 | } # End of PrivateData hashtable
125 |
126 | # HelpInfo URI of this module
127 | # HelpInfoURI = ''
128 |
129 | # Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
130 | # DefaultCommandPrefix = ''
131 |
132 | }
133 |
134 |
--------------------------------------------------------------------------------
/Test/NugetPackage/NugetPackage.Test.Tests.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (c) Microsoft Corporation.
3 | #
4 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10 | # THE SOFTWARE.
11 | #
12 |
13 | $CurrentDirectory = Split-Path -Parent $MyInvocation.MyCommand.Path
14 |
15 | . "$CurrentDirectory\..\OneGetTestHelper.ps1"
16 |
17 | #
18 | # Pre-Requisite: MyTestPackage.12.0.1.1, MyTestPackage.12.0.1, MyTestPackage.15.2.1 packages are available under the $LocalRepositoryPath.
19 | # It's been taken care of by SetupNugetTest
20 | #
21 |
22 | # Calling the setup function
23 | SetupNugetTest
24 |
25 |
26 | Describe -Name "NugetPackage Test-TargetResource Basic Tests" -Tags "BVT"{
27 |
28 | BeforeEach {
29 |
30 | #Remove all left over files if exists
31 | Remove-Item "$($DestinationPath)" -Recurse -Force -ErrorAction SilentlyContinue
32 | }
33 |
34 | AfterEach {
35 |
36 | }
37 |
38 |
39 | Context "NugetPackage Test-TargetResource with Mandatory Parameters" {
40 |
41 | Mock Set-TargetResource {
42 |
43 | #Nuget package folder name format: MyTestPackage.12.0.1, i.e., name + version
44 | $package = $name + "." + $RequiredVersion+ ".nupkg"
45 |
46 | #MyTestPackage.12.0.1.1
47 | $path = "$($DestinationPath)\$($name).$($RequiredVersion)"
48 |
49 | if ($Ensure -ieq "Present") {
50 |
51 | if (!(Test-Path -path $path)) {New-Item $path -Type Directory}
52 |
53 |
54 | #Copy the $package folder to your destination folder
55 | Copy-Item -Path "$($LocalRepositoryPath)\$package" -Destination "$($path)" -Recurse -Force
56 | }
57 | else {
58 |
59 | #Delete the $package folder
60 | Remove-Item "$($path)\$package" -Recurse -Force -ErrorAction SilentlyContinue
61 | }
62 | }
63 |
64 | It "Test-TargetResource: Check False" {
65 |
66 | # Because 'BeforeEach' removes all packages, there is no package left in the $DestinationPath.
67 | # It is expected Test-Target* returns false for ensure='Present'
68 | #
69 | # Calling Test-TargetResource in the NugetPackage resource
70 | $result = MSFT_NugetPackage\Test-TargetResource -Name "MyTestPackage" -DestinationPath $DestinationPath
71 |
72 | # Validate the result
73 | $result | should be $false
74 | }
75 |
76 | It "Test-TargetResource: Check True" {
77 |
78 | # Calling Test-TargetResource in the NugetPackage resource
79 | $result = MSFT_NugetPackage\Test-TargetResource -Name "MyTestPackage" -DestinationPath $DestinationPath -Ensure Absent
80 |
81 | # Validate the result
82 | $result | should be $true
83 | }
84 |
85 | It "Test-TargetResource with RequiredVersion: Check True" {
86 |
87 | Set-TargetResource -name "MyTestPackage" -DestinationPath $DestinationPath -RequiredVersion "12.0.1" -Ensure "Present" -Verbose
88 |
89 | $result = MSFT_NugetPackage\Test-TargetResource -Name "MyTestPackage" -DestinationPath $destinationPath -RequiredVersion "12.0.1"
90 |
91 | #Validate the returned results
92 | $result | should be $true
93 | }
94 |
95 |
96 | It "Test-TargetResource with InstalledVersion 12.0.1 but RequiredVersion 12.0.1.1: Check False" {
97 |
98 | Set-TargetResource -name "MyTestPackage" -DestinationPath $DestinationPath -RequiredVersion "12.0.1" -Ensure "Present" -Verbose
99 |
100 | #The requiredVersion does not exist, expect Ensure=Absent
101 | $result = MSFT_NugetPackage\Test-TargetResource -Name "MyTestPackage" -DestinationPath $destinationPath -RequiredVersion "12.0.1.1"
102 |
103 | #Validate the returned results
104 | $result | should be $false
105 | }
106 |
107 | It "Test-TargetResource with InstalledVersion 12.0.1.1 but RequiredVersion 12.0.1: Check False" {
108 |
109 | Set-TargetResource -name "MyTestPackage" -DestinationPath $DestinationPath -RequiredVersion "12.0.1.1" -Ensure "Present" -Verbose
110 |
111 | #Provide a req version does not exist, expect Ensure=Absent
112 | $result = MSFT_NugetPackage\Test-TargetResource -Name "MyTestPackage" -DestinationPath $destinationPath -RequiredVersion "12.0.1"
113 |
114 | #Validate the returned results
115 | $result | should be $false
116 | }
117 |
118 |
119 | It "Test-TargetResource with MaximumVersion: Check True" {
120 |
121 | Set-TargetResource -name "MyTestPackage" -DestinationPath $DestinationPath -RequiredVersion "12.0.1.1" -Ensure "Present" -Verbose
122 | Set-TargetResource -name "MyTestPackage" -DestinationPath $DestinationPath -RequiredVersion "12.0.1" -Ensure "Present" -Verbose
123 | Set-TargetResource -name "MyTestPackage" -DestinationPath $DestinationPath -RequiredVersion "15.2.1" -Ensure "Present" -Verbose
124 |
125 | $result = MSFT_NugetPackage\Test-TargetResource -Name "MyTestPackage" -DestinationPath $destinationPath -MaximumVersion "12.9.9"
126 |
127 | $result | should be $true
128 | }
129 | }#context
130 |
131 | }#Describe
132 |
133 |
--------------------------------------------------------------------------------
/Test/PackageManagement/PackageManagement.Test.Tests.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (c) Microsoft Corporation.
3 | #
4 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10 | # THE SOFTWARE.
11 | #
12 |
13 | $CurrentDirectory = Split-Path -Parent $MyInvocation.MyCommand.Path
14 |
15 | . "$CurrentDirectory\..\OneGetTestHelper.ps1"
16 |
17 | #
18 | # Pre-Requisite: MyTestPackage.12.0.1.1, MyTestPackage.12.0.1, MyTestPackage.15.2.1 packages are available under the $LocalRepositoryPath.
19 | # It's been taken care of by SetupPackageManagementTest
20 | #
21 |
22 | # Calling the setup function
23 | SetupPackageManagementTest
24 |
25 | $AdditionalParameters = @{"Destination" = $DestinationPath}
26 | $AdditionalParameterCimInstanceArray = ConvertHashtableToArryCimInstance $AdditionalParameters
27 |
28 | Describe -Name "PackageManagement Test-TargetResource Basic Tests" -Tags "BVT"{
29 |
30 | BeforeEach {
31 |
32 | #Remove all left over files if exists
33 | Remove-Item "$($DestinationPath)" -Recurse -Force -ErrorAction SilentlyContinue
34 | }
35 |
36 | AfterEach {
37 |
38 | }
39 |
40 |
41 | Context "PackageManagement Test-TargetResource with Mandatory Parameters" {
42 |
43 | Mock Set-TargetResource {
44 |
45 | #Nuget package folder name format: MyTestPackage.12.0.1, i.e., name + version
46 | $package = $name + "." + $RequiredVersion+ ".nupkg"
47 |
48 | #MyTestPackage.12.0.1.1
49 | $path = "$($DestinationPath)\$($name).$($RequiredVersion)"
50 |
51 | if ($Ensure -ieq "Present") {
52 |
53 | if (!(Test-Path -path $path)) {New-Item $path -Type Directory}
54 |
55 |
56 | #Copy the $package folder to your destination folder
57 | Copy-Item -Path "$($LocalRepositoryPath)\$package" -Destination "$($path)" -Recurse -Force
58 | }
59 | else {
60 |
61 | #Delete the $package folder
62 | Remove-Item "$($path)\$package" -Recurse -Force -ErrorAction SilentlyContinue
63 | }
64 | }
65 |
66 | It "Test-TargetResource: Check False" {
67 |
68 | # Because 'BeforeEach' removes all packages, there is no package left in the $DestinationPath.
69 | # It is expected Test-Target* returns false for ensure='Present'
70 | #
71 | # Calling Test-TargetResource in the NugetPackage resource
72 | $result = MSFT_PackageManagement\Test-TargetResource -Name "MyTestPackage" -AdditionalParameters $AdditionalParameterCimInstanceArray
73 |
74 | # Validate the result
75 | $result | should be $false
76 | }
77 |
78 | It "Test-TargetResource: Check True" {
79 |
80 | # Calling Test-TargetResource in the NugetPackage resource
81 | $result = MSFT_PackageManagement\Test-TargetResource -Name "MyTestPackage" -AdditionalParameters $AdditionalParameterCimInstanceArray -Ensure Absent
82 |
83 | # Validate the result
84 | $result | should be $true
85 | }
86 |
87 | It "Test-TargetResource with RequiredVersion: Check True" {
88 |
89 | Set-TargetResource -name "MyTestPackage" -AdditionalParameters $AdditionalParameterCimInstanceArray -RequiredVersion "12.0.1" -Ensure "Present" -Verbose
90 |
91 | $result = MSFT_PackageManagement\Test-TargetResource -Name "MyTestPackage" -AdditionalParameters $AdditionalParameterCimInstanceArray -RequiredVersion "12.0.1"
92 |
93 | #Validate the returned results
94 | $result | should be $true
95 | }
96 |
97 |
98 | It "Test-TargetResource with InstalledVersion 12.0.1 but RequiredVersion 12.0.1.1: Check False" {
99 |
100 | Set-TargetResource -name "MyTestPackage" -AdditionalParameters $AdditionalParameterCimInstanceArray -RequiredVersion "12.0.1" -Ensure "Present" -Verbose
101 |
102 | #The requiredVersion does not exist, expect Ensure=Absent
103 | $result = MSFT_PackageManagement\Test-TargetResource -Name "MyTestPackage" -AdditionalParameters $AdditionalParameterCimInstanceArray -RequiredVersion "12.0.1.1"
104 |
105 | #Validate the returned results
106 | $result | should be $false
107 | }
108 |
109 | It "Test-TargetResource with InstalledVersion 12.0.1.1 but RequiredVersion 12.0.1: Check False" {
110 |
111 | Set-TargetResource -name "MyTestPackage" -AdditionalParameters $AdditionalParameterCimInstanceArray -RequiredVersion "12.0.1.1" -Ensure "Present" -Verbose
112 |
113 | #Provide a req version does not exist, expect Ensure=Absent
114 | $result = MSFT_PackageManagement\Test-TargetResource -Name "MyTestPackage" -AdditionalParameters $AdditionalParameterCimInstanceArray -RequiredVersion "12.0.1"
115 |
116 | #Validate the returned results
117 | $result | should be $false
118 | }
119 |
120 | It "Test-TargetResource with MaximumVersion: Check True" {
121 |
122 | Set-TargetResource -name "MyTestPackage" -AdditionalParameters $AdditionalParameterCimInstanceArray -RequiredVersion "12.0.1.1" -Ensure "Present" -Verbose
123 | Set-TargetResource -name "MyTestPackage" -AdditionalParameters $AdditionalParameterCimInstanceArray -RequiredVersion "12.0.1" -Ensure "Present" -Verbose
124 | Set-TargetResource -name "MyTestPackage" -AdditionalParameters $AdditionalParameterCimInstanceArray -RequiredVersion "15.2.1" -Ensure "Present" -Verbose
125 |
126 | $result = MSFT_PackageManagement\Test-TargetResource -Name "MyTestPackage" -AdditionalParameters $AdditionalParameterCimInstanceArray -MaximumVersion "12.9.9"
127 |
128 | $result | should be $true
129 | }
130 | }#context
131 |
132 | }#Describe
133 |
134 |
--------------------------------------------------------------------------------
/Test/PackageManagement/PackageManagement.Set.Tests.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (c) Microsoft Corporation.
3 | #
4 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10 | # THE SOFTWARE.
11 | #
12 |
13 |
14 | $CurrentDirectory = Split-Path -Parent $MyInvocation.MyCommand.Path
15 |
16 | . "$CurrentDirectory\..\OneGetTestHelper.ps1"
17 |
18 | if (-not (IsAdmin))
19 | {
20 | throw "This test script requires to be run from an elevated PowerShell session. Launch an elevated PowerShell session and try again."
21 | }
22 |
23 | #
24 | # Pre-Requisite: MyTestModule 1.1, 1.1.2, 3.2.1 modules are available under the $LocalRepositoryPath for testing purpose only.
25 | # It's been taken care of by SetupPackageManagementTest
26 | #
27 |
28 | # Calling the setup function
29 | SetupPackageManagementTest -SetupPSModuleRepository
30 |
31 | Describe -Name "PackageManagement Set-TargetResource Basic Test" -Tags "BVT" {
32 |
33 | BeforeAll {
34 | $script:OriginalRepository = CleanupRepository
35 | }
36 |
37 | BeforeEach {
38 |
39 | #Remove all left over files if exists
40 | Remove-Item "$PSModuleBase\MyTestModule" -Recurse -Force -ErrorAction SilentlyContinue
41 | Remove-Item "$PSModuleBase\MyTestModule" -Recurse -Force -ErrorAction SilentlyContinue
42 | }
43 |
44 | AfterEach {
45 |
46 | }
47 |
48 | AfterAll {
49 | # Remove all left over files if exists
50 | Remove-Item "$PSModuleBase\MyTestModule" -Recurse -Force -ErrorAction SilentlyContinue
51 | Remove-Item "$PSModuleBase\MyTestModule" -Recurse -Force -ErrorAction SilentlyContinue
52 |
53 | RestoreRepository $script:OriginalRepository
54 | }
55 |
56 | Context "PackageManagement Set-TargetResource Basic Test" {
57 |
58 | It "Set, Test-TargetResource with Trusted Source, No Versions Specified: Check Installed" {
59 |
60 | #Register a local module repository to make the test run faster
61 | RegisterRepository -Name "LocalRepository" -InstallationPolicy Trusted -Ensure Present
62 |
63 | # 'BeforeEach' removes all specific modules under the $module path, so it is expected Set-Target* should success in the installation
64 | MSFT_PackageManagement\Set-TargetResource -name "MyTestModule" -Source $LocalRepository -Ensure Present -Verbose
65 |
66 | # Validate the module is installed
67 | Test-Path -Path "$PSModuleBase\MyTestModule\3.2.1" | should be $true
68 |
69 | # Uninstalling the module
70 | MSFT_PackageManagement\Set-TargetResource -name "MyTestModule" -Source $LocalRepository -Ensure Absent -Verbose
71 |
72 | # Validate the module is uninstalled
73 | $result = MSFT_PackageManagement\Test-TargetResource -name "MyTestModule" -Source $LocalRepository -Ensure Absent
74 | $result| should be $true
75 |
76 | Test-Path -Path "$PSModuleBase\MyTestModule\3.2.1" | should be $false
77 | }
78 |
79 | It "Set, Test-TargetResource with Trusted Source, No respository Specified: Check Installed" {
80 |
81 | #Register a local module repository to make the test run faster
82 | RegisterRepository -Name "LocalRepository" -InstallationPolicy Trusted -Ensure Present
83 |
84 | # 'BeforeEach' removes all specific modules under the $module path, so it is expected Set-Target* should success in the installation
85 | MSFT_PackageManagement\Set-TargetResource -name "MyTestModule" -Ensure Present -Verbose
86 |
87 | # Validate the module is installed
88 | Test-Path -Path "$PSModuleBase\MyTestModule\3.2.1" | should be $true
89 |
90 | # Uninstalling the module
91 | MSFT_PackageManagement\Set-TargetResource -name "MyTestModule" -Ensure Absent -Verbose
92 |
93 | # Validate the module is uninstalled
94 | $result = MSFT_PackageManagement\Test-TargetResource -name "MyTestModule" -Ensure Absent
95 |
96 | $result| should be $true
97 | }
98 |
99 | It "Set, Test-TargetResource with multiple sources and versions of a modules: Check Installed" {
100 |
101 | # Registering multiple source
102 |
103 | $returnVal = $null
104 |
105 | try
106 | {
107 | $returnVal = CleanupRepository
108 |
109 | RegisterRepository -Name "LocalRepository1" -InstallationPolicy Untrusted -Ensure Present -SourceLocation $LocalRepositoryPath1 -PublishLocation $LocalRepositoryPath1
110 |
111 | RegisterRepository -Name "LocalRepository2" -InstallationPolicy Trusted -Ensure Present -SourceLocation $LocalRepositoryPath2 -PublishLocation $LocalRepositoryPath2
112 |
113 | RegisterRepository -Name "LocalRepository3" -InstallationPolicy Untrusted -Ensure Present -SourceLocation $LocalRepositoryPath3 -PublishLocation $LocalRepositoryPath3
114 |
115 | # User's installation policy is untrusted
116 | MSFT_PackageManagement\Set-TargetResource -name "MyTestModule" -Ensure "Present" -Verbose -Source "LocalRepository2"
117 |
118 | # The module from the trusted source should be installed
119 | Get-InstalledModule MyTestModule | % Repository | should be "LocalRepository2"
120 | }
121 | finally
122 | {
123 | RestoreRepository -RepositoryInfo $returnVal
124 | # Unregistering the repository sources
125 |
126 | RegisterRepository -Name "LocalRepository1" -Ensure Absent -SourceLocation $LocalRepositoryPath1 -PublishLocation $LocalRepositoryPath1
127 |
128 | RegisterRepository -Name "LocalRepository2" -Ensure Absent -SourceLocation $LocalRepositoryPath2 -PublishLocation $LocalRepositoryPath2
129 |
130 | RegisterRepository -Name "LocalRepository3" -Ensure Absent -SourceLocation $LocalRepositoryPath3 -PublishLocation $LocalRepositoryPath3
131 | }
132 | }
133 |
134 | }#context
135 |
136 |
137 | Context "PackageManagement Set-TargetResource Error Cases" {
138 |
139 | #Register a local module repository to make the test run faster
140 | RegisterRepository -Name "LocalRepository" -InstallationPolicy Trusted -Ensure Present
141 |
142 | It "Set-TargetResource with module not found for the install: Check Error" {
143 |
144 | try
145 | {
146 | # The module does not exist
147 | MSFT_PackageManagement\Set-TargetResource -name "NonExistModule" -Ensure Present -ErrorAction SilentlyContinue 2>&1
148 | }
149 | catch
150 | {
151 | #Expect fail to install.
152 | $_.FullyQualifiedErrorId | should be "NoMatchFoundForCriteria,Microsoft.PowerShell.PackageManagement.Cmdlets.InstallPackage"
153 | return
154 | }
155 |
156 | Throw "Expected 'ModuleNotFoundInRepository' exception did not happen"
157 | }
158 |
159 |
160 | It "Set , Test-TargetResource: Check Absent and False" {
161 |
162 | # Calling Set-TargetResource to uninstall the MyTestModule module
163 | try
164 | {
165 | MSFT_PackageManagement\Set-TargetResource -name "MyTestModule" -Source $LocalRepository -RequiredVersion "1.1.2" -Ensure "Absent" -Verbose
166 | }
167 | catch
168 | {
169 | if ($_.FullyQualifiedErrorId -ieq "NoMatchFound,Microsoft.PowerShell.PackageManagement.Cmdlets.UninstallPackage")
170 | {
171 | #The module is not installed. Ignore the error
172 | }
173 | else
174 | {
175 | throw
176 | }
177 | }
178 |
179 | # Calling Get-TargetResource in the PSModule resource
180 | $result = MSFT_PackageManagement\Test-TargetResource -Name "MyTestModule" -Source $LocalRepository -RequiredVersion "1.1.2"
181 |
182 | # Validate the result
183 | $result | should be $false
184 |
185 | }
186 |
187 | }#context
188 | }#Describe
189 |
--------------------------------------------------------------------------------
/Test/PSModule/PSModule.Get.Tests.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (c) Microsoft Corporation.
3 | #
4 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10 | # THE SOFTWARE.
11 | #
12 | $CurrentDirectory = Split-Path -Parent $MyInvocation.MyCommand.Path
13 |
14 | . "$CurrentDirectory\..\OneGetTestHelper.ps1"
15 |
16 | #
17 | # Pre-Requisite: MyTestModule 1.1, 1.1.2, 3.2.1 are available under the $LocalRepositoryPath for testing purpose only.
18 | # It's been taken care of by SetupPSModuleTest
19 | #
20 |
21 | # Calling the setup function
22 | SetupPSModuleTest
23 |
24 | Describe -Name "PSModule Get-TargetResource Basic Tests" -Tags "BVT" {
25 |
26 | BeforeEach {
27 |
28 | # Remove all left over files if exists
29 | Remove-Item "$($InstallationFolder)\..\..\MyTestModule" -Recurse -Force -ErrorAction SilentlyContinue
30 | Remove-Item "$($InstallationFolder)\..\MyTestModule" -Recurse -Force -ErrorAction SilentlyContinue
31 | }
32 |
33 | AfterEach {
34 |
35 | }
36 |
37 |
38 | # Register a local module repository to make the test run faster. This gets called once per Describe.
39 | RegisterRepository -Name "LocalRepository" -InstallationPolicy Trusted -Ensure Present
40 |
41 | It "Get-TargetResource with the Mandatory Parameters: Check Present" {
42 |
43 | # Calling Set-TargetResource to install the MyTestModule
44 | Set-TargetResource -name "MyTestModule" -Repository $LocalRepository -RequiredVersion "3.2.1" -Ensure "Present" -Verbose
45 |
46 | # Calling Get-TargetResource in the PSModule resource
47 | $result = MSFT_PSModule\Get-TargetResource -Name "MyTestModule" -Repository $LocalRepository
48 |
49 | # Validate the result
50 | $result.Ensure | should be "Present"
51 | }
52 |
53 | It "Get-TargetResource given the different versions of modules on the same repository: Check Present" {
54 |
55 | #Calling Set-TargetResource to install the module
56 | Set-TargetResource -name "MyTestModule" -Repository $LocalRepository -RequiredVersion "3.2.1" -Ensure "Present" -Verbose
57 | Set-TargetResource -name "MyTestModule" -Repository $LocalRepository -RequiredVersion "1.1.2" -Ensure "Present" -Verbose
58 | Set-TargetResource -name "MyTestModule" -Repository $LocalRepository -RequiredVersion "1.1" -Ensure "Present" -Verbose
59 |
60 | $result = MSFT_PSModule\Get-TargetResource -Name "MyTestModule" -Repository $LocalRepository
61 |
62 | #Validate the returned results. You can also use "Get-Module -ListAvailable -name MyTestModule" to find these info
63 | $result.Ensure | should be "Present"
64 | $result.Name | should be "MyTestModule"
65 | $result.Repository | should be $LocalRepository
66 | $result.InstalledVersion | should be "3.2.1"
67 | $result.InstallationPolicy | should be "Trusted"
68 | ($result.Author.Length -ne 0) | should be $true
69 | $result.ModuleType | should be "Manifest"
70 | ($result.Description.Length -ne 0) | should be $true
71 | }
72 |
73 | It "Get-TargetResource with RequiredVersion: Check Present" {
74 |
75 | Set-TargetResource -name "MyTestModule" -Repository $LocalRepository -RequiredVersion "1.1.2" -Ensure "Present" -Verbose
76 |
77 | # Provide a req version that exists, expect ensure=Present
78 | $result = MSFT_PSModule\Get-TargetResource -Name "MyTestModule" -Repository $LocalRepository -RequiredVersion "1.1.2"
79 |
80 | #Validate the returned results
81 | $result.Ensure | should be "Present"
82 | $result.Name | should be "MyTestModule"
83 | $result.InstalledVersion | should be "1.1.2"
84 | }
85 |
86 | It "Get-TargetResource with Non-exist RequiredVersion: Check Absent" {
87 |
88 | Set-TargetResource -name "MyTestModule" -Repository $LocalRepository -RequiredVersion "1.1.2" -Ensure "Present" -Verbose
89 |
90 | #Provide a req version does not exist, expect Ensure=Absent
91 | $result = MSFT_PSModule\Get-TargetResource -Name "MyTestModule" -Repository $LocalRepository -RequiredVersion "10.11.12"
92 |
93 | #Validate the returned results
94 | $result.Ensure | should be "Absent"
95 | }
96 |
97 | It "Get-TargetResource with MaximumVersion: Check Present" {
98 |
99 | Set-TargetResource -name "MyTestModule" -Repository $LocalRepository -RequiredVersion "3.2.1" -Ensure "Present" -Verbose
100 | Set-TargetResource -name "MyTestModule" -Repository $LocalRepository -RequiredVersion "1.1" -Ensure "Present" -Verbose
101 | Set-TargetResource -name "MyTestModule" -Repository $LocalRepository -RequiredVersion "1.1.2" -Ensure "Present" -Verbose
102 |
103 | $result = MSFT_PSModule\Get-TargetResource -Name "MyTestModule" -Repository $LocalRepository -MaximumVersion "2.0"
104 |
105 | $result.Ensure | should be "Present"
106 | $result.InstalledVersion | should be "1.1.2" #1.1.2 is the only module -le maximumversion
107 | }
108 |
109 | It "Get-TargetResource MinimumVersion: Check Present" {
110 |
111 | Set-TargetResource -name "MyTestModule" -Repository $LocalRepository -RequiredVersion "1.1.2" -Ensure "Present" -Verbose
112 | Set-TargetResource -name "MyTestModule" -Repository $LocalRepository -RequiredVersion "1.1" -Ensure "Present" -Verbose
113 | Set-TargetResource -name "MyTestModule" -Repository $LocalRepository -RequiredVersion "3.2.1" -Ensure "Present" -Verbose
114 |
115 | $result = MSFT_PSModule\Get-TargetResource -Name "MyTestModule" -Repository $LocalRepository -MinimumVersion "1.1.1"
116 |
117 | $result.Ensure | should be "Present"
118 | $result.InstalledVersion | should be "3.2.1" #Here two modules: 1.1.1 and 3.2.1 are qualified. Get-Target will return the latest
119 | }
120 |
121 | It "Get-TargetResource MinimumVersion and MaximumVersion: Check Present" {
122 |
123 | Set-TargetResource -name "MyTestModule" -Repository $LocalRepository -RequiredVersion "1.1.2" -Ensure "Present" -Verbose
124 | Set-TargetResource -name "MyTestModule" -Repository $LocalRepository -RequiredVersion "1.1" -Ensure "Present" -Verbose
125 | Set-TargetResource -name "MyTestModule" -Repository $LocalRepository -RequiredVersion "3.2.1" -Ensure "Present" -Verbose
126 |
127 | $result = MSFT_PSModule\Get-TargetResource -Name "MyTestModule" -Repository $LocalRepository -MinimumVersion "1.0" -MaximumVersion "2.0"
128 |
129 | $result.Ensure | should be "Present"
130 | $result.InstalledVersion | should be "1.1.2"
131 | }
132 |
133 | }#Describe
134 |
135 | Describe -Name "PSModule Get-TargetResource Error Cases" -Tags "RI" {
136 |
137 | BeforeEach {
138 |
139 | #Remove all left over files if exists
140 | Remove-Item "$($InstallationFolder)\..\..\MyTestModule" -Recurse -Force -ErrorAction SilentlyContinue
141 | Remove-Item "$($InstallationFolder)\..\MyTestModule" -Recurse -Force -ErrorAction SilentlyContinue
142 | }
143 |
144 | AfterEach {
145 |
146 | }
147 |
148 | #Register a local module repository to make the test run faster. This gets called once per Describe.
149 | RegisterRepository -Name "LocalRepository" -InstallationPolicy Trusted -Ensure Present
150 |
151 | # Not allow Max, Req and Min co-existance
152 | It "Get-TargetResource with Max, Req and Min Verion: Check Absent" {
153 |
154 | Set-TargetResource -name "MyTestModule" -Repository $LocalRepository -RequiredVersion "1.1.2" -Ensure "Present" -Verbose
155 |
156 | $result = MSFT_PSModule\Get-TargetResource -Name "MyTestModule" -Repository $LocalRepository `
157 | -MinimumVersion "1.0" -RequiredVersion "1.1.1" #-MaximumVersion "2.3.5"
158 |
159 | # Get-Target does not throw, so check 'Absent' is enough here
160 | $result.Ensure | should be "Absent"
161 | }
162 |
163 | # Min should le Max
164 | It "Get-TargetResource with Max le Min Verion: Check Absent" {
165 |
166 |
167 | Set-TargetResource -name "MyTestModule" -Repository $LocalRepository -RequiredVersion "1.1.2" -Ensure "Present" -Verbose
168 |
169 | $result = MSFT_PSModule\Get-TargetResource -Name "MyTestModule" -Repository $LocalRepository `
170 | -MinimumVersion "5.0" #-MaximumVersion "2.5"
171 |
172 | $result.Ensure | should be "Absent"
173 | }
174 |
175 | It "Get-TargetResource with NoneExistRepository: Check Absent" {
176 |
177 | Set-TargetResource -name "MyTestModule" -Repository $LocalRepository -RequiredVersion "1.1.2" -Ensure "Present" -Verbose
178 |
179 | $result = MSFT_PSModule\Get-TargetResource -Name "MyTestModule" -Repository "NoneExistRepository" `
180 | -MinimumVersion "1.0" # -MaximumVersion "2.5"
181 |
182 | $result.Ensure | should be "Absent"
183 | }
184 | }
185 |
--------------------------------------------------------------------------------
/Test/NugetPackage/NugetPackage.Get.Tests.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (c) Microsoft Corporation.
3 | #
4 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10 | # THE SOFTWARE.
11 | #
12 | $CurrentDirectory = Split-Path -Parent $MyInvocation.MyCommand.Path
13 |
14 | . "$CurrentDirectory\..\OneGetTestHelper.ps1"
15 |
16 | #
17 | # Pre-Requisite: MyTestPackage.12.0.1.1, MyTestPackage.12.0.1, MyTestPackage.15.2.1 packages are available under the $LocalRepositoryPath.
18 | # It's been taken care of by SetupNugetTest
19 | #
20 |
21 | # Calling the setup function
22 | SetupNugetTest
23 |
24 | Describe -Name "NugetPackage Get-TargetResource Basic Test" -Tags "BVT" {
25 |
26 | BeforeEach {
27 |
28 | #Remove all left over files if exists
29 | Remove-Item "$($DestinationPath)" -Recurse -Force -ErrorAction SilentlyContinue
30 | }
31 |
32 | AfterEach {
33 |
34 | }
35 |
36 | Context "NugetPackage Get-TargetResource BVT" {
37 |
38 | #Mock Set-TargetResource/NugetPackage DSC Resource. The tests under this context use the below mock function
39 |
40 | Mock Set-TargetResource {
41 |
42 | #Nuget package folder name format: MyTestPackage.12.0.1, i.e., name + version
43 | $package = $name + "." + $RequiredVersion+ ".nupkg"
44 |
45 | #MyTestPackage.12.0.1.1
46 | $path = "$($DestinationPath)\$($name).$($RequiredVersion)"
47 |
48 | if ($Ensure -ieq "Present") {
49 |
50 | if (!(Test-Path -path $path)) {New-Item $path -Type Directory}
51 |
52 |
53 | #Copy the $package folder to your destination folder
54 | Copy-Item -Path "$($LocalRepositoryPath)\$package" -Destination "$($path)" -Recurse -Force
55 | }
56 | else {
57 |
58 | #Delete the $package folder
59 | Remove-Item "$($path)\$package" -Recurse -Force -ErrorAction SilentlyContinue
60 | }
61 | }
62 |
63 | It "Get-TargetResource with the Mandatory Parameters: Check Absent" {
64 |
65 | # Calling Get-TargetResource in the NugetPackage resource
66 | $result = MSFT_NugetPackage\Get-TargetResource -Name "MyTestPackage" -DestinationPath $DestinationPath -Verbose
67 |
68 | # Validate the result
69 | $result.Ensure | should be "Absent"
70 | }
71 |
72 | It "Get-TargetResource with the Mandatory Parameters: Check Present" {
73 |
74 | Set-TargetResource -name "MyTestPackage" -DestinationPath $DestinationPath -RequiredVersion "12.0.1" -Ensure "Present" -Verbose
75 |
76 | $result = MSFT_NugetPackage\Get-TargetResource -Name "MyTestPackage" -DestinationPath $destinationPath -ErrorVariable ev
77 |
78 | #Validate the returned results
79 | $result.Ensure | should be "Present"
80 | $result.Name | should be "MyTestPackage.12.0.1"
81 | $result.DestinationPath | should be $DestinationPath
82 | $result.InstalledVersion | should be "12.0.1"
83 | $result.SoftwareIdentity | should not BeNullOrEmpty
84 | #($result.Description.Length -ne 0) | should be $true
85 | ($result.Source).StartsWith($DestinationPath) | should be $true
86 | }
87 |
88 | It "Get-TargetResource with RequiredVersion: Check Present" {
89 |
90 | Set-TargetResource -name "MyTestPackage" -DestinationPath $DestinationPath -RequiredVersion "12.0.1" -Ensure "Present" -Verbose
91 |
92 | #provide a req version that exists, expect ensure=Present
93 | $result = MSFT_NugetPackage\Get-TargetResource -Name "MyTestPackage" -DestinationPath $destinationPath -RequiredVersion "12.0.1" -ErrorVariable ev
94 |
95 | #Validate the returned results
96 | $result.Ensure | should be "Present"
97 | $result.Name | should be "MyTestPackage.12.0.1"
98 | $result.InstalledVersion | should be "12.0.1"
99 | }
100 |
101 | It "Get-TargetResource with Non-exist RequiredVersion: Check Absent" {
102 |
103 | Set-TargetResource -name "MyTestPackage" -DestinationPath $DestinationPath -RequiredVersion "12.0.1" -Ensure "Present" -Verbose
104 |
105 | #Provide a req version does not exist, expect Ensure=Absent
106 | $result = MSFT_NugetPackage\Get-TargetResource -Name "MyTestPackage" -DestinationPath $destinationPath -RequiredVersion "10.11.12" -ErrorVariable ev
107 |
108 | #Validate the returned results
109 | $result.Ensure | should be "Absent"
110 | }
111 |
112 |
113 | It "Get-TargetResource with MaximumVersion: Check Present" {
114 |
115 | Set-TargetResource -name "MyTestPackage" -DestinationPath $DestinationPath -RequiredVersion "12.0.1.1" -Ensure "Present" -Verbose
116 | Set-TargetResource -name "MyTestPackage" -DestinationPath $DestinationPath -RequiredVersion "12.0.1" -Ensure "Present" -Verbose
117 | Set-TargetResource -name "MyTestPackage" -DestinationPath $DestinationPath -RequiredVersion "15.2.1" -Ensure "Present" -Verbose
118 |
119 | $result = MSFT_NugetPackage\Get-TargetResource -Name "MyTestPackage" -DestinationPath $destinationPath -MaximumVersion "19.9" -ErrorVariable ev
120 |
121 | $result.Ensure | should be "Present"
122 | $result.InstalledVersion | should be "15.2.1" #1.8.2 is the only package -le maximumversion 1.9.9
123 | }
124 |
125 | It "Get-TargetResource MinimumVersion: Check Present" {
126 |
127 | Set-TargetResource -name "MyTestPackage" -DestinationPath $DestinationPath -RequiredVersion "12.0.1.1" -Ensure "Present" -Verbose
128 | Set-TargetResource -name "MyTestPackage" -DestinationPath $DestinationPath -RequiredVersion "12.0.1" -Ensure "Present" -Verbose
129 | Set-TargetResource -name "MyTestPackage" -DestinationPath $DestinationPath -RequiredVersion "15.2.1" -Ensure "Present" -Verbose
130 |
131 | $result = MSFT_NugetPackage\Get-TargetResource -Name "MyTestPackage" -DestinationPath $destinationPath -MinimumVersion "12.0.1"
132 |
133 | $result.Ensure | should be "Present"
134 | $result.InstalledVersion | should be "15.2.1" #Get-package will return the latest version
135 | }
136 |
137 |
138 | It "Get-TargetResource MinimumVersion and MaximumVersion: Check Present" {
139 |
140 | Set-TargetResource -name "MyTestPackage" -DestinationPath $DestinationPath -RequiredVersion "12.0.1.1" -Ensure "Present" -Verbose
141 | Set-TargetResource -name "MyTestPackage" -DestinationPath $DestinationPath -RequiredVersion "12.0.1" -Ensure "Present" -Verbose
142 | Set-TargetResource -name "MyTestPackage" -DestinationPath $DestinationPath -RequiredVersion "15.2.1" -Ensure "Present" -Verbose
143 |
144 | #will return the latest, ie 15.2.1
145 | $result = MSFT_NugetPackage\Get-TargetResource -Name "MyTestPackage" -DestinationPath $destinationPath -MinimumVersion "15.0" -MaximumVersion "19.0"
146 |
147 | $result.Ensure | should be "Present"
148 | $result.InstalledVersion | should be "15.2.1"
149 | }
150 |
151 | }#context
152 | }#Describe
153 |
154 | Describe -Name "NugetPackage Get-Dscconfiguration Error Cases" -Tags "RI" {
155 |
156 |
157 | BeforeEach {
158 |
159 | #Remove all left over files if exists
160 | Remove-Item "$($DestinationPath)" -Recurse -Force -ErrorAction SilentlyContinue
161 | }
162 |
163 | AfterEach {
164 |
165 | }
166 |
167 | #Mock Set-TargetResource/NugetPackage DSC Resource
168 | Mock Set-TargetResource {
169 |
170 | #Nuget package folder name format: MyTestPackage.12.0.1, i.e., name + version
171 | $package = $Name + "." + $RequiredVersion
172 |
173 | if ($Ensure -ieq "Present") {
174 |
175 | #Copy the $package folder to your destination folder
176 | Copy-Item -Path "$($LocalRepositoryPath)\$package" -Destination "$($DestinationPath)\$package" -Recurse -Force
177 | }
178 | else {
179 |
180 | #Delete the $package folder
181 | Remove-Item "$($DestinationPath)\$package" -Recurse -Force -ErrorAction SilentlyContinue
182 | }
183 |
184 | }
185 |
186 | It "Get-TargetResource with Max, Req and Min Verion: Check Error" {
187 |
188 | try
189 | {
190 |
191 | $result = MSFT_NugetPackage\Get-TargetResource -Name "MyTestPackage" -DestinationPath $destinationPath `
192 | -MinimumVersion "2.1.3" -RequiredVersion "1.1.1" -MaximumVersion "2.3.5" `
193 | -ErrorVariable ev
194 |
195 | }
196 | Catch
197 | {
198 | $_.FullyQualifiedErrorId | should be "VersionError"
199 | return
200 | }
201 |
202 |
203 | throw "Expect VersionError but not happen"
204 | }
205 |
206 | It "Get-TargetResource with Max and Min Verion: Check Error" {
207 |
208 | try
209 | {
210 |
211 | $result = MSFT_NugetPackage\Get-TargetResource -Name "MyTestPackage" -DestinationPath $destinationPath `
212 | -MinimumVersion "5.0" -MaximumVersion "2.5" `
213 | -ErrorVariable ev
214 |
215 | }
216 | Catch
217 | {
218 | $_.FullyQualifiedErrorId | should be "VersionError"
219 | return
220 | }
221 |
222 | throw "Expect VersionError but not happen"
223 | }
224 | }
225 |
--------------------------------------------------------------------------------
/Test/PackageManagement/PackageManagement.Get.Tests.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (c) Microsoft Corporation.
3 | #
4 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10 | # THE SOFTWARE.
11 | #
12 | $CurrentDirectory = Split-Path -Parent $MyInvocation.MyCommand.Path
13 |
14 | . "$CurrentDirectory\..\OneGetTestHelper.ps1"
15 |
16 | #
17 | # Pre-Requisite: MyTestPackage.12.0.1.1, MyTestPackage.12.0.1, MyTestPackage.15.2.1 packages are available under the $LocalRepositoryPath.
18 | # It's been taken care of by SetupPackageManagementTest
19 | #
20 |
21 | # Calling the setup function
22 | SetupPackageManagementTest
23 |
24 | $AdditionalParameters = @{"Destination" = $DestinationPath}
25 | $AdditionalParameterCimInstanceArray = ConvertHashtableToArryCimInstance $AdditionalParameters
26 |
27 | Describe -Name "PackageManagement Get-TargetResource Basic Test" -Tags "BVT" {
28 |
29 | BeforeEach {
30 | #Remove all left over files if exists
31 | Remove-Item "$($DestinationPath)" -Recurse -Force -ErrorAction SilentlyContinue
32 | }
33 |
34 | AfterEach {
35 |
36 | }
37 |
38 | Context "PackageManagement Get-TargetResource BVT" {
39 |
40 | #Mock Set-TargetResource/PackageManagement DSC Resource. The tests under this context use the below mock function
41 |
42 | Mock Set-TargetResource {
43 |
44 | #Nuget package folder name format: MyTestPackage.12.0.1, i.e., name + version
45 | $package = $name + "." + $RequiredVersion+ ".nupkg"
46 |
47 | #MyTestPackage.12.0.1.1
48 | $path = "$($DestinationPath)\$($name).$($RequiredVersion)"
49 |
50 | if ($Ensure -ieq "Present") {
51 |
52 | if (!(Test-Path -path $path)) {New-Item $path -Type Directory}
53 |
54 |
55 | #Copy the $package folder to your destination folder
56 | Copy-Item -Path "$($LocalRepositoryPath)\$package" -Destination "$($path)" -Recurse -Force
57 | }
58 | else {
59 |
60 | #Delete the $package folder
61 | Remove-Item "$($path)\$package" -Recurse -Force -ErrorAction SilentlyContinue
62 | }
63 | }
64 |
65 | It "Get-TargetResource with the Mandatory Parameters: Check Absent" {
66 |
67 | # Calling Get-TargetResource in the NugetPackage resource
68 | $result = MSFT_PackageManagement\Get-TargetResource -Name "MyTestPackage" -Verbose
69 |
70 | # Validate the result
71 | $result.Ensure | should be "Absent"
72 | }
73 |
74 | It "Get-TargetResource with the Mandatory Parameters: Check Present" {
75 |
76 | Set-TargetResource -name "MyTestPackage" -RequiredVersion "12.0.1" -Ensure "Present" -AdditionalParameters $AdditionalParameterCimInstanceArray -Verbose
77 |
78 | $result = MSFT_PackageManagement\Get-TargetResource -Name "MyTestPackage" -AdditionalParameters $AdditionalParameterCimInstanceArray -ErrorVariable ev
79 |
80 | #Validate the returned results
81 | $result.Ensure | should be "Present"
82 | $result.Name | should be "MyTestPackage"
83 | $result.ProviderName | should be "NuGet"
84 | $result.RequiredVersion | should be "12.0.1"
85 | ($result.Source).StartsWith($DestinationPath) | should be $true
86 | }
87 |
88 | It "Get-TargetResource with RequiredVersion: Check Present" {
89 |
90 | Set-TargetResource -name "MyTestPackage" -RequiredVersion "12.0.1" -Ensure "Present" -AdditionalParameters $AdditionalParameterCimInstanceArray -Verbose
91 |
92 | #provide a req version that exists, expect ensure=Present
93 | $result = MSFT_PackageManagement\Get-TargetResource -Name "MyTestPackage" -AdditionalParameters $AdditionalParameterCimInstanceArray -RequiredVersion "12.0.1" -ErrorVariable ev
94 |
95 | #Validate the returned results
96 | $result.Ensure | should be "Present"
97 | $result.Name | should be "MyTestPackage"
98 | $result.RequiredVersion | should be "12.0.1"
99 | }
100 |
101 | It "Get-TargetResource with Non-exist RequiredVersion: Check Absent" {
102 |
103 | Set-TargetResource -name "MyTestPackage" -RequiredVersion "12.0.1" -Ensure "Present" -Verbose -AdditionalParameters $AdditionalParameterCimInstanceArray
104 |
105 | #Provide a req version does not exist, expect Ensure=Absent
106 | $result = MSFT_PackageManagement\Get-TargetResource -Name "MyTestPackage" -RequiredVersion "10.11.12" -ErrorVariable ev -AdditionalParameters $AdditionalParameterCimInstanceArray
107 |
108 | #Validate the returned results
109 | $result.Ensure | should be "Absent"
110 | }
111 |
112 | It "Get-TargetResource with MaximumVersion: Check Present" {
113 |
114 | Set-TargetResource -name "MyTestPackage" -AdditionalParameters $AdditionalParameterCimInstanceArray -RequiredVersion "12.0.1.1" -Ensure "Present" -Verbose
115 | Set-TargetResource -name "MyTestPackage" -AdditionalParameters $AdditionalParameterCimInstanceArray -RequiredVersion "12.0.1" -Ensure "Present" -Verbose
116 | Set-TargetResource -name "MyTestPackage" -AdditionalParameters $AdditionalParameterCimInstanceArray -RequiredVersion "15.2.1" -Ensure "Present" -Verbose
117 |
118 | $result = MSFT_PackageManagement\Get-TargetResource -Name "MyTestPackage" -AdditionalParameters $AdditionalParameterCimInstanceArray -MaximumVersion "19.9" -ErrorVariable ev
119 |
120 | $result.Ensure | should be "Present"
121 | $result.RequiredVersion | should be "15.2.1" #1.8.2 is the only package -le maximumversion 1.9.9
122 | }
123 |
124 | It "Get-TargetResource MinimumVersion: Check Present" {
125 |
126 | Set-TargetResource -name "MyTestPackage" -RequiredVersion "12.0.1.1" -Ensure "Present" -Verbose -AdditionalParameters $AdditionalParameterCimInstanceArray
127 | Set-TargetResource -name "MyTestPackage" -RequiredVersion "12.0.1" -Ensure "Present" -Verbose -AdditionalParameters $AdditionalParameterCimInstanceArray
128 | Set-TargetResource -name "MyTestPackage" -RequiredVersion "15.2.1" -Ensure "Present" -Verbose -AdditionalParameters $AdditionalParameterCimInstanceArray
129 |
130 | $result = MSFT_PackageManagement\Get-TargetResource -Name "MyTestPackage" -AdditionalParameters $AdditionalParameterCimInstanceArray -MinimumVersion "12.0.1"
131 |
132 | $result.Ensure | should be "Present"
133 | $result.RequiredVersion | should be "15.2.1" #Get-package will return the latest version
134 | }
135 |
136 | It "Get-TargetResource MinimumVersion and MaximumVersion: Check Present" {
137 |
138 | Set-TargetResource -name "MyTestPackage" -AdditionalParameters $AdditionalParameterCimInstanceArray -RequiredVersion "12.0.1.1" -Ensure "Present" -Verbose
139 | Set-TargetResource -name "MyTestPackage" -AdditionalParameters $AdditionalParameterCimInstanceArray -RequiredVersion "12.0.1" -Ensure "Present" -Verbose
140 | Set-TargetResource -name "MyTestPackage" -AdditionalParameters $AdditionalParameterCimInstanceArray -RequiredVersion "15.2.1" -Ensure "Present" -Verbose
141 |
142 | #will return the latest, ie 15.2.1
143 | $result = MSFT_PackageManagement\Get-TargetResource -Name "MyTestPackage" -AdditionalParameters $AdditionalParameterCimInstanceArray -MinimumVersion "15.0" -MaximumVersion "19.0"
144 |
145 | $result.Ensure | should be "Present"
146 | $result.RequiredVersion | should be "15.2.1"
147 | }
148 |
149 | }#context
150 | }#Describe
151 |
152 | Describe -Name "PackageManagement Get-Dscconfiguration Error Cases" -Tags "RI" {
153 |
154 |
155 | BeforeEach {
156 |
157 | #Remove all left over files if exists
158 | Remove-Item "$($DestinationPath)" -Recurse -Force -ErrorAction SilentlyContinue
159 | }
160 |
161 | AfterEach {
162 |
163 | }
164 |
165 | #Mock Set-TargetResource/NugetPackage DSC Resource
166 | Mock Set-TargetResource {
167 |
168 | #Nuget package folder name format: MyTestPackage.12.0.1, i.e., name + version
169 | $package = $Name + "." + $RequiredVersion
170 |
171 | if ($Ensure -ieq "Present") {
172 |
173 | #Copy the $package folder to your destination folder
174 | Copy-Item -Path "$($LocalRepositoryPath)\$package" -Destination "$($DestinationPath)\$package" -Recurse -Force
175 | }
176 | else {
177 |
178 | #Delete the $package folder
179 | Remove-Item "$($DestinationPath)\$package" -Recurse -Force -ErrorAction SilentlyContinue
180 | }
181 |
182 | }
183 |
184 | It "Get-TargetResource with Max, Req and Min Verion: Check Error" {
185 |
186 | $result = MSFT_PackageManagement\Get-TargetResource -Name "MyTestPackage" -AdditionalParameters $AdditionalParameterCimInstanceArray `
187 | -MinimumVersion "2.1.3" -RequiredVersion "1.1.1" -MaximumVersion "2.3.5" `
188 | -ErrorVariable ev
189 |
190 | ($ev -ne $null) | should be $true
191 | $ev[0].FullyQualifiedErrorId | should be "VersionRangeAndRequiredVersionCannotBeSpecifiedTogether,Microsoft.PowerShell.PackageManagement.Cmdlets.GetPackage"
192 | }
193 |
194 | It "Get-TargetResource with Max and Min Verion: Check Error" {
195 |
196 | $result = MSFT_PackageManagement\Get-TargetResource -Name "MyTestPackage" -AdditionalParameters $AdditionalParameterCimInstanceArray `
197 | -MinimumVersion "5.0" -MaximumVersion "2.5" `
198 | -ErrorVariable ev
199 |
200 | ($ev -ne $null) | should be $true
201 | $ev[0].FullyQualifiedErrorId | should be "NoMatchFound,Microsoft.PowerShell.PackageManagement.Cmdlets.GetPackage"
202 | }
203 | }
204 |
--------------------------------------------------------------------------------
/DSCResources/OneGetHelper.psm1:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (c) Microsoft Corporation.
3 | #
4 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10 | # THE SOFTWARE.
11 | #
12 | #Helper functions for PackageManagement DSC Resouces
13 |
14 |
15 | Import-LocalizedData -BindingVariable LocalizedData -filename OneGetHelper.strings.psd1
16 |
17 |
18 | Function ExtractArguments
19 | {
20 | <#
21 | .SYNOPSIS
22 |
23 | This is a helper function that extract the parameters from a given table.
24 |
25 | .PARAMETER FunctionBoundParameters
26 | Specifies the hashtable containing a set of parameters to be extracted
27 |
28 | .PARAMETER ArgumentNames
29 | Specifies A list of arguments you want to extract
30 | #>
31 |
32 | Param
33 | (
34 | [parameter(Mandatory = $true)]
35 | [System.Collections.Hashtable]
36 | $FunctionBoundParameters,
37 |
38 | #A list of arguments you want to extract
39 | [parameter(Mandatory = $true)]
40 | [System.String[]]$ArgumentNames
41 | )
42 |
43 | Write-Verbose -Message ($LocalizedData.CallingFunction -f $($MyInvocation.mycommand))
44 |
45 | $returnValue=@{}
46 |
47 | foreach ($arg in $ArgumentNames)
48 | {
49 | if($FunctionBoundParameters.ContainsKey($arg))
50 | {
51 | #Found an argument we are looking for, so we add it to return collection
52 | $returnValue.Add($arg,$FunctionBoundParameters[$arg])
53 | }
54 | }
55 |
56 | return $returnValue
57 | }
58 |
59 | function ThrowError
60 | {
61 | <#
62 | .SYNOPSIS
63 |
64 | This is a helper function that throws an error.
65 |
66 | .PARAMETER ExceptionName
67 | Specifies the type of errors, e.g. System.ArgumentException
68 |
69 | .PARAMETER ExceptionMessage
70 | Specifies the exception message
71 |
72 | .PARAMETER ErrorId
73 | Specifies an identifier of the error
74 |
75 | .PARAMETER ErrorCategory
76 | Specifies the error category, e.g., InvalidArgument defined in System.Management.Automation.
77 |
78 | #>
79 |
80 | param
81 | (
82 | [parameter(Mandatory = $true)]
83 | [ValidateNotNullOrEmpty()]
84 | [System.String]
85 | $ExceptionName,
86 |
87 | [parameter(Mandatory = $true)]
88 | [ValidateNotNullOrEmpty()]
89 | [System.String]
90 | $ExceptionMessage,
91 |
92 | [parameter(Mandatory = $true)]
93 | [ValidateNotNullOrEmpty()]
94 | [System.String]
95 | $ErrorId,
96 |
97 | [parameter(Mandatory = $true)]
98 | [ValidateNotNull()]
99 | [System.Management.Automation.ErrorCategory]
100 | $ErrorCategory
101 | )
102 |
103 | Write-Verbose -Message ($LocalizedData.CallingFunction -f $($MyInvocation.mycommand))
104 |
105 | $exception = New-Object -TypeName $ExceptionName -ArgumentList $ExceptionMessage;
106 | $errorRecord = New-Object -TypeName System.Management.Automation.ErrorRecord -ArgumentList ($exception, $ErrorId, $ErrorCategory, $null)
107 | throw $errorRecord
108 | }
109 |
110 | Function ValidateArgument
111 | {
112 | <#
113 | .SYNOPSIS
114 |
115 | This is a helper function that validates the arguments.
116 |
117 | .PARAMETER Argument
118 | Specifies the argument to be validated.
119 |
120 | .PARAMETER Type
121 | Specifies the type of argument.
122 | #>
123 |
124 | [CmdletBinding()]
125 | param
126 | (
127 | [parameter(Mandatory = $true)]
128 | [ValidateNotNullOrEmpty()]
129 | [string]$Argument,
130 |
131 | [parameter(Mandatory = $true)]
132 | [ValidateNotNullOrEmpty()]
133 | [String]$Type,
134 |
135 | [parameter(Mandatory = $true)]
136 | [ValidateNotNullOrEmpty()]
137 | [String]$ProviderName
138 | )
139 |
140 | Write-Verbose -Message ($LocalizedData.CallingFunction -f $($MyInvocation.mycommand))
141 |
142 | switch ($Type)
143 | {
144 |
145 | "SourceUri"
146 | {
147 | # Checks whether given URI represents specific scheme
148 | # Most common schemes: file, http, https, ftp
149 | $scheme =@('http', 'https', 'file', 'ftp')
150 |
151 | $newUri = $Argument -as [System.URI]
152 | $returnValue = ($newUri -and $newUri.AbsoluteURI -and ($scheme -icontains $newuri.Scheme))
153 |
154 | if ($returnValue -eq $false)
155 | {
156 | ThrowError -ExceptionName "System.ArgumentException" `
157 | -ExceptionMessage ($LocalizedData.InValidUri -f $Argument)`
158 | -ErrorId "InValidUri" `
159 | -ErrorCategory InvalidArgument
160 | }
161 |
162 | #Check whether it's a valid uri. Wait for the response within 2mins.
163 | <#$result = Invoke-WebRequest $newUri -TimeoutSec 120 -UseBasicParsing -ErrorAction SilentlyContinue
164 |
165 | if ($null -eq (([xml]$result.Content).service ))
166 | {
167 | ThrowError -ExceptionName "System.ArgumentException" `
168 | -ExceptionMessage ($LocalizedData.InValidUri -f $Argument)`
169 | -ErrorId "InValidUri" `
170 | -ErrorCategory InvalidArgument
171 | }#>
172 |
173 | }
174 | "DestinationPath"
175 | {
176 | $returnValue = Test-Path -Path $Argument
177 | if ($returnValue -eq $false)
178 | {
179 | ThrowError -ExceptionName "System.ArgumentException" `
180 | -ExceptionMessage ($LocalizedData.PathDoesNotExist -f $Argument)`
181 | -ErrorId "PathDoesNotExist" `
182 | -ErrorCategory InvalidArgument
183 | }
184 | }
185 | "PackageSource"
186 | {
187 | #Argument can be either the package source Name or source Uri.
188 |
189 | #Check if the source is a uri
190 | $uri = $Argument -as [System.URI]
191 |
192 | if($uri -and $uri.AbsoluteURI)
193 | {
194 | # Check if it's a valid Uri
195 | ValidateArgument -Argument $Argument -Type "SourceUri" -ProviderName $ProviderName
196 | }
197 | else
198 | {
199 | #Check if it's a registered package source name
200 | $source = PackageManagement\Get-PackageSource -Name $Argument -ProviderName $ProviderName -verbose -ErrorVariable ev
201 | if ((-not $source) -or $ev)
202 | {
203 | #We do not need to throw error here as Get-PackageSource does already
204 | Write-Verbose -Message ($LocalizedData.SourceNotFound -f $source)
205 | }
206 | }
207 | }
208 | default
209 | {
210 | ThrowError -ExceptionName "System.ArgumentException" `
211 | -ExceptionMessage ($LocalizedData.UnexpectedArgument -f $Type)`
212 | -ErrorId "UnexpectedArgument" `
213 | -ErrorCategory InvalidArgument
214 | }
215 | }
216 | }
217 |
218 | Function ValidateVersionArgument
219 | {
220 | <#
221 | .SYNOPSIS
222 |
223 | This is a helper function that does the version validation.
224 |
225 | .PARAMETER RequiredVersion
226 | Provides the required version.
227 |
228 | .PARAMETER MaximumVersion
229 | Provides the maximum version.
230 |
231 | .PARAMETER MinimumVersion
232 | Provides the minimum version.
233 | #>
234 |
235 | [CmdletBinding()]
236 | param
237 | (
238 | [string]$RequiredVersion,
239 | [string]$MinimumVersion,
240 | [string]$MaximumVersion
241 |
242 | )
243 |
244 | Write-Verbose -Message ($LocalizedData.CallingFunction -f $($MyInvocation.mycommand))
245 |
246 | $isValid = $false
247 |
248 | #Case 1: No further check required if a user provides either none or one of these: minimumVersion, maximumVersion, and requiredVersion
249 | if ($PSBoundParameters.Count -le 1)
250 | {
251 | return $true
252 | }
253 |
254 | #Case 2: #If no RequiredVersion is provided
255 | if (-not $PSBoundParameters.ContainsKey('RequiredVersion'))
256 | {
257 | #If no RequiredVersion, both MinimumVersion and MaximumVersion are provided. Otherwise fall into the Case #1
258 | $isValid = $PSBoundParameters['MinimumVersion'] -le $PSBoundParameters['MaximumVersion']
259 | }
260 |
261 | #Case 3: RequiredVersion is provided.
262 | # In this case MinimumVersion and/or MaximumVersion also are provided. Otherwise fall in to Case #1.
263 | # This is an invalid case. When RequiredVersion is provided, others are not allowed. so $isValid is false, which is already set in the init
264 |
265 | if ($isValid -eq $false)
266 | {
267 | ThrowError -ExceptionName "System.ArgumentException" `
268 | -ExceptionMessage ($LocalizedData.VersionError)`
269 | -ErrorId "VersionError" `
270 | -ErrorCategory InvalidArgument
271 | }
272 | }
273 |
274 | Function Get-InstallationPolicy
275 | {
276 | <#
277 | .SYNOPSIS
278 |
279 | This is a helper function that retrives the InstallationPolicy from the given repository.
280 |
281 | .PARAMETER RepositoryName
282 | Provides the repository Name.
283 |
284 | #>
285 |
286 | Param
287 | (
288 | [parameter(Mandatory = $true)]
289 | [ValidateNotNullOrEmpty()]
290 | [System.String]$RepositoryName
291 | )
292 |
293 | Write-Verbose -Message ($LocalizedData.CallingFunction -f $($MyInvocation.mycommand))
294 |
295 | $repositoryobj = PackageManagement\Get-PackageSource -Name $RepositoryName -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
296 |
297 | if ($repositoryobj)
298 | {
299 | return $repositoryobj.IsTrusted
300 | }
301 | }
302 |
--------------------------------------------------------------------------------
/Test/PackageManagementSource/OneGetSource.Get.Set.Test.Tests.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (c) Microsoft Corporation.
3 | #
4 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10 | # THE SOFTWARE.
11 | #
12 | $CurrentDirectory = Split-Path -Parent $MyInvocation.MyCommand.Path
13 |
14 | . "$CurrentDirectory\..\OneGetTestHelper.ps1"
15 |
16 | #Calling the setup function
17 | SetupOneGetSourceTest
18 |
19 | Describe -Name "PackageManagementSource Get.Set.Test-TargetResource Basic Test" -Tags "BVT" {
20 |
21 | BeforeEach {
22 |
23 | #Unregister the source if already registered
24 | UnRegisterSource -Name "MyNuget" -providerName "Nuget" -SourceUri $LocalRepositoryPath
25 | }
26 |
27 | AfterEach {
28 | }
29 |
30 | Context "PackageManagementSource Get.Set.Test-TargetResource Basic Test" {
31 |
32 | It "Get.Set.Test-TargetResource: Check Present" {
33 |
34 | #Register the package source
35 | MSFT_PackageManagementSource\Set-TargetResource -name "MyNuget" -providerName "Nuget" -SourceUri $LocalRepositoryPath -Ensure Present -Verbose
36 |
37 | #Test it to make sure Set-TargetResource is successfully register the source
38 | $testResult = MSFT_PackageManagementSource\Test-TargetResource -Name "MyNuget" -providerName "Nuget" -SourceUri $LocalRepositoryPath -Verbose
39 |
40 | $testResult | should be $true
41 |
42 | #Validate the returned Get results
43 | $getResult = MSFT_PackageManagementSource\Get-TargetResource -Name "MyNuget" -providerName "Nuget" -SourceUri $LocalRepositoryPath -Verbose
44 |
45 | $getResult.Ensure | should be "Present"
46 | $getResult.Name | should be "MyNuget"
47 | $getResult.SourceUri | should be $LocalRepositoryPath
48 | $getResult.InstallationPolicy | should be "Untrusted" #default is untrusted
49 | $getResult.Providername | should be "Nuget"
50 | }
51 |
52 |
53 | It "Get.Set.Test-TargetResource: Check Absent" {
54 |
55 |
56 | #Test it to make sure the source is unregistered
57 | $testResult = MSFT_PackageManagementSource\Test-TargetResource -Name "MyNuget" -providerName "Nuget" -SourceUri $LocalRepositoryPath -Verbose
58 |
59 | $testResult | should be $false
60 |
61 | #Validate the returned Get results
62 | $getResult = MSFT_PackageManagementSource\Get-TargetResource -Name "MyNuget" -providerName "Nuget" -SourceUri $LocalRepositoryPath -Verbose
63 |
64 | $getResult.Ensure | should be "Absent"
65 | $getResult.Name | should be "MyNuget"
66 | $getResult.Providername | should be "Nuget"
67 | $getResult.SourceUri | should BeNullOrEmpty
68 | $getResult.InstallationPolicy | should BeNullOrEmpty
69 | }
70 |
71 |
72 | It "Get.Set.Test-TargetResource with the multiple Sources" {
73 |
74 | #Unregister the source if already registered
75 | UnRegisterSource -Name "MyNuget1" -providerName "Nuget" -SourceUri $LocalRepositoryPath1
76 | UnRegisterSource -Name "MyNuget2" -providerName "Nuget" -SourceUri $LocalRepositoryPath2
77 |
78 | Try
79 | {
80 | #Register the package source
81 | MSFT_PackageManagementSource\Set-TargetResource -name "MyNuget" -providerName "Nuget" -SourceUri $LocalRepositoryPath -Ensure Present -Verbose
82 | MSFT_PackageManagementSource\Set-TargetResource -name "MyNuget1" -providerName "Nuget" -SourceUri $LocalRepositoryPath1 -Ensure Present -Verbose
83 | MSFT_PackageManagementSource\Set-TargetResource -name "MyNuget2" `
84 | -providerName "Nuget" `
85 | -SourceUri $LocalRepositoryPath2 `
86 | -Ensure Present `
87 | -InstallationPolicy Trusted `
88 | -Verbose
89 |
90 |
91 | $testResult = MSFT_PackageManagementSource\Test-TargetResource -Name "MyNuget" `
92 | -providerName "Nuget"`
93 | -SourceUri $LocalRepositoryPath `
94 | -InstallationPolicy Trusted `
95 | -Verbose
96 |
97 | #We registered a source with untrusted installation policy but test-targetresource uses trusted, so it's a false
98 | $testResult | should be $false
99 |
100 | $testResult = MSFT_PackageManagementSource\Test-TargetResource -Name "MyNuget" `
101 | -providerName "Nuget"`
102 | -SourceUri $LocalRepositoryPath1 `
103 | -InstallationPolicy Untrusted `
104 | -Verbose
105 |
106 | #We registered a source with $LocalRepositoryPath but test-targetresource uses $LocalRepositoryPath1 , so it's a false
107 | $testResult | should be $false
108 |
109 | $testResult = MSFT_PackageManagementSource\Test-TargetResource -Name "MyNuget2" `
110 | -providerName "Nuget"`
111 | -SourceUri $LocalRepositoryPath2 `
112 | -InstallationPolicy Trusted `
113 | -Verbose
114 |
115 | # The properties in Test and Set all match, should return true
116 | $testResult | should be $true
117 | }
118 | finally
119 | {
120 | #Unregister the source if already registered
121 | UnRegisterSource -Name "MyNuget" -providerName "Nuget" -SourceUri $LocalRepositoryPath
122 | UnRegisterSource -Name "MyNuget1" -providerName "Nuget" -SourceUri $LocalRepositoryPath1
123 | UnRegisterSource -Name "MyNuget2" -providerName "Nuget" -SourceUri $LocalRepositoryPath2
124 | }
125 | }
126 |
127 |
128 | It "Get.Set.Test-TargetResource with SourceCredential: Check Registered" {
129 |
130 | $credential = (CreateCredObject -Name ".\Administrator" -PSCode "MassRules!")
131 |
132 | MSFT_PackageManagementSource\Set-TargetResource -name "MyNuget" `
133 | -providerName "Nuget" `
134 | -SourceUri $LocalRepositoryPath `
135 | -Ensure Present `
136 | -InstallationPolicy Trusted `
137 | -SourceCredential $credential `
138 | -Verbose
139 |
140 |
141 | # Validate the package is installed
142 | $testResult = MSFT_PackageManagementSource\Test-TargetResource -Name "MyNuget" `
143 | -providerName "Nuget" `
144 | -SourceUri $LocalRepositoryPath `
145 | -Ensure Present `
146 | -InstallationPolicy Trusted `
147 | -SourceCredential $credential `
148 | -Verbose
149 |
150 | # The properties in Test and Set all match, should return true
151 | $testResult | should be $true
152 |
153 | }
154 |
155 | It "Set-TargetResource to change installationpolicy from untrusted to trusted: Check Installed" {
156 |
157 | #Register the package source
158 | MSFT_PackageManagementSource\Set-TargetResource -name "MyNuget" -providerName "Nuget" -SourceUri $LocalRepositoryPath -Ensure Present -InstallationPolicy Untrusted -Verbose
159 |
160 | #Test it to make sure Set-TargetResource is successfully unregister the source
161 | $testResult = MSFT_PackageManagementSource\Test-TargetResource -Name "MyNuget" -providerName "Nuget" -SourceUri $LocalRepositoryPath
162 |
163 | $testResult | should be $true
164 |
165 |
166 | #register it with the same name but different source uri
167 | MSFT_PackageManagementSource\Set-TargetResource -name "MyNuget" -providerName "Nuget" -SourceUri $LocalRepositoryPath -Ensure Present -InstallationPolicy Trusted -Verbose
168 |
169 | $testResult = MSFT_PackageManagementSource\Test-TargetResource -Name "MyNuget" -providerName "Nuget" -SourceUri $LocalRepositoryPath -InstallationPolicy Trusted
170 |
171 | $testResult | should be $true
172 |
173 | }
174 |
175 | }#context
176 |
177 | Context "PackageManagementSource Get.Set.Test-TargetResource Error Case" {
178 |
179 | It "Get-TargetResource to unregistered a source that does not exist: Check Error" {
180 |
181 | try
182 | {
183 | MSFT_PackageManagementSource\Set-TargetResource -name "MyNuget" -providerName "Nuget" -SourceUri $LocalRepositoryPath -Ensure Absent -Verbose 2>&1
184 | }
185 | catch
186 | {
187 | $_.FullyQualifiedErrorId -ieq "UnRegisterFailed" | should be $true
188 | return
189 | }
190 |
191 | Throw "Expected Error 'UnRegisterFailed' does not happen"
192 | }
193 |
194 | } #context
195 |
196 | }#Describe
197 |
198 |
199 |
200 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 | >`Announcement`
7 |
8 | This repo has been deprecated. The PackageManagementProviderResource module has been merged to [PackageManagement]( https://github.com/OneGet/oneget/tree/WIP/src/Microsoft.PackageManagement.DscResources). Please use https://github.com/OneGet/oneget going forward. Thank you!
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 | ### PackageManagementProviderResource
20 |
21 | The PackageManagementProviderResource is the DSC resources for PackageManagement (aka OneGet) providers. Currently it contains the Nuget and PowerShellGet provider DSC resources to allow you to manage packages and Windows PowerShell modules.
22 |
23 | #### Contributing
24 | Please check out common DSC Resources [contributing guidelines](https://github.com/PowerShell/DscResource.Kit/blob/master/CONTRIBUTING.md).
25 |
26 | #### Resources
27 |
28 | * **PackageManagement** – A generic PackageManagement provider that lets you download and install packages from any source. This provider uses Install-Package & Get-Package cmdlets. You may have to use PackageManagementSource DSC resource to register non-default sources.
29 |
30 | * **NugetPackage** – lets you download packages from the NuGet source location (e.g., http://nuget.org/api/v2/), and install or uninstall the package.
31 |
32 | * **PSModule** – lets you download Windows PowerShell modules from the PowerShell Gallery, "PSGallery" (e.g., https://www.powershellgallery.com/api/v2/ ), and install them on your computer.
33 |
34 | * **PackageManagementSource** – lets you register or unregister a package source on your computer
35 |
36 | **PackageManagement** DSC resource has the following properties:
37 |
38 |
39 | | Property |
40 | Description |
41 |
42 |
43 | | Name |
44 | Specifies the name of the Package to be installed or uninstalled. |
45 |
46 |
47 | | Source |
48 | Specifies the name of the package source where the package can be found. This can either be a URI or a source registered with Register-PackageSource cmdlet or PackageManagementSource DSC resource. The DSC resource MSFT_PackageManagementSource can also register a package source. |
49 |
50 |
51 | | Ensure |
52 | Determines whether the package is to be installed or uninstalled. |
53 |
54 |
55 | | RequiredVersion |
56 | Specifies the exact version of the package that you want to install. If you do not specify this parameter, this DSC resource installs the newest available version of the package that also satisfies any maximum version specified by the MaximumVersion parameter. |
57 |
58 |
59 | | MinimumVersion |
60 | Specifies the minimum allowed version of the package that you want to install. If you do not add this parameter, this DSC resource intalls the highest available version of the package that also satisfies any maximum specified version specified by the MaximumVersion parameter. |
61 |
62 |
63 | | MaximumVersion |
64 | Specifies the maximum allowed version of the package that you want to install. If you do not specify this parameter, this DSC resource installs the highest-numbered available version of the package. |
65 |
66 |
67 | | SourceCredential |
68 | Specifies a user account that has rights to install a package for a specified package provider or source. |
69 |
70 |
71 | | ProviderName |
72 | Specifies a package provider name to which to scope your package search. You can get package provider names by running the Get-PackageProvider cmdlet. |
73 |
74 |
75 | | AdditionalParameters |
76 | Provider specific parameters that are passed as an Hashtable. For example, for NuGet provider you can pass additional parameters like DestinationPath. |
77 |
78 |
79 |
80 | **NugetPackage** DSC resource has the following properties:
81 |
82 |
83 | | Property |
84 | Description |
85 |
86 |
87 | | Name |
88 | Specifies the name of the package to be installed or uninstalled. |
89 |
90 |
91 | | DestinationPath |
92 | Specifies a file location where you want the package to be installed. |
93 |
94 |
95 | | Ensure |
96 | Determines whether the package is to be installed or uninstalled. |
97 |
98 |
99 | | InstallationPolicy |
100 | Determines whether you trust the package's source. |
101 |
102 |
103 | | RequiredVersion |
104 | Specifies the exact version of the package you want to install or uninstall. |
105 |
106 |
107 | | MinimumVersion |
108 | Specifies the minimum version of the package you want to install or uninstall. |
109 |
110 |
111 | | MaximumVersion |
112 | Specifies the maximum version of the package you want to install or uninstall. |
113 |
114 |
115 | | Source |
116 | Specifies the URI or name of the registered package source. |
117 |
118 |
119 | | SourceCredential |
120 | Provides access to the package on a remote source. This property is not used to install the package. The package is always installed on the local system account. |
121 |
122 |
123 |
124 | **PSModule** DSC resource has the following properties:
125 |
126 |
127 |
128 | | Property |
129 | Description |
130 |
131 |
132 | | Name |
133 | Specifies the name of the PowerShell module to be installed or uninstalled. |
134 |
135 |
136 | | Ensure |
137 | Determines whether the module to be installed or uninstalled. |
138 |
139 |
140 | | InstallationPolicy |
141 | Determines whether you trust the source repository where the module resides. |
142 |
143 |
144 | | RequiredVersion |
145 | Specifies the exact version of the module you want to install or uninstall. |
146 |
147 |
148 | | MinimumVersion |
149 | Specifies the minimum version of the module you want to install or uninstall. |
150 |
151 |
152 | | Repository |
153 | Specifies the name of the module source repository where the module can found. |
154 |
155 |
156 |
157 | **PackageManagementSource** has the following properties:
158 |
159 |
160 |
161 | | Property |
162 | Description |
163 |
164 |
165 | | Name |
166 | Specifies the name of the package source to be registered or unregistered on your system. |
167 |
168 |
169 | | ProviderName |
170 | Specifies the name of the OneGet provider through which you can interop with the package source. |
171 |
172 |
173 | | Ensure |
174 | Determines whether the package source is to be registered or unregistered. |
175 |
176 |
177 | | InstallationPolicy |
178 | Determines whether you trust the package source. |
179 |
180 |
181 | | SourceUri |
182 | Specifies the URI of the package source. |
183 |
184 |
185 | | SourceCredential |
186 | Provides access to the package on a remote source. |
187 |
188 |
189 |
190 | ####**Requirements**####
191 |
192 | Before you install this package, you must be running [Windows Management Framework 5.0 RTM(https://www.microsoft.com/en-us/download/details.aspx?id=50395).
193 |
194 |
195 | ####**Installation**####
196 |
197 | To use the **PackageManagementProviderResource** module,
198 | * Copy the content of the download to the $env:ProgramFiles\WindowsPowerShell\Modules folder.
199 |
200 | To confirm installation,
201 | * Run **Get-DSCResource** to verify that PackageManagement, NugetPackage, PackageManagementSource and PSModule are among the DSC Resources listed in your DSC resources.
202 |
203 |
204 | ####**Building the Code**####
205 |
206 | The code is a Windows PowerShell script and interpreted by the Windows PowerShell engine at runtime.
207 |
208 |
209 | ####**Running Test**####
210 |
211 | To test the modules, run the following commands. The NuGetPackage resource is used here as an example.
212 | * cd $env:ProgramFiles\WindowsPowerShell\Modules\PackageManagementProviderResource\Test
213 | * .\NugetPackage\NugetPackage.Get.Tests.ps1
214 | * .\NugetPackage\NugetPackage.Set.Tests.ps1
215 | * .\NugetPackage\NugetPackage.Test.Tests.ps1
216 |
217 | You can repeat these commands similarly for testing PackageManagement, PSModule and PackageManagementSource DSC resources.
218 |
219 |
220 | ####**Contributing to the Code**####
221 |
222 | You are welcome to contribute to this project. There are many ways to contribute:
223 |
224 | 1. Submit a bug report via [Issues]( https://github.com/PowerShell/PackageManagementProviderResource/issues). For a guide to submitting good bug reports, please read [Painless Bug Tracking](http://www.joelonsoftware.com/articles/fog0000000029.html).
225 |
226 | 2. Verify fixes for bugs.
227 |
228 | 3. Submit your fixes for a bug. Before submitting, please make sure you have:
229 | - Performed code reviews of your own
230 | - Updated the test cases if needed
231 | - Run the test cases to ensure no feature breaks or test breaks
232 | - Added the test cases for new code
233 | 4. Submit a feature request.
234 | 5. Help answer questions in the discussions list.
235 | 6. Submit test cases.
236 | 7. Tell others about the project.
237 | 8. Tell the developers how much you appreciate the product!
238 |
239 | You might also read these two blog posts about contributing code: [Open Source Contribution Etiquette](http://tirania.org/blog/archive/2010/Dec-31.html) by Miguel de Icaza, and [Don’t “Push” Your Pull Requests](http://www.igvita.com/2011/12/19/dont-push-your-pull-requests/) by Ilya Grigorik.
240 |
241 | Before submitting a feature or substantial code contribution, please discuss it with the Windows PowerShell team via [Issues]( https://github.com/WindowsPowerShell/OneGetResource/issues), and ensure it follows the product roadmap. Note that all code submissions will be rigorously reviewed by the Windows PowerShell Team. Only those that meet a high bar for both quality and roadmap fit will be merged into the source.
242 |
243 | ####**Examples**####
244 |
245 | Samples are included in the Examples folder.
246 |
--------------------------------------------------------------------------------
/Test/NugetPackage/NugetPackage.Set.Tests.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (c) Microsoft Corporation.
3 | #
4 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10 | # THE SOFTWARE.
11 | #
12 | $CurrentDirectory = Split-Path -Parent $MyInvocation.MyCommand.Path
13 |
14 | . "$CurrentDirectory\..\OneGetTestHelper.ps1"
15 |
16 | #
17 | # Pre-Requisite: MyTestPackage.12.0.1.1, MyTestPackage.12.0.1, MyTestPackage.15.2.1 packages are available under the $LocalRepositoryPath.
18 | # It's been taken care of by SetupNugetTest
19 | #
20 |
21 | # Calling the setup function
22 | SetupNugetTest
23 |
24 | Describe -Name "NugetPackage Set-TargetResource Basic Test" -Tags "BVT" {
25 |
26 | BeforeEach {
27 |
28 | #Remove all left over files if exists
29 | Remove-Item "$($DestinationPath)" -Recurse -Force -ErrorAction SilentlyContinue
30 |
31 | }
32 |
33 | AfterEach {
34 |
35 | }
36 |
37 | Context "NugetPackage Set-TargetResource Basic Test" {
38 |
39 |
40 | It "Set-TargetResource with RequiredVersion: Check Installed & UnInstalled" {
41 |
42 | RegisterPackageSource -Name "NugetTestSourceName" -InstallationPolicy Trusted -Ensure Present -SourceUri $LocalRepositoryPath
43 |
44 | $result = MSFT_NugetPackage\Set-TargetResource -Name "MyTestPackage" `
45 | -DestinationPath $DestinationPath `
46 | -RequiredVersion "12.0.1" `
47 | -Ensure Present
48 |
49 | # Validate the package is installed
50 | Test-Path -Path "$($DestinationPath)\MyTestPackage.12.0.1" | should be $true
51 |
52 |
53 | # Calling Set-TargetResource in the NugetPackage resource to uninstall it
54 | $result = MSFT_NugetPackage\Set-TargetResource -Name "MyTestPackage" `
55 | -DestinationPath $DestinationPath `
56 | -RequiredVersion "12.0.1" `
57 | -Ensure Absent
58 |
59 | # Package should not be there
60 | Test-Path -Path "$($DestinationPath)\MyTestPackage.12.0.1" | should be $false
61 | }
62 |
63 | It "Set-TargetResource with Trusted Source, No Versions Specified: Check Installed" {
64 |
65 | # Calling Set-TargetResource in the NugetPackage resource with trusted policy
66 |
67 | RegisterPackageSource -Name "NugetTestSourceName" -InstallationPolicy Trusted -Ensure Present -SourceUri $LocalRepositoryPath
68 |
69 | # User's installation policy is untrusted by default
70 | $result = MSFT_NugetPackage\Set-TargetResource -Name "MyTestPackage" -DestinationPath $DestinationPath -Source "NugetTestSourceName"
71 |
72 | # Validate the package is installed. 15.2.1 is the latest in the local source
73 |
74 | Test-Path -Path "$($DestinationPath)\MyTestPackage.15.2.1" | should be $true
75 | }
76 |
77 |
78 |
79 | It "Set-TargetResource with untrusted Source and trusted user policy: Check Warning & Installed" {
80 |
81 | # Calling Set-TargetResource in the NugetPackage resource with untrusted policy
82 |
83 | RegisterPackageSource -Name "NugetTestSourceName" -Ensure Present -SourceUri $LocalRepositoryPath
84 |
85 | # User's installation policy is trusted
86 | $result = MSFT_NugetPackage\Set-TargetResource -Name "MyTestPackage" `
87 | -DestinationPath $DestinationPath `
88 | -Source "NugetTestSourceName" `
89 | -InstallationPolicy Trusted `
90 | -WarningVariable wv
91 |
92 |
93 | if ($wv)
94 | {
95 | # Check the warning message
96 | $wv -imatch "untrusted repository"
97 |
98 | # The package should be installed
99 | $result = MSFT_NugetPackage\Test-TargetResource -name "MyTestPackage" -DestinationPath $DestinationPath -Ensure "Present" -Source "NugetTestSourceName"
100 |
101 | $result| should be $true
102 |
103 | return
104 | }
105 |
106 | Throw "Expecting InstallationPolicyWarning but not happen"
107 |
108 | }
109 |
110 |
111 | It "Set-TargetResource with mulitple sources containing the same package: Check Installed" {
112 |
113 | try
114 | {
115 | # registering multiple source
116 | RegisterPackageSource -Name "NugetTestSourceName10" -Ensure Present -SourceUri $LocalRepositoryPath
117 | RegisterPackageSource -Name "NugetTestSourceName20" -Ensure Present -SourceUri $LocalRepositoryPath -InstallationPolicy Trusted
118 | RegisterPackageSource -Name "NugetTestSourceName30" -Ensure Present -SourceUri $LocalRepositoryPath
119 |
120 | # User's installation policy is untrusted
121 | $result = MSFT_NugetPackage\Set-TargetResource -Name "MyTestPackage" -DestinationPath $DestinationPath
122 |
123 | # The package should be installed
124 | MSFT_NugetPackage\Test-TargetResource -Name "MyTestPackage" -DestinationPath $destinationPath -Source "NugetTestSourceName20" | should be $true
125 | }
126 | finally
127 | {
128 | #unregister them
129 | RegisterPackageSource -Name "NugetTestSourceName10" -Ensure Absent -SourceUri $LocalRepositoryPath
130 | RegisterPackageSource -Name "NugetTestSourceName20" -Ensure Absent -SourceUri $LocalRepositoryPath -InstallationPolicy Trusted
131 | RegisterPackageSource -Name "NugetTestSourceName30" -Ensure Absent -SourceUri $LocalRepositoryPath
132 | }
133 |
134 | }
135 |
136 | It "Set-TargetResource with SourceCredential: Check Installed" {
137 |
138 | $credential = (CreateCredObject -Name ".\Administrator" -PSCode "MassRules!")
139 |
140 | # Calling Set-TargetResource in the NugetPackage resource with SourceCredential
141 | $result = MSFT_NugetPackage\Set-TargetResource -Name "MyTestPackage" `
142 | -DestinationPath $DestinationPath `
143 | -Source $LocalRepositoryPath `
144 | -SourceCredential $credential `
145 | -InstallationPolicy Trusted
146 |
147 | # Validate the package is installed
148 | MSFT_NugetPackage\Test-TargetResource -Name "MyTestPackage" -DestinationPath $destinationPath -Source "NugetTestSourceName" | should be $true
149 | }
150 |
151 | }#context
152 |
153 | }#Describe
154 |
155 | Describe -Name "NugetPackage Set-TargetResource Error Cases" -Tags "RI" {
156 |
157 | BeforeEach {
158 |
159 | #Remove all left over files if exists
160 | Remove-Item "$($DestinationPath)" -Recurse -Force -ErrorAction SilentlyContinue
161 |
162 | RegisterPackageSource -Name "NugetTestSourceName" -Ensure Present -SourceUri $LocalRepositoryPath -InstallationPolicy Trusted
163 | }
164 |
165 | AfterEach {
166 | RegisterPackageSource -Name "NugetTestSourceName" -Ensure Absent -SourceUri $LocalRepositoryPath
167 | }
168 |
169 |
170 | Context "NugetPackage Set-TargetResource Error Cases" {
171 |
172 | It "Set-TargetResource with package not found for the install: Check Error" {
173 |
174 | #every slow need mock
175 | try
176 | {
177 | # None-exist package for install
178 | $result = MSFT_NugetPackage\Set-TargetResource -Name "MyTestPackageyyyy" -DestinationPath $DestinationPath -Ensure Present -ErrorAction SilentlyContinue
179 |
180 | }
181 | Catch
182 | {
183 | #Expect fail to install.
184 | $_.FullyQualifiedErrorId | should be "PackageNotFoundInRepository"
185 | return
186 | }
187 |
188 | Throw "Expecting PackageNotFoundInRepository but not happen"
189 | }
190 |
191 |
192 | It "Set-TargetResource with package not found for the uninstall: Check Error" {
193 |
194 | # Create a folder that is mimicking the package is installed
195 | if (-not (Test-Path -Path $DestinationPath))
196 | {
197 | New-Item -Path $DestinationPath
198 | }
199 |
200 | try
201 | {
202 | # None-exist package for uninstall
203 | $result = MSFT_NugetPackage\Set-TargetResource -Name "MyTestPackageyyyy" -DestinationPath $DestinationPath -Ensure Absent -ErrorAction SilentlyContinue
204 | }
205 | Catch
206 | {
207 | #Expect fail to install.
208 | $_.FullyQualifiedErrorId | should be "PackageNotFound"
209 | return
210 | }
211 |
212 | Throw "Expecting PackageNotFound but not happen"
213 | }
214 |
215 | It "Set-TargetResource with Untrusted User InstallationPolicy and Source: Check Error" {
216 |
217 | # No install will happen if both user and source are untrusted
218 |
219 | RegisterPackageSource -Name "NugetTestSourceName" -Ensure Present -SourceUri $LocalRepositoryPath
220 |
221 | Try
222 | {
223 | # User's installation policy is untrusted.
224 | $result = MSFT_NugetPackage\Set-TargetResource -Name "MyTestPackage" `
225 | -DestinationPath $DestinationPath `
226 | -Source "NugetTestSourceName" `
227 | -InstallationPolicy Untrusted `
228 | -ErrorVariable ev
229 |
230 | }
231 | Catch
232 | {
233 | #Expect fail to install.
234 | $_.FullyQualifiedErrorId | should be "InstallationPolicyFailed"
235 | return
236 | }
237 |
238 |
239 | Throw "Expecting InstallationPolicyFailed but not happen"
240 | }
241 |
242 | }#context
243 | }#Describe
244 |
--------------------------------------------------------------------------------
/Test/PSModule/PSModule.Set.and.Test.Tests.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (c) Microsoft Corporation.
3 | #
4 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10 | # THE SOFTWARE.
11 | #
12 |
13 | $CurrentDirectory = Split-Path -Parent $MyInvocation.MyCommand.Path
14 |
15 | . "$CurrentDirectory\..\OneGetTestHelper.ps1"
16 |
17 | #
18 | # Pre-Requisite: MyTestModule 1.1, 1.1.2, 3.2.1 modules are available under the $LocalRepositoryPath for testing purpose only.
19 | # It's been taken care of by SetupPSModuleTest
20 | #
21 |
22 | #Calling the setup function
23 | SetupPSModuleTest
24 |
25 | # We will be focusing on the tests around installation policy, versions, and multiple repositories, as we have covered basics in the get tests already.
26 | Describe -Name "PSModule Set, Test-TargetResource Basic Test" -Tags "BVT"{
27 |
28 | BeforeEach {
29 |
30 | #Remove all left over files if exists
31 | Remove-Item "$($script:InstallationFolder)\..\..\MyTestModule" -Recurse -Force -ErrorAction SilentlyContinue
32 | Remove-Item "$($script:InstallationFolder)\..\MyTestModule" -Recurse -Force -ErrorAction SilentlyContinue
33 | }
34 |
35 | AfterEach {
36 |
37 | }
38 |
39 | Context "PSModule Set, Test-TargetResource Basic Test" {
40 |
41 | It "Set, Test-TargetResource with Trusted Source, No Versions Specified: Check Installed" {
42 |
43 | #Register a local module repository to make the test run faster
44 | RegisterRepository -Name "LocalRepository" -InstallationPolicy Trusted -Ensure Present
45 |
46 | # 'BeforeEach' removes all specific modules under the $module path, so it is expected Set-Target* should success in the installation
47 | MSFT_PSModule\Set-TargetResource -name "MyTestModule" -Repository $LocalRepository -Ensure Present -Verbose
48 |
49 | # Validate the module is installed
50 | $result = MSFT_PSModule\Test-TargetResource -name "MyTestModule" -Repository $LocalRepository -Ensure Present
51 |
52 | $result| should be $true
53 |
54 | # Uninstalling the module
55 | MSFT_PSModule\Set-TargetResource -name "MyTestModule" -Repository $LocalRepository -Ensure Absent -Verbose
56 |
57 | # Validate the module is uninstalled
58 | $result = MSFT_PSModule\Test-TargetResource -name "MyTestModule" -Repository $LocalRepository -Ensure Absent
59 |
60 | $result| should be $true
61 | }
62 |
63 | It "Set, Test-TargetResource with Trusted Source, No respository Specified: Check Installed" {
64 |
65 | #Register a local module repository to make the test run faster
66 | RegisterRepository -Name "LocalRepository" -InstallationPolicy Trusted -Ensure Present
67 |
68 | # 'BeforeEach' removes all specific modules under the $module path, so it is expected Set-Target* should success in the installation
69 | MSFT_PSModule\Set-TargetResource -name "MyTestModule" -Ensure Present -Verbose
70 |
71 | # Validate the module is installed
72 | $result = MSFT_PSModule\Test-TargetResource -name "MyTestModule" -Ensure Present
73 |
74 | $result| should be $true
75 |
76 | # Uninstalling the module
77 | MSFT_PSModule\Set-TargetResource -name "MyTestModule" -Ensure Absent -Verbose
78 |
79 | # Validate the module is uninstalled
80 | $result = MSFT_PSModule\Test-TargetResource -name "MyTestModule" -Ensure Absent
81 |
82 | $result| should be $true
83 | }
84 |
85 | It "Set, Test-TargetResource with untrusted source and trusted user policy: Check Warning" {
86 |
87 | # Registering repository with untrusted installation policy
88 | RegisterRepository -Name "LocalRepository" -InstallationPolicy Untrusted -Ensure Present
89 |
90 |
91 | # User's installation policy is trusted
92 | $result = MSFT_PSModule\Set-TargetResource -Name "MyTestModule" `
93 | -Repository $LocalRepository `
94 | -InstallationPolicy Trusted `
95 | -WarningVariable wv
96 |
97 | if ($wv)
98 | {
99 | # Check the warning message
100 | $wv -imatch "untrusted repository"
101 |
102 | # The module should be installed
103 | $result = MSFT_PSModule\Test-TargetResource -name "MyTestModule" -Repository $LocalRepository -Ensure "Present"
104 |
105 | $result| should be $true
106 |
107 | MSFT_PSModule\Set-TargetResource -name "MyTestModule" -Ensure Absent -Verbose -Repository $LocalRepository
108 | $result1 = MSFT_PSModule\Test-TargetResource -name "MyTestModule" -Repository $LocalRepository -Ensure Absent
109 | $result1 | should be $true
110 |
111 | return
112 | }
113 |
114 | Throw "Expecting InstallationPolicyWarning but not happen"
115 | }
116 |
117 |
118 | It "Set, Test-TargetResource with multiple sources and versions of a modules: Check Installed" {
119 |
120 | # Registering multiple source
121 |
122 | $returnVal = $null
123 |
124 | try
125 | {
126 | $returnVal = CleanupRepository
127 |
128 | RegisterRepository -Name "LocalRepository1" -InstallationPolicy Untrusted -Ensure Present -SourceLocation $LocalRepositoryPath1 -PublishLocation $LocalRepositoryPath1
129 |
130 | RegisterRepository -Name "LocalRepository2" -InstallationPolicy Trusted -Ensure Present -SourceLocation $LocalRepositoryPath2 -PublishLocation $LocalRepositoryPath2
131 |
132 | RegisterRepository -Name "LocalRepository3" -InstallationPolicy Untrusted -Ensure Present -SourceLocation $LocalRepositoryPath3 -PublishLocation $LocalRepositoryPath3
133 |
134 | $result1 = MSFT_PSModule\Test-TargetResource -name "MyTestModule" -Repository "LocalRepository2" -Ensure "Present" -Verbose
135 |
136 | $result1 | should be $false
137 |
138 | # User's installation policy is untrusted
139 | MSFT_PSModule\Set-TargetResource -name "MyTestModule" -Ensure "Present" -Verbose -Repository "LocalRepository2"
140 |
141 | # The module from the trusted source should be installed
142 | $result = MSFT_PSModule\Test-TargetResource -name "MyTestModule" -Repository "LocalRepository2" -Ensure "Present" -Verbose
143 |
144 | $result| should be $true
145 | }
146 | finally
147 | {
148 | RestoreRepository -RepositoryInfo $returnVal
149 | # Unregistering the repository sources
150 |
151 | RegisterRepository -Name "LocalRepository1" -Ensure Absent -SourceLocation $LocalRepositoryPath1 -PublishLocation $LocalRepositoryPath1
152 |
153 | RegisterRepository -Name "LocalRepository2" -Ensure Absent -SourceLocation $LocalRepositoryPath2 -PublishLocation $LocalRepositoryPath2
154 |
155 | RegisterRepository -Name "LocalRepository3" -Ensure Absent -SourceLocation $LocalRepositoryPath3 -PublishLocation $LocalRepositoryPath3
156 | }
157 | }
158 |
159 |
160 | }#context
161 |
162 | Context "PSModule Set-TargetResource Error Cases" {
163 |
164 | #Register a local module repository to make the test run faster
165 | RegisterRepository -Name "LocalRepository" -InstallationPolicy Trusted -Ensure Present
166 |
167 | It "Set-TargetResource with module not found for the install: Check Error" {
168 |
169 | try
170 | {
171 | # The module does not exist
172 | MSFT_PSModule\Set-TargetResource -name "NonExistModule" -Ensure Present -ErrorAction SilentlyContinue 2>&1
173 | }
174 | catch
175 | {
176 | #Expect fail to install.
177 | $_.FullyQualifiedErrorId | should be "ModuleNotFoundInRepository"
178 | return
179 | }
180 |
181 | Throw "Expected 'ModuleNotFoundInRepository' exception did not happen"
182 | }
183 |
184 | # In the reality the following case won't happen because LCM always call Test-TargetResource first before calling Set
185 | It "Set-TargetResource with module not found for the uninstall: Check Error" {
186 |
187 | try
188 | {
189 | # The module does not exist
190 | $result = MSFT_PSModule\Set-TargetResource -Name "NonExistModule" -Ensure Absent -Verbose -ErrorAction SilentlyContinue
191 | }
192 | Catch
193 | {
194 | #Expect an expection
195 | $_.FullyQualifiedErrorId | should be "ModuleWithRightPropertyNotFound"
196 | return
197 | }
198 |
199 | Throw "Expected 'ModuleWithRightPropertyNotFound' exception did not happen"
200 | }
201 |
202 |
203 | It "Set , Test-TargetResource: Check Absent and False" {
204 |
205 | # Calling Set-TargetResource to uninstall the MyTestModule module
206 | try
207 | {
208 | Set-TargetResource -name "MyTestModule" -Repository $LocalRepository -RequiredVersion "1.1.2" -Ensure "Absent" -Verbose
209 | }
210 | catch
211 | {
212 | if ($_.FullyQualifiedErrorId -ieq "ModuleWithRightPropertyNotFound")
213 | {
214 | #The module is not installed. Ignore the error
215 | }
216 | else
217 | {
218 | throw
219 | }
220 | }
221 |
222 | # Calling Get-TargetResource in the PSModule resource
223 | $result = MSFT_PSModule\Test-TargetResource -Name "MyTestModule" -Repository $LocalRepository -RequiredVersion "1.1.2"
224 |
225 | # Validate the result
226 | $result | should be $false
227 |
228 | }
229 |
230 | # Both the user's and repository installation policies are untrusted, expect an error
231 | It "Set-TargetResource with Untrusted User InstallationPolicy and Source: Check Error" {
232 |
233 | # Register a repository with the untrusted policy
234 |
235 | RegisterRepository -Name "LocalRepository1" -InstallationPolicy Untrusted -Ensure Present -SourceLocation $LocalRepositoryPath1 -PublishLocation $LocalRepositoryPath1
236 |
237 |
238 | Try
239 | {
240 | # User's installation policy is untrusted.
241 | $result = MSFT_PSModule\Set-TargetResource -Name "MyTestModule" -Repository "LocalRepository1" -InstallationPolicy Untrusted
242 | }
243 | Catch
244 | {
245 | #Expect fail to install.
246 | $_.FullyQualifiedErrorId | should be "InstallationPolicyFailed"
247 | return
248 | }
249 | finally
250 | {
251 | RegisterRepository -Name "LocalRepository1" -Ensure Absent -SourceLocation $LocalRepositoryPath1 -PublishLocation $LocalRepositoryPath1
252 | }
253 |
254 | Throw "Expected 'InstallationPolicyFailed' exception did not happen"
255 | }
256 |
257 | }#context
258 |
259 | }#Describe
260 |
261 |
262 |
263 |
--------------------------------------------------------------------------------
/DSCResources/MSFT_PackageManagement/MSFT_PackageManagement.psm1:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (c) Microsoft Corporation.
3 | #
4 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10 | # THE SOFTWARE.
11 | #
12 | # This PS DSC resource enables installing a package. The resource uses Install-Package cmdlet
13 | # to install the package from various providers/sources.
14 |
15 | Import-LocalizedData -BindingVariable LocalizedData -filename MSFT_PackageManagement.strings.psd1
16 |
17 | Import-Module -Name "$PSScriptRoot\..\OneGetHelper.psm1"
18 |
19 | function Get-TargetResource
20 | {
21 | <#
22 | .SYNOPSIS
23 |
24 | This DSC resource provides a mechanism to download and install packages on a computer.
25 |
26 | Get-TargetResource returns the current state of the resource.
27 |
28 | .PARAMETER Name
29 | Specifies the name of the Package to be installed or uninstalled.
30 |
31 | .PARAMETER Source
32 | Specifies the name of the package source where the package can be found.
33 | This can either be a URI or a source registered with Register-PackageSource cmdlet.
34 | The DSC resource MSFT_PackageManagementSource can also register a package source.
35 |
36 | .PARAMETER RequiredVersion
37 | Specifies the exact version of the package that you want to install. If you do not specify this parameter,
38 | this DSC resource installs the newest available version of the package that also satisfies any
39 | maximum version specified by the MaximumVersion parameter.
40 |
41 | .PARAMETER MaximumVersion
42 | Specifies the maximum allowed version of the package that you want to install. If you do not specify this parameter,
43 | this DSC resource installs the highest-numbered available version of the package.
44 |
45 | .PARAMETER MinimumVersion
46 | Specifies the minimum allowed version of the package that you want to install. If you do not add this parameter,
47 | this DSC resource intalls the highest available version of the package that also satisfies any maximum
48 | specified version specified by the MaximumVersion parameter.
49 |
50 | .PARAMETER SourceCredential
51 | Specifies a user account that has rights to install a package for a specified package provider or source.
52 |
53 | .PARAMETER ProviderName
54 | Specifies a package provider name to which to scope your package search. You can get package provider names
55 | by running the Get-PackageProvider cmdlet.
56 |
57 | .PARAMETER AdditionalParameters
58 | Provider specific parameters that are passed as an Hashtable. For example, for NuGet provider you can
59 | pass additional parameters like DestinationPath.
60 | #>
61 |
62 | [CmdletBinding()]
63 | [OutputType([System.Collections.Hashtable])]
64 | param
65 | (
66 | [Parameter(Mandatory = $true)]
67 | [System.String]
68 | $Name,
69 |
70 | [Parameter()]
71 | [System.String]
72 | $RequiredVersion,
73 |
74 | [Parameter()]
75 | [System.String]
76 | $MinimumVersion,
77 |
78 | [Parameter()]
79 | [System.String]
80 | $MaximumVersion,
81 |
82 | [Parameter()]
83 | [System.String]
84 | $Source,
85 |
86 | [Parameter()]
87 | [PSCredential] $SourceCredential,
88 |
89 | [Parameter()]
90 | [System.String]
91 | $ProviderName,
92 |
93 | [Parameter()]
94 | [Microsoft.Management.Infrastructure.CimInstance[]]$AdditionalParameters
95 | )
96 |
97 | $ensure = "Absent"
98 | $null = $PSBoundParameters.Remove("Source")
99 | $null = $PSBoundParameters.Remove("SourceCredential")
100 |
101 | if ($AdditionalParameters)
102 | {
103 | foreach($instance in $AdditionalParameters)
104 | {
105 | Write-Verbose ('AdditionalParameter: {0}, AdditionalParameterValue: {1}' -f $instance.Key, $instance.Value)
106 | $null = $PSBoundParameters.Add($instance.Key, $instance.Value)
107 | }
108 | }
109 | $null = $PSBoundParameters.Remove("AdditionalParameters")
110 |
111 | $verboseMessage =$localizedData.StartGetPackage -f (GetMessageFromParameterDictionary $PSBoundParameters),$env:PSModulePath
112 | Write-Verbose -Message $verboseMessage
113 | $result = PackageManagement\Get-Package @PSBoundParameters -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
114 |
115 |
116 | if ($result.count -eq 1)
117 | {
118 | Write-Verbose -Message ($localizedData.PackageFound -f $Name)
119 | $ensure = "Present"
120 | }
121 | elseif ($result.count -gt 1)
122 | {
123 | Write-Verbose -Message ($localizedData.MultiplePackagesFound -f $Name)
124 | $ensure = "Present"
125 | }
126 | else
127 | {
128 | Write-Verbose -Message ($localizedData.PackageNotFound -f $($Name))
129 | }
130 |
131 | Write-Debug -Message "Source $($Name) is $($ensure)"
132 |
133 |
134 | if ($ensure -eq 'Absent')
135 | {
136 | return @{
137 | Ensure = $ensure
138 | Name = $Name
139 | ProviderName = $ProviderName
140 | RequiredVersion = $RequiredVersion
141 | MinimumVersion = $MinimumVersion
142 | MaximumVersion = $MaximumVersion
143 | }
144 | }
145 | else
146 | {
147 | if ($result.Count -gt 1)
148 | {
149 | $result = $result[0]
150 | }
151 |
152 | return @{
153 | Ensure = $ensure
154 | Name = $result.Name
155 | ProviderName = $result.ProviderName
156 | Source = $result.source
157 | RequiredVersion = $result.Version
158 | }
159 | }
160 | }
161 |
162 | function Test-TargetResource
163 | {
164 | <#
165 | .SYNOPSIS
166 |
167 | This DSC resource provides a mechanism to download and install packages on a computer.
168 |
169 | Test-TargetResource returns a boolean which determines whether the resource is in
170 | desired state or not.
171 |
172 | .PARAMETER Name
173 | Specifies the name of the Package to be installed or uninstalled.
174 |
175 | .PARAMETER Source
176 | Specifies the name of the package source where the package can be found.
177 | This can either be a URI or a source registered with Register-PackageSource cmdlet.
178 | The DSC resource MSFT_PackageManagementSource can also register a package source.
179 |
180 | .PARAMETER RequiredVersion
181 | Specifies the exact version of the package that you want to install. If you do not specify this parameter,
182 | this DSC resource installs the newest available version of the package that also satisfies any
183 | maximum version specified by the MaximumVersion parameter.
184 |
185 | .PARAMETER MaximumVersion
186 | Specifies the maximum allowed version of the package that you want to install. If you do not specify this parameter,
187 | this DSC resource installs the highest-numbered available version of the package.
188 |
189 | .PARAMETER MinimumVersion
190 | Specifies the minimum allowed version of the package that you want to install. If you do not add this parameter,
191 | this DSC resource intalls the highest available version of the package that also satisfies any maximum
192 | specified version specified by the MaximumVersion parameter.
193 |
194 | .PARAMETER SourceCredential
195 | Specifies a user account that has rights to install a package for a specified package provider or source.
196 |
197 | .PARAMETER ProviderName
198 | Specifies a package provider name to which to scope your package search. You can get package provider names
199 | by running the Get-PackageProvider cmdlet.
200 |
201 | .PARAMETER AdditionalParameters
202 | Provider specific parameters that are passed as an Hashtable. For example, for NuGet provider you can
203 | pass additional parameters like DestinationPath.
204 | #>
205 |
206 | [CmdletBinding()]
207 | [OutputType([bool])]
208 | param
209 | (
210 | [Parameter(Mandatory = $true)]
211 | [System.String]
212 | $Name,
213 |
214 | [Parameter()]
215 | [System.String]
216 | $RequiredVersion,
217 |
218 | [Parameter()]
219 | [System.String]
220 | $MinimumVersion,
221 |
222 | [Parameter()]
223 | [System.String]
224 | $MaximumVersion,
225 |
226 | [Parameter()]
227 | [System.String]
228 | $Source,
229 |
230 | [Parameter()]
231 | [PSCredential] $SourceCredential,
232 |
233 | [ValidateSet("Present","Absent")]
234 | [System.String]
235 | $Ensure="Present",
236 |
237 | [Parameter()]
238 | [System.String]
239 | $ProviderName,
240 |
241 | [Parameter()]
242 | [Microsoft.Management.Infrastructure.CimInstance[]]$AdditionalParameters
243 | )
244 |
245 |
246 | Write-Verbose -Message ($localizedData.StartTestPackage -f (GetMessageFromParameterDictionary $PSBoundParameters))
247 | $null = $PSBoundParameters.Remove("Ensure")
248 |
249 | $temp = Get-TargetResource @PSBoundParameters
250 |
251 | if ($temp.Ensure -eq $ensure)
252 | {
253 | Write-Verbose -Message ($localizedData.InDesiredState -f $Name, $Ensure, $temp.Ensure)
254 | return $True
255 | }
256 | else
257 | {
258 | Write-Verbose -Message ($localizedData.NotInDesiredState -f $Name,$ensure,$temp.ensure)
259 | return [bool] $False
260 | }
261 | }
262 |
263 | function Set-TargetResource
264 | {
265 | <#
266 | .SYNOPSIS
267 |
268 | This DSC resource provides a mechanism to download and install packages on a computer.
269 |
270 | Set-TargetResource either intalls or uninstall a package as defined by the vaule of Ensure parameter.
271 |
272 | .PARAMETER Name
273 | Specifies the name of the Package to be installed or uninstalled.
274 |
275 | .PARAMETER Source
276 | Specifies the name of the package source where the package can be found.
277 | This can either be a URI or a source registered with Register-PackageSource cmdlet.
278 | The DSC resource MSFT_PackageManagementSource can also register a package source.
279 |
280 | .PARAMETER RequiredVersion
281 | Specifies the exact version of the package that you want to install. If you do not specify this parameter,
282 | this DSC resource installs the newest available version of the package that also satisfies any
283 | maximum version specified by the MaximumVersion parameter.
284 |
285 | .PARAMETER MaximumVersion
286 | Specifies the maximum allowed version of the package that you want to install. If you do not specify this parameter,
287 | this DSC resource installs the highest-numbered available version of the package.
288 |
289 | .PARAMETER MinimumVersion
290 | Specifies the minimum allowed version of the package that you want to install. If you do not add this parameter,
291 | this DSC resource intalls the highest available version of the package that also satisfies any maximum
292 | specified version specified by the MaximumVersion parameter.
293 |
294 | .PARAMETER SourceCredential
295 | Specifies a user account that has rights to install a package for a specified package provider or source.
296 |
297 | .PARAMETER ProviderName
298 | Specifies a package provider name to which to scope your package search. You can get package provider names
299 | by running the Get-PackageProvider cmdlet.
300 |
301 | .PARAMETER AdditionalParameters
302 | Provider specific parameters that are passed as an Hashtable. For example, for NuGet provider you can
303 | pass additional parameters like DestinationPath.
304 | #>
305 |
306 | [CmdletBinding()]
307 | param
308 | (
309 | [Parameter(Mandatory = $true)]
310 | [System.String]
311 | $Name,
312 |
313 | [Parameter()]
314 | [System.String]
315 | $RequiredVersion,
316 |
317 | [Parameter()]
318 | [System.String]
319 | $MinimumVersion,
320 |
321 | [Parameter()]
322 | [System.String]
323 | $MaximumVersion,
324 |
325 | [Parameter()]
326 | [System.String]
327 | $Source,
328 |
329 | [Parameter()]
330 | [PSCredential] $SourceCredential,
331 |
332 | [ValidateSet("Present","Absent")]
333 | [System.String]
334 | $Ensure="Present",
335 |
336 | [Parameter()]
337 | [System.String]
338 | $ProviderName,
339 |
340 | [Parameter()]
341 | [Microsoft.Management.Infrastructure.CimInstance[]]$AdditionalParameters
342 | )
343 |
344 | Write-Verbose -Message ($localizedData.StartSetPackage -f (GetMessageFromParameterDictionary $PSBoundParameters))
345 |
346 | $null = $PSBoundParameters.Remove("Ensure")
347 |
348 | if ($AdditionalParameters)
349 | {
350 | foreach($instance in $AdditionalParameters)
351 | {
352 | Write-Verbose ('AdditionalParameter: {0}, AdditionalParameterValue: {1}' -f $instance.Key, $instance.Value)
353 | $null = $PSBoundParameters.Add($instance.Key, $instance.Value)
354 | }
355 | }
356 |
357 | $PSBoundParameters.Remove("AdditionalParameters")
358 |
359 |
360 | # We do not want others to control the behavior of ErrorAction
361 | # while calling Install-Package/Uninstall-Package.
362 | $PSBoundParameters.Remove("ErrorAction")
363 | if ($Ensure -eq "Present")
364 | {
365 | PackageManagement\Install-Package @PSBoundParameters -ErrorAction Stop
366 | }
367 | else
368 | {
369 | # we dont source location for uninstalling an already
370 | # installed package
371 | $PSBoundParameters.Remove("Source")
372 | # Ensure is Absent
373 | PackageManagement\Uninstall-Package @PSBoundParameters -ErrorAction Stop
374 | }
375 | }
376 |
377 | function GetMessageFromParameterDictionary
378 | {
379 | <#
380 | Returns a strng of form "ParameterName:ParameterValue"
381 | Used with Write-Verbose message. The input is mostly $PSBoundParameters
382 | #>
383 | param([System.Collections.IDictionary] $paramDictionary)
384 |
385 | $returnValue = ""
386 | $paramDictionary.Keys | % { $returnValue += "-{0} {1} " -f $_,$paramDictionary[$_] }
387 | return $returnValue
388 | }
389 |
390 | Export-ModuleMember -function Get-TargetResource, Set-TargetResource, Test-TargetResource
391 |
392 |
--------------------------------------------------------------------------------
/DSCResources/MSFT_PSModule/MSFT_PSModule.psm1:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (c) Microsoft Corporation.
3 | #
4 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10 | # THE SOFTWARE.
11 | #
12 |
13 | Import-LocalizedData -BindingVariable LocalizedData -filename MSFT_PSModule.strings.psd1
14 | Import-Module -Name "$PSScriptRoot\..\OneGetHelper.psm1"
15 |
16 | #DSC Resource for the $CurrentProviderName
17 | $CurrentProviderName="PowerShellGet"
18 |
19 |
20 | #Return the current state of the resource
21 | function Get-TargetResource
22 | {
23 | <#
24 | .SYNOPSIS
25 |
26 | This DSC resource provides a mechanism to download PowerShell modules from the PowerShell
27 | Gallery and install it on your computer.
28 |
29 | Get-TargetResource returns the current state of the resource.
30 |
31 | .PARAMETER Name
32 | Specifies the name of the PowerShell module to be installed or uninstalled.
33 |
34 | .PARAMETER Repository
35 | Specifies the name of the module source repository where the module can be found.
36 |
37 | .PARAMETER RequiredVersion
38 | Provides the version of the module you want to install or uninstall.
39 |
40 | .PARAMETER MaximumVersion
41 | Provides the maximum version of the module you want to install or uninstall.
42 |
43 | .PARAMETER MinimumVersion
44 | Provides the minimum version of the module you want to install or uninstall.
45 | #>
46 |
47 | [CmdletBinding()]
48 | [OutputType([System.Collections.Hashtable])]
49 | param
50 | (
51 | [parameter(Mandatory = $true)]
52 | [System.String]
53 | $Name,
54 |
55 | [System.String]
56 | $Repository="PSGallery",
57 |
58 | [System.String]
59 | $RequiredVersion,
60 |
61 | [System.String]
62 | $MaximumVersion,
63 |
64 | [System.String]
65 | $MinimumVersion
66 | )
67 |
68 | #Initialize the $Ensure variable
69 | $ensure = 'Absent'
70 |
71 | $extractedArguments = ExtractArguments -FunctionBoundParameters $PSBoundParameters `
72 | -ArgumentNames ("Name", "Repository", "MinimumVersion", "MaximumVersion", "RequiredVersion")
73 |
74 | #Get the module with the right version and repository properties
75 | $modules = Get-RightModule @extractedArguments -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
76 |
77 | #If the module is found, the count > 0
78 | if ($modules.count -gt 0)
79 | {
80 | $ensure = 'Present'
81 |
82 | Write-Verbose -Message ($localizedData.ModuleFound -f $($Name))
83 | }
84 | else
85 | {
86 | Write-Verbose -Message ($localizedData.ModuleNotFound -f $($Name))
87 | }
88 |
89 | Write-Debug -Message "Ensure of $($Name) module is $($ensure)"
90 |
91 | if ($ensure -eq 'Absent')
92 | {
93 | return @{
94 | Ensure = $ensure
95 | Name = $Name
96 | }
97 | }
98 | else
99 | {
100 | #Find a module with the latest version and return its properties
101 | $latestModule = $modules[0]
102 |
103 | foreach ($module in $modules)
104 | {
105 | if ($module.Version -gt $latestModule.Version)
106 | {
107 | $latestModule = $module
108 | }
109 | }
110 |
111 | #Check if the repository matches
112 | $repositoryName = Get-ModuleRepositoryName -Module $latestModule -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
113 |
114 | $installationPolicy = Get-InstallationPolicy -RepositoryName $repositoryName -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
115 |
116 | return @{
117 | Ensure = $ensure
118 | Name = $Name
119 | Repository = $repositoryName
120 | Description = $latestModule.Description
121 | Guid = $latestModule.Guid
122 | ModuleBase = $latestModule.ModuleBase
123 | ModuleType = $latestModule.ModuleType
124 | Author = $latestModule.Author
125 | InstalledVersion = $latestModule.Version
126 | InstallationPolicy=if($installationPolicy) {"Trusted"}else{"Untrusted"}
127 | }
128 | }
129 | }
130 |
131 | function Test-TargetResource
132 | {
133 | <#
134 | .SYNOPSIS
135 |
136 | This DSC resource provides a mechanism to download PowerShell modules from the PowerShell
137 | Gallery and install it on your computer.
138 |
139 | Test-TargetResource validates whether the resource is currently in the desired state.
140 |
141 | .PARAMETER Ensure
142 | Determines whether the module to be installed or uninstalled.
143 |
144 | .PARAMETER Name
145 | Specifies the name of the PowerShell module to be installed or uninstalled.
146 |
147 | .PARAMETER Repository
148 | Specifies the name of the module source repository where the module can be found.
149 |
150 | .PARAMETER InstallationPolicy
151 | Determines whether you trust the source repository where the module resides.
152 |
153 | .PARAMETER RequiredVersion
154 | Provides the version of the module you want to install or uninstall.
155 |
156 | .PARAMETER MaximumVersion
157 | Provides the maximum version of the module you want to install or uninstall.
158 |
159 | .PARAMETER MinimumVersion
160 | Provides the minimum version of the module you want to install or uninstall.
161 | #>
162 | [CmdletBinding()]
163 | [OutputType([System.Boolean])]
164 | param
165 | (
166 | [ValidateSet("Present","Absent")]
167 | [System.String]
168 | $Ensure="Present",
169 |
170 | [parameter(Mandatory = $true)]
171 | [System.String]
172 | $Name,
173 |
174 | [System.String]
175 | $Repository="PSGallery",
176 |
177 | [ValidateSet("Trusted","Untrusted")]
178 | [System.String]
179 | $InstallationPolicy="Untrusted",
180 |
181 | [System.String]
182 | $RequiredVersion,
183 |
184 | [System.String]
185 | $MaximumVersion,
186 |
187 | [System.String]
188 | $MinimumVersion
189 | )
190 |
191 | Write-Debug -Message "Calling Test-TargetResource"
192 |
193 | $extractedArguments = ExtractArguments -FunctionBoundParameters $PSBoundParameters `
194 | -ArgumentNames ("Name", "Repository", "MinimumVersion", "MaximumVersion", "RequiredVersion")
195 |
196 | $status = Get-TargetResource @extractedArguments
197 |
198 | #The ensure returned from Get-TargetResource is not equal to the desired $Ensure
199 | #
200 | if ($status.Ensure -ieq $Ensure)
201 | {
202 | Write-Verbose -Message ($localizedData.InDesiredState -f $Name)
203 | return $true
204 | }
205 | else
206 | {
207 | Write-Verbose -Message ($localizedData.NotInDesiredState -f $Name)
208 | return $false
209 | }
210 | }
211 |
212 | function Set-TargetResource
213 | {
214 | <#
215 | .SYNOPSIS
216 |
217 | This DSC resource provides a mechanism to download PowerShell modules from the PowerShell
218 | Gallery and install it on your computer.
219 |
220 | Set-TargetResource sets the resource to the desired state. "Make it so".
221 |
222 | .PARAMETER Ensure
223 | Determines whether the module to be installed or uninstalled.
224 |
225 | .PARAMETER Name
226 | Specifies the name of the PowerShell module to be installed or uninstalled.
227 |
228 | .PARAMETER Repository
229 | Specifies the name of the module source repository where the module can be found.
230 |
231 | .PARAMETER InstallationPolicy
232 | Determines whether you trust the source repository where the module resides.
233 |
234 | .PARAMETER RequiredVersion
235 | Provides the version of the module you want to install or uninstall.
236 |
237 | .PARAMETER MaximumVersion
238 | Provides the maximum version of the module you want to install or uninstall.
239 |
240 | .PARAMETER MinimumVersion
241 | Provides the minimum version of the module you want to install or uninstall.
242 | #>
243 |
244 | [CmdletBinding()]
245 | param
246 | (
247 | [ValidateSet("Present","Absent")]
248 | [System.String]
249 | $Ensure="Present",
250 |
251 | [parameter(Mandatory = $true)]
252 | [System.String]
253 | $Name,
254 |
255 | [System.String]
256 | $Repository="PSGallery",
257 |
258 | [ValidateSet("Trusted","Untrusted")]
259 | [System.String]
260 | $InstallationPolicy="Untrusted",
261 |
262 | [System.String]
263 | $RequiredVersion,
264 |
265 | [System.String]
266 | $MaximumVersion,
267 |
268 | [System.String]
269 | $MinimumVersion
270 | )
271 |
272 |
273 | #Validate the repository argument
274 | if ($PSBoundParameters.ContainsKey("Repository"))
275 | {
276 | ValidateArgument -Argument $Repository -Type "PackageSource" -ProviderName $CurrentProviderName -Verbose
277 | }
278 |
279 | if($Ensure -ieq "Present")
280 | {
281 |
282 | #Version check
283 | $extractedArguments = ExtractArguments -FunctionBoundParameters $PSBoundParameters `
284 | -ArgumentNames ("MinimumVersion","MaximumVersion", "RequiredVersion")
285 |
286 | ValidateVersionArgument @extractedArguments
287 |
288 | $extractedArguments = ExtractArguments -FunctionBoundParameters $PSBoundParameters `
289 | -ArgumentNames ("Name","Repository", "MinimumVersion", "MaximumVersion","RequiredVersion")
290 |
291 | Write-Verbose -Message ($localizedData.StartFindmodule -f $($Name))
292 |
293 |
294 | $modules = PowerShellGet\Find-Module @extractedArguments -ErrorVariable ev
295 |
296 |
297 | if (-not $modules)
298 | {
299 |
300 | ThrowError -ExceptionName "System.InvalidOperationException" `
301 | -ExceptionMessage ($localizedData.ModuleNotFoundInRepository -f $Name, $ev.Exception) `
302 | -ErrorId "ModuleNotFoundInRepository" `
303 | -ErrorCategory InvalidOperation
304 | }
305 |
306 | $trusted = $null
307 | $moduleFound = $null
308 |
309 | foreach ($m in $modules)
310 | {
311 | #Check for the installation policy
312 | $trusted = Get-InstallationPolicy -RepositoryName $m.Repository -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
313 |
314 | #Stop the loop if found a trusted repository
315 | if ($trusted)
316 | {
317 | $moduleFound = $m
318 | break;
319 | }
320 | }
321 |
322 |
323 | #The respository is trusted, so we install it
324 | if ($trusted)
325 | {
326 | Write-Verbose -Message ($localizedData.StartInstallModule -f $Name, $moduleFound.Version.toString(), $moduleFound.Repository )
327 | $moduleFound | PowerShellGet\Install-Module -ErrorVariable ev
328 | }
329 | #The repository is untrusted but user's installation policy is trusted, so we install it with a warning
330 | elseif ($InstallationPolicy -ieq 'Trusted')
331 | {
332 | Write-Warning -Message ($localizedData.InstallationPolicyWarning -f $Name, $modules[0].Repository, $InstallationPolicy)
333 |
334 | #if all the repositories are untrusted, we choose the first one
335 | $modules[0] | PowerShellGet\Install-Module -Force -ErrorVariable ev
336 | }
337 | #Both user and repository is untrusted
338 | else
339 | {
340 | ThrowError -ExceptionName "System.InvalidOperationException" `
341 | -ExceptionMessage ($localizedData.InstallationPolicyFailed -f $InstallationPolicy, "Untrusted") `
342 | -ErrorId "InstallationPolicyFailed" `
343 | -ErrorCategory InvalidOperation
344 | }
345 |
346 | if ($ev)
347 | {
348 | ThrowError -ExceptionName "System.InvalidOperationException" `
349 | -ExceptionMessage ($localizedData.FailtoInstall -f $Name, $ev.Exception) `
350 | -ErrorId "FailtoInstall" `
351 | -ErrorCategory InvalidOperation
352 | }
353 | else
354 | {
355 | Write-Verbose -Message ($localizedData.InstalledSuccess -f $($Name))
356 | }
357 | }
358 | #Ensure=Absent
359 | else
360 | {
361 |
362 | $extractedArguments = ExtractArguments -FunctionBoundParameters $PSBoundParameters `
363 | -ArgumentNames ("Name", "Repository", "MinimumVersion", "MaximumVersion", "RequiredVersion")
364 |
365 |
366 | #Get the module with the right version and repository properties
367 | $modules = Get-RightModule @extractedArguments -ErrorVariable ev
368 |
369 | if ((-not $modules) -or $ev)
370 | {
371 | ThrowError -ExceptionName "System.InvalidOperationException" `
372 | -ExceptionMessage ($localizedData.ModuleWithRightPropertyNotFound -f $Name, $ev.Exception) `
373 | -ErrorId "ModuleWithRightPropertyNotFound" `
374 | -ErrorCategory InvalidOperation
375 | }
376 |
377 | foreach ($module in $modules)
378 | {
379 | #Get the path where the module is installed
380 | $path=$module.ModuleBase
381 |
382 | Write-Verbose -Message ($localizedData.StartUnInstallModule -f $($Name))
383 |
384 | #There is no Uninstall-Module cmdlet exists, so we will remove the ModuleBase folder as an uninstall operation
385 | Microsoft.PowerShell.Management\Remove-Item -Path $path -Force -Recurse -ErrorVariable ev
386 |
387 | if($ev)
388 | {
389 | ThrowError -ExceptionName "System.InvalidOperationException" `
390 | -ExceptionMessage ($localizedData.FailtoUninstall -f $module.Name, $ev.Exception) `
391 | -ErrorId "FailtoUninstall" `
392 | -ErrorCategory InvalidOperation
393 | }
394 | else
395 | {
396 | Write-Verbose -Message ($localizedData.UnInstalledSuccess -f $($module.Name))
397 | }
398 |
399 | }#foreach
400 |
401 | } #Ensure=Absent
402 | }
403 |
404 |
405 | Function Get-RightModule
406 | {
407 | <#
408 | .SYNOPSIS
409 |
410 | This is a helper function. It returns the modules that meet the specified versions and the repository requirements
411 |
412 | .PARAMETER Name
413 | Specifies the name of the PowerShell module.
414 |
415 | .PARAMETER RequiredVersion
416 | Provides the version of the module you want to install or uninstall.
417 |
418 | .PARAMETER MaximumVersion
419 | Provides the maximum version of the module you want to install or uninstall.
420 |
421 | .PARAMETER MinimumVersion
422 | Provides the minimum version of the module you want to install or uninstall.
423 |
424 | .PARAMETER Repository
425 | Specifies the name of the module source repository where the module can be found.
426 | #>
427 |
428 | param
429 | (
430 | [parameter(Mandatory = $true)]
431 | [ValidateNotNullOrEmpty()]
432 | [System.String]
433 | $Name,
434 |
435 | [System.String]
436 | $RequiredVersion,
437 |
438 | [System.String]
439 | $MinimumVersion,
440 |
441 | [System.String]
442 | $MaximumVersion,
443 |
444 | [System.String]
445 | $Repository
446 | )
447 |
448 |
449 | Write-Verbose -Message ($localizedData.StartGetModule -f $($Name))
450 |
451 | $modules = Microsoft.PowerShell.Core\Get-Module -Name $Name -ListAvailable -ErrorAction SilentlyContinue -WarningAction SilentlyContinue
452 |
453 | if (-not $modules)
454 | {
455 | return $null
456 | }
457 |
458 | #
459 | #As Get-Module does not take RequiredVersion, MinimumVersion, MaximumVersion, or Repository, below we need to check
460 | #whether the modules are containing the right version and repository location.
461 |
462 | $extractedArguments = ExtractArguments -FunctionBoundParameters $PSBoundParameters `
463 | -ArgumentNames ("MaximumVersion","MinimumVersion", "RequiredVersion")
464 |
465 | $returnVal =@()
466 |
467 | foreach ($m in $modules)
468 | {
469 | $versionMatch = $false
470 | $installedVersion = $m.Version
471 |
472 | #Case 1 - a user provides none of RequiredVersion, MinimumVersion, MaximumVersion
473 |
474 | if ($extractedArguments.Count -eq 0)
475 | {
476 | $versionMatch = $true
477 | }
478 | #
479 | #Case 2 - a user provides RequiredVersion
480 | #
481 | elseif ($extractedArguments.ContainsKey("RequiredVersion"))
482 | {
483 | #Check if it matches with the installedversion
484 | $versionMatch = ($installedVersion -eq [System.Version]$RequiredVersion)
485 | }
486 | else
487 | {
488 | #Case 3 - a user provides MinimumVersion
489 | if ($extractedArguments.ContainsKey("MinimumVersion"))
490 | {
491 | $versionMatch = ($installedVersion -ge [System.Version]$extractedArguments['MinimumVersion'])
492 | }
493 | #
494 | #Case 4 - a user provides MaximumVersion
495 | #
496 | if ($extractedArguments.ContainsKey("MaximumVersion"))
497 | {
498 | $isLessThanMax = ($installedVersion -le [System.Version]$extractedArguments['MaximumVersion'])
499 |
500 | if ($extractedArguments.ContainsKey("MinimumVersion"))
501 | {
502 | $versionMatch = $versionMatch -and $isLessThanMax
503 | }
504 | else
505 | {
506 | $versionMatch = $isLessThanMax
507 | }
508 | }
509 | #Case 5 - Both MinimumVersion and MaximumVersion are provided. it's covered by the above
510 |
511 | #Do not return $false yet to allow the foreach to continue
512 | if (-not $versionMatch)
513 | {
514 | Write-Verbose -Message ($localizedData.VersionMismatch -f $($Name), $($installedVersion))
515 | $versionMatch = $false
516 | }
517 | }
518 |
519 | #Case 6 - Version matches but need to check if the module is from the right repository
520 | #
521 | if ($versionMatch)
522 | {
523 | #a user does not provide Repository, we are good
524 | if (-not $PSBoundParameters.ContainsKey("Repository"))
525 | {
526 | Write-Verbose -Message ($localizedData.ModuleFound -f "$($Name) $($installedVersion)")
527 | $returnVal+=$m
528 |
529 | }
530 | else
531 | {
532 | #Check if the Repository matches
533 | $sourceName = Get-ModuleRepositoryName -Module $m
534 |
535 | if ($Repository -ieq $sourceName)
536 | {
537 | Write-Verbose -Message ($localizedData.ModuleFound -f "$($Name) $($installedVersion)")
538 | $returnVal+=$m
539 | }
540 | else
541 | {
542 | Write-Verbose -Message ($localizedData.RepositoryMismatch -f $($Name), $($sourceName))
543 | }
544 | }
545 | }
546 |
547 | } #foreach
548 |
549 | return $returnVal
550 | }
551 |
552 | Function Get-ModuleRepositoryName
553 | {
554 | <#
555 | .SYNOPSIS
556 |
557 | This is a helper function that returns the module's repository name
558 |
559 | .PARAMETER Module
560 | Specifies the name of the PowerShell module.
561 | #>
562 | Param
563 | (
564 | [parameter(Mandatory = $true)]
565 | [ValidateNotNullOrEmpty()]
566 | [System.Object]$Module
567 | )
568 |
569 |
570 | #RepositorySourceLocation property is supported in PS V5 only. To work with the earlier PS version, we need to do a different way.
571 | #PSGetModuleInfo.xml exists for any PS modules downloaded through PSModule provider.
572 |
573 | $psGetModuleInfoFileName = "PSGetModuleInfo.xml"
574 |
575 | $psGetModuleInfoPath = Microsoft.PowerShell.Management\Join-Path -Path $Module.ModuleBase -ChildPath $psGetModuleInfoFileName
576 |
577 | Write-Verbose -Message ($localizedData.FoundModulePath -f $($psGetModuleInfoPath))
578 |
579 | if (Microsoft.PowerShell.Management\Test-path -Path $psGetModuleInfoPath)
580 | {
581 | $psGetModuleInfo = Microsoft.PowerShell.Utility\Import-Clixml -Path $psGetModuleInfoPath
582 |
583 | return $psGetModuleInfo.Repository
584 | }
585 | }
586 |
587 | Export-ModuleMember -function Get-TargetResource, Set-TargetResource, Test-TargetResource
588 |
--------------------------------------------------------------------------------
/Test/OneGetTestHelper.ps1:
--------------------------------------------------------------------------------
1 | #
2 | # Copyright (c) Microsoft Corporation.
3 | #
4 | # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
5 | # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
6 | # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
7 | # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
8 | # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
9 | # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
10 | # THE SOFTWARE.
11 | #
12 |
13 | <# Run Test cases Pre-Requisite:
14 | 1. After download the OngetGet DSC resources modules, it is expected the following are available under your current directory. For example,
15 |
16 | C:\Program Files\WindowsPowerShell\Modules\PackageManagementProviderResource\
17 |
18 | DSCResources
19 | Examples
20 | Test
21 | PackageManagementProviderResource.psd1
22 | #>
23 |
24 | #Define the variables
25 |
26 | $CurrentDirectory = Split-Path -Path $MyInvocation.MyCommand.Path -Parent
27 |
28 | $script:LocalRepositoryPath = "$CurrentDirectory\LocalRepository"
29 | $script:LocalRepositoryPath1 = "$CurrentDirectory\LocalRepository1"
30 | $script:LocalRepositoryPath2 = "$CurrentDirectory\LocalRepository2"
31 | $script:LocalRepositoryPath3 = "$CurrentDirectory\LocalRepository3"
32 | $script:LocalRepository = "LocalRepository"
33 | $script:InstallationFolder = $null
34 | $script:DestinationPath = $null
35 | $script:Module = $null
36 |
37 |
38 |
39 | #A DSC configuration for installing Pester
40 | configuration Sample_InstallPester
41 | {
42 | <#
43 | .SYNOPSIS
44 |
45 | This is a DSC configution that install/uninstall the Pester tool from the nuget.
46 |
47 | .PARAMETER DestinationPath
48 | Provides the file folder where the Pester to be installed.
49 |
50 | #>
51 |
52 | param
53 | (
54 | #Destination path for the package
55 | [Parameter(Mandatory)]
56 | [string]$DestinationPath
57 | )
58 |
59 | Import-DscResource -Module PackageManagementProviderResource -ModuleVersion 1.0.3
60 |
61 | Node "localhost"
62 | {
63 |
64 | #register package source
65 | PackageManagementSource SourceRepository
66 | {
67 |
68 | Ensure = "Present"
69 | Name = "Mynuget"
70 | ProviderName= "Nuget"
71 | SourceUri = "http://nuget.org/api/v2/"
72 | InstallationPolicy ="Trusted"
73 | }
74 |
75 | #Install a package from Nuget repository
76 | NugetPackage Nuget
77 | {
78 | Ensure = "Present"
79 | Name = "Pester"
80 | DestinationPath = $DestinationPath
81 | DependsOn = "[PackageManagementSource]SourceRepository"
82 | InstallationPolicy="Trusted"
83 | }
84 | }
85 | }
86 |
87 | Function InstallPester
88 | {
89 | <#
90 | .SYNOPSIS
91 |
92 | This function downloads and installs the pester tool.
93 |
94 | #>
95 |
96 | Write-Verbose -Message ("Calling function '$($MyInvocation.mycommand)'") -Verbose
97 |
98 | # Check if the Pester have installed already under Program Files\WindowsPowerShell\Modules\Pester
99 | $pester = Get-Module -Name "Pester" -ListAvailable | select -first 1
100 |
101 | if ($pester.count -ge 1)
102 | {
103 | Write-Verbose -Message "Pester has already installed under $($pester.ModuleBase)" -Verbose
104 |
105 | Import-module -Name "$($pester.ModuleBase)\Pester.psd1"
106 | }
107 | else
108 | {
109 | # Get the module path where to be installed
110 | $module = Get-Module -Name "PackageManagementProviderResource" -ListAvailable
111 |
112 | # Compile it
113 | Sample_InstallPester -DestinationPath "$($module.ModuleBase)\test"
114 |
115 | # Run it
116 | Start-DscConfiguration -path .\Sample_InstallPester -wait -Verbose -force
117 |
118 | $result = Get-DscConfiguration
119 |
120 | #import the Pester tool. Note:$result.Name is something like 'Pester.3.3.5'
121 | Import-module -Name "$($module.ModuleBase)\test\$($result[1].Name)\tools\Pester.psd1"
122 | }
123 | }
124 |
125 |
126 | Function SetupLocalRepository
127 | {
128 | <#
129 | .SYNOPSIS
130 |
131 | This is a helper function to setup a local repostiory/package resouce to speed up the test execution
132 |
133 | .PARAMETER PSModule
134 | Provides whether you are testing PowerShell Modules or Packages.
135 |
136 | #>
137 |
138 | param
139 | (
140 | [Switch]$PSModule
141 | )
142 |
143 | Write-Verbose -Message ("Calling function '$($MyInvocation.mycommand)'") -Verbose
144 |
145 | # Create the LocalRepository path if does not exist
146 | if (-not ( Test-Path -Path $script:LocalRepositoryPath))
147 | {
148 | New-Item -Path $script:LocalRepositoryPath -ItemType Directory -Force
149 | New-Item -Path $script:LocalRepositoryPath1 -ItemType Directory -Force
150 | New-Item -Path $script:LocalRepositoryPath2 -ItemType Directory -Force
151 | New-Item -Path $script:LocalRepositoryPath3 -ItemType Directory -Force
152 | }
153 |
154 | # UnRegister repository/sources
155 | UnRegisterAllSource
156 |
157 | # Register the local repository
158 | RegisterRepository -Name $script:LocalRepository -InstallationPolicy Trusted -Ensure Present
159 |
160 | # Create test modules for the test automation
161 | if ($PSModule)
162 | {
163 | # Set up for PSModule testing
164 | CreateTestModuleInLocalRepository -ModuleName "MyTestModule" -ModuleVersion "1.1" -LocalRepository $script:LocalRepository
165 | CreateTestModuleInLocalRepository -ModuleName "MyTestModule" -ModuleVersion "1.1.2" -LocalRepository $script:LocalRepository
166 | CreateTestModuleInLocalRepository -ModuleName "MyTestModule" -ModuleVersion "3.2.1" -LocalRepository $script:LocalRepository
167 | }
168 | else
169 | {
170 | #Setup for nuget and others testing
171 | CreateTestModuleInLocalRepository -ModuleName "MyTestPackage" -ModuleVersion "12.0.1" -LocalRepository $script:LocalRepository
172 | CreateTestModuleInLocalRepository -ModuleName "MyTestPackage" -ModuleVersion "12.0.1.1" -LocalRepository $script:LocalRepository
173 | CreateTestModuleInLocalRepository -ModuleName "MyTestPackage" -ModuleVersion "15.2.1" -LocalRepository $script:LocalRepository
174 | }
175 |
176 | # Replica the repository
177 | Copy-Item -Path "$script:LocalRepositoryPath\*" -Destination $script:LocalRepositoryPath1 -Recurse -force -Verbose
178 | Copy-Item -Path "$script:LocalRepositoryPath\*" -Destination $script:LocalRepositoryPath2 -Recurse -force -Verbose
179 | Copy-Item -Path "$script:LocalRepositoryPath\*" -Destination $script:LocalRepositoryPath3 -Recurse -force -Verbose
180 | }
181 |
182 | Function SetupPSModuleTest
183 | {
184 | <#
185 | .SYNOPSIS
186 |
187 | This is a helper function for a PSModule test
188 |
189 | #>
190 |
191 | Write-Verbose -Message ("Calling function '$($MyInvocation.mycommand)'") -Verbose
192 |
193 | #Need to import resource MSFT_PSModule.psm1
194 | Import-ModulesToSetupTest -ModuleChildPath "MSFT_PSModule\MSFT_PSModule.psm1"
195 |
196 | SetupLocalRepository -PSModule
197 |
198 | # Install Pester and import it
199 | InstallPester
200 | }
201 |
202 | Function SetupNugetTest
203 | {
204 | <#
205 | .SYNOPSIS
206 |
207 | This is a helper function for a Nuget test
208 |
209 | #>
210 | Write-Verbose -Message ("Calling function '$($MyInvocation.mycommand)'") -Verbose
211 |
212 | #Import MSFT_NugetPackage.psm1 module
213 | Import-ModulesToSetupTest -ModuleChildPath "MSFT_NugetPackage\MSFT_NugetPackage.psm1"
214 |
215 | $script:DestinationPath = "$CurrentDirectory\TestResult\NugetTest"
216 |
217 | SetupLocalRepository
218 |
219 | # Install Pester and import it
220 | InstallPester
221 | }
222 |
223 | Function SetupOneGetSourceTest
224 | {
225 | <#
226 | .SYNOPSIS
227 |
228 | This is a helper function for a PackageManagementSource test
229 |
230 | #>
231 | Write-Verbose -Message ("Calling function '$($MyInvocation.mycommand)'") -Verbose
232 |
233 | Import-ModulesToSetupTest -ModuleChildPath "MSFT_PackageManagementSource\MSFT_PackageManagementSource.psm1"
234 |
235 | SetupLocalRepository
236 |
237 | # Install Pester and import it
238 | InstallPester
239 | }
240 |
241 | function SetupPackageManagementTest
242 | {
243 | <#
244 | .SYNOPSIS
245 |
246 | This is a helper function for a PackageManagement test
247 |
248 | #>
249 | param([switch]$SetupPSModuleRepository)
250 |
251 | Write-Verbose -Message ("Calling function '$($MyInvocation.mycommand)'") -Verbose
252 |
253 | Import-ModulesToSetupTest -ModuleChildPath "MSFT_PackageManagement\MSFT_PackageManagement.psm1"
254 |
255 | $script:DestinationPath = "$CurrentDirectory\TestResult\PackageManagementTest"
256 |
257 | SetupLocalRepository
258 | if ($SetupPSModuleRepository)
259 | {
260 | SetupLocalRepository -PSModule
261 | $script:PSModuleBase = "$env:ProgramFiles\windowspowershell\modules"
262 | }
263 |
264 | # Install Pester and import it
265 | InstallPester
266 |
267 | }
268 |
269 | Function Import-ModulesToSetupTest
270 | {
271 | <#
272 | .SYNOPSIS
273 |
274 | This is a helper function to import modules
275 |
276 | .PARAMETER ModuleChildPath
277 | Provides the child path of the module. The parent path should be the same as the DSC resource.
278 | #>
279 |
280 | param
281 | (
282 | [parameter(Mandatory = $true)]
283 | [System.String]
284 | $ModuleChildPath
285 |
286 | )
287 |
288 | Write-Verbose -Message ("Calling function '$($MyInvocation.mycommand)'") -Verbose
289 |
290 | $moduleChildPath="DSCResources\$($ModuleChildPath)"
291 |
292 | $script:Module = Get-Module -Name "PackageManagementProviderResource" -ListAvailable
293 |
294 | $modulePath = Microsoft.PowerShell.Management\Join-Path -Path $script:Module.ModuleBase -ChildPath $moduleChildPath
295 |
296 | # Using -Force to reload the module (while writing tests..it is common to change product code)
297 | Import-Module -Name "$($modulePath)" -Force
298 |
299 | #c:\Program Files\WindowsPowerShell\Modules
300 | $script:InstallationFolder = "$($script:Module.ModuleBase)"
301 | }
302 |
303 | function RegisterRepository
304 | {
305 | <#
306 | .SYNOPSIS
307 |
308 | This is a helper function to register/unregister the PowerShell repository
309 |
310 | .PARAMETER Name
311 | Provides the repository Name.
312 |
313 | .PARAMETER SourceLocation
314 | Provides the source location.
315 |
316 | .PARAMETER PublishLocation
317 | Provides the publish location.
318 |
319 | .PARAMETER InstallationPolicy
320 | Determines whether you trust the source repository.
321 |
322 | .PARAMETER Ensure
323 | Determines whether the repository to be registered or unregistered.
324 | #>
325 |
326 | param
327 | (
328 | [parameter(Mandatory = $true)]
329 | [System.String]
330 | $Name,
331 |
332 | [System.String]
333 | $SourceLocation=$script:LocalRepositoryPath,
334 |
335 | [System.String]
336 | $PublishLocation=$script:LocalRepositoryPath,
337 |
338 | [ValidateSet("Trusted","Untrusted")]
339 | [System.String]
340 | $InstallationPolicy="Trusted",
341 |
342 | [ValidateSet("Present","Absent")]
343 | [System.String]
344 | $Ensure="Present"
345 | )
346 |
347 | Write-Verbose -Message "RegisterRepository called" -Verbose
348 |
349 | # Calling the following to trigger Bootstrap provider for the first time use PackageManagement
350 | Get-PackageSource -ProviderName Nuget -ForceBootstrap -WarningAction Ignore
351 |
352 | $psrepositories = PowerShellGet\get-PSRepository
353 | $registeredRepository = $null
354 | $isRegistered = $false
355 |
356 | #Check if the repository has been registered already
357 | foreach ($repository in $psrepositories)
358 | {
359 | # The PSRepository is considered as "exists" if either the Name or Source Location are in used
360 | $isRegistered = ($repository.SourceLocation -ieq $SourceLocation) -or ($repository.Name -ieq $Name)
361 |
362 | if ($isRegistered)
363 | {
364 | $registeredRepository = $repository
365 | break;
366 | }
367 | }
368 |
369 | if($Ensure -ieq "Present")
370 | {
371 | # If the repository has already been registered, unregister it.
372 | if ($isRegistered -and ($null -ne $registeredRepository))
373 | {
374 | Unregister-PSRepository -Name $registeredRepository.Name
375 | }
376 |
377 | PowerShellGet\Register-PSRepository -Name $Name -SourceLocation $SourceLocation -PublishLocation $PublishLocation -InstallationPolicy $InstallationPolicy
378 | }
379 | else
380 | {
381 | # The repository has already been registered
382 | if (-not $isRegistered)
383 | {
384 | return
385 | }
386 |
387 | PowerShellGet\UnRegister-PSRepository -Name $Name
388 | }
389 | }
390 |
391 | function RestoreRepository
392 | {
393 | <#
394 | .SYNOPSIS
395 |
396 | This is a helper function to reset back your test environment.
397 |
398 | .PARAMETER RepositoryInfo
399 | Provides the hashtable containing the repository information used for regsitering the repositories.
400 | #>
401 |
402 | param
403 | (
404 | [parameter(Mandatory = $true)]
405 | [Hashtable]
406 | $RepositoryInfo
407 | )
408 |
409 | Write-Verbose -Message "RestoreRepository called" -Verbose
410 |
411 | foreach ($repository in $RepositoryInfo.Keys)
412 | {
413 | try
414 | {
415 | $null = PowerShellGet\Register-PSRepository -Name $RepositoryInfo[$repository].Name `
416 | -SourceLocation $RepositoryInfo[$repository].SourceLocation `
417 | -PublishLocation $RepositoryInfo[$repository].PublishLocation `
418 | -InstallationPolicy $RepositoryInfo[$repository].InstallationPolicy `
419 | -ErrorAction SilentlyContinue
420 | }
421 | #Ignore if the repository already registered
422 | catch
423 | {
424 | if ($_.FullyQualifiedErrorId -ine "PackageSourceExists")
425 | {
426 | throw
427 | }
428 | }
429 | }
430 | }
431 |
432 | function CleanupRepository
433 | {
434 | <#
435 | .SYNOPSIS
436 |
437 | This is a helper function for the test setp. Sometimes tests require no other repositories
438 | are registered, this function helps to do so
439 |
440 | #>
441 |
442 | Write-Verbose -Message "CleanupRepository called" -Verbose
443 |
444 | $returnVal = @{}
445 | $psrepositories = PowerShellGet\get-PSRepository
446 |
447 | foreach ($repository in $psrepositories)
448 | {
449 | #Save the info for later restore process
450 | $repositoryInfo = @{"Name"=$repository.Name; `
451 | "SourceLocation"=$repository.SourceLocation; `
452 | "PublishLocation"=$repository.PublishLocation;`
453 | "InstallationPolicy"=$repository.InstallationPolicy}
454 |
455 | $returnVal.Add($repository.Name, $repositoryInfo);
456 |
457 | try
458 | {
459 | $null = Unregister-PSRepository -Name $repository.Name -ErrorAction SilentlyContinue
460 | }
461 | catch
462 | {
463 | if ($_.FullyQualifiedErrorId -ine "RepositoryCannotBeUnregistered")
464 | {
465 | throw
466 | }
467 | }
468 | }
469 |
470 | Return $returnVal
471 | }
472 |
473 | function RegisterPackageSource
474 | {
475 | <#
476 | .SYNOPSIS
477 |
478 | This is a helper function to register/unregister the package source
479 |
480 | .PARAMETER Name
481 | Provides the package source Name.
482 |
483 | .PARAMETER SourceUri
484 | Provides the source location.
485 |
486 | .PARAMETER PublishLocation
487 | Provides the publish location.
488 |
489 | .PARAMETER Credential
490 | Provides the access to the package on a remote source.
491 |
492 | .PARAMETER InstallationPolicy
493 | Determines whether you trust the source repository.
494 |
495 | .PARAMETER ProviderName
496 | Provides the package provider name.
497 |
498 | .PARAMETER Ensure
499 | Determines whether the package source to be registered or unregistered.
500 | #>
501 |
502 | param
503 | (
504 | [parameter(Mandatory = $true)]
505 | [System.String]
506 | $Name,
507 |
508 | #Source location. It can be source name or uri
509 | [System.String]
510 | $SourceUri,
511 |
512 | [System.Management.Automation.PSCredential]
513 | $Credential,
514 |
515 | [System.String]
516 | [ValidateSet("Trusted","Untrusted")]
517 | $InstallationPolicy ="Untrusted",
518 |
519 | [System.String]
520 | $ProviderName="Nuget",
521 |
522 | [ValidateSet("Present","Absent")]
523 | [System.String]
524 | $Ensure="Present"
525 | )
526 |
527 | Write-Verbose -Message "Calling RegisterPackageSource" -Verbose
528 |
529 | #import the OngetSource module
530 | Import-ModulesToSetupTest -ModuleChildPath "MSFT_PackageManagementSource\MSFT_PackageManagementSource.psm1"
531 |
532 | if($Ensure -ieq "Present")
533 | {
534 | # If the repository has already been registered, unregister it.
535 | UnRegisterSource -Name $Name -ProviderName $ProviderName -SourceUri $SourceUri
536 |
537 | MSFT_PackageManagementSource\Set-TargetResource -Name $name `
538 | -providerName $ProviderName `
539 | -SourceUri $SourceUri `
540 | -SourceCredential $Credential `
541 | -InstallationPolicy $InstallationPolicy `
542 | -Verbose `
543 | -Ensure Present
544 | }
545 | else
546 | {
547 | # The repository has already been registered
548 | UnRegisterSource -Name $Name -ProviderName $ProviderName -SourceUri $SourceUri
549 | }
550 |
551 | # remove the OngetSource module, after we complete the register/unregister task
552 | Remove-Module -Name "MSFT_PackageManagementSource" -Force -ErrorAction SilentlyContinue
553 | }
554 |
555 | Function UnRegisterSource
556 | {
557 | <#
558 | .SYNOPSIS
559 |
560 | This is a helper function to unregister a particular package source
561 |
562 | .PARAMETER Name
563 | Provides the package source Name.
564 |
565 | .PARAMETER SourceUri
566 | Provides the source location.
567 |
568 | .PARAMETER ProviderName
569 | Provides the package provider name.
570 | #>
571 |
572 | param
573 | (
574 | [parameter(Mandatory = $true)]
575 | [System.String]
576 | $Name,
577 |
578 | [System.String]
579 | $SourceUri,
580 |
581 | [System.String]
582 | $ProviderName="Nuget"
583 | )
584 |
585 | Write-Verbose -Message ("Calling function '$($MyInvocation.mycommand)'") -Verbose
586 |
587 | $getResult = MSFT_PackageManagementSource\Get-TargetResource -Name $name -providerName $ProviderName -SourceUri $SourceUri -Verbose
588 |
589 | if ($getResult.Ensure -ieq "Present")
590 | {
591 | #Unregister it
592 | MSFT_PackageManagementSource\Set-TargetResource -Name $name -providerName $ProviderName -SourceUri $SourceUri -Verbose -Ensure Absent
593 | }
594 | }
595 |
596 | Function UnRegisterAllSource
597 | {
598 | <#
599 | .SYNOPSIS
600 |
601 | This is a helper function to unregister all the package source on the machine
602 |
603 | #>
604 |
605 | Write-Verbose -Message ("Calling function '$($MyInvocation.mycommand)'") -Verbose
606 |
607 | $sources = PackageManagement\Get-PackageSource
608 |
609 | foreach ($source in $sources)
610 | {
611 | try
612 | {
613 | #Unregister whatever can be unregistered
614 | PackageManagement\Unregister-PackageSource -Name $source.Name -providerName $source.ProviderName -ErrorAction SilentlyContinue 2>&1
615 | }
616 | catch
617 | {
618 | if ($_.FullyQualifiedErrorId -ine "RepositoryCannotBeUnregistered")
619 | {
620 | throw
621 | }
622 | }
623 | }
624 | }
625 |
626 | function CreateCredObject
627 | {
628 | <#
629 | .SYNOPSIS
630 |
631 | This is a helper function for the cmdlets testing where requires PSCredential
632 |
633 | #>
634 |
635 | [System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")]
636 | param(
637 | [System.String]
638 | $Name,
639 |
640 | [System.String]
641 | $PSCode
642 | )
643 |
644 |
645 | Write-Verbose -Message ("Calling function '$($MyInvocation.mycommand)'") -Verbose
646 |
647 | $secCode = ConvertTo-SecureString -String $PSCode -AsPlainText -Force
648 | $cred = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList ($Name, $secCode)
649 | return $cred
650 | }
651 |
652 | function CreateTestModuleInLocalRepository
653 | {
654 | <#
655 | .SYNOPSIS
656 |
657 | This is a helper function that generates test packages/modules and publishes them to a local repository.
658 | Please note that it only generates manifest files just for testing purpose.
659 |
660 | .PARAMETER ModuleName
661 | Provides the module Name to be generated.
662 |
663 | .PARAMETER ModuleVersion
664 | Provides the module version to be generated.
665 |
666 | .PARAMETER LocalRepository
667 | Provides the local repository Name.
668 | #>
669 |
670 | param(
671 | [System.String]
672 | $ModuleName,
673 |
674 | [System.String]
675 | $ModuleVersion,
676 |
677 | [System.String]
678 | $LocalRepository
679 | )
680 |
681 | Write-Verbose -Message ("Calling function '$($MyInvocation.mycommand)'") -Verbose
682 |
683 | # Return if the package already exists
684 | $m = PowerShellGet\Find-Module -Name $ModuleName -Repository $LocalRepository -RequiredVersion $ModuleVersion -ErrorAction Ignore
685 | if($m)
686 | {
687 | return
688 | }
689 |
690 | # Get the parent 'PackageManagementProviderResource' module path
691 | $parentModulePath = Microsoft.PowerShell.Management\Split-Path -Path $script:Module.ModuleBase -Parent
692 |
693 | $modulePath = Microsoft.PowerShell.Management\Join-Path -Path $parentModulePath -ChildPath "$ModuleName"
694 |
695 | New-Item -Path $modulePath -ItemType Directory -Force
696 |
697 | $modulePSD1Path = "$modulePath\$ModuleName.psd1"
698 |
699 | # Create the module manifest
700 | Microsoft.PowerShell.Core\New-ModuleManifest -Path $modulePSD1Path -Description "$ModuleName" -ModuleVersion $ModuleVersion
701 |
702 |
703 |
704 | try
705 | {
706 | # Publish the module to your local repository
707 | PowerShellGet\Publish-Module -Path $modulePath -NuGetApiKey "Local-Repository-NuGet-ApiKey" -Repository $LocalRepository -Verbose -ErrorAction SilentlyContinue
708 | }
709 | catch
710 | {
711 | # Ignore the particular error
712 | if ($_.FullyQualifiedErrorId -ine "ModuleVersionShouldBeGreaterThanGalleryVersion,Publish-Module")
713 | {
714 | throw
715 | }
716 | }
717 |
718 | # Remove the module under modulepath once we published it to the local repository
719 | Microsoft.PowerShell.Management\Remove-item -Path $modulePath -Recurse -Force -ErrorAction SilentlyContinue
720 | }
721 |
722 | function ConvertHashtableToArryCimInstance
723 | {
724 | <#
725 | .SYNOPSIS
726 |
727 | This helper function is mainly used to convert AdditionalParameters of PackageMangement DSC resource
728 | to Microsoft.Management.Infrastructure.CimInstance[]. This will enable writing DRTs for Get/Set/Test
729 | methods.
730 |
731 | #>
732 | [OutputType([Microsoft.Management.Infrastructure.CimInstance[]])]
733 | param([Hashtable] $AdditionalParameters = $(throw "AdditionalParameters cannot be null."))
734 |
735 | [Microsoft.Management.Infrastructure.CimInstance[]] $result = [Microsoft.Management.Infrastructure.CimInstance[]]::new($AdditionalParameters.Count)
736 |
737 | $index = 0
738 | $AdditionalParameters.Keys | % {
739 | $instance = New-CimInstance -ClassName MSFT_KeyValuePair -Namespace root/microsoft/Windows/DesiredStateConfiguration -Property @{
740 | Key = $_
741 | Value = $AdditionalParameters[$_]
742 | } -ClientOnly
743 | $result[$index] = $instance
744 | $index++
745 | }
746 |
747 | $result
748 | }
749 |
750 | function IsAdmin
751 | {
752 | <#
753 | .SYNOPSIS
754 | Checks whether the current session is Elevated. Used for test suites which has this
755 | requirement
756 | #>
757 | [OutputType([bool])]
758 |
759 | param()
760 | try {
761 | $identity = [Security.Principal.WindowsIdentity]::GetCurrent()
762 | $principal = New-Object Security.Principal.WindowsPrincipal -ArgumentList $identity
763 | return $principal.IsInRole( [Security.Principal.WindowsBuiltInRole]::Administrator )
764 | } catch {
765 | }
766 |
767 | return $false
768 | }
769 |
770 |
--------------------------------------------------------------------------------