diff --git a/.vscode/RunAllTests.ps1 b/.vscode/RunAllTests.ps1 new file mode 100644 index 00000000..598956b3 --- /dev/null +++ b/.vscode/RunAllTests.ps1 @@ -0,0 +1,11 @@ +[string] $repoRoot = Split-Path -Path (Split-Path -Path $Script:MyInvocation.MyCommand.Path) +if ( (-not (Test-Path -Path (Join-Path -Path $repoRoot -ChildPath 'DSCResource.Tests'))) -or ` + (-not (Test-Path -Path (Join-Path -Path $repoRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) +{ + & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $repoRoot -ChildPath '\DSCResource.Tests\')) +} + +Import-Module (Join-Path $PSScriptRoot "..\Tests\TestHarness.psm1" -Resolve) +$dscTestsPath = Join-Path -Path $PSScriptRoot ` + -ChildPath "..\Modules\xComputerManagement\DscResource.Tests\Meta.Tests.ps1" +Invoke-TestHarness -DscTestsPath $dscTestsPath diff --git a/.vscode/launch.json b/.vscode/launch.json new file mode 100644 index 00000000..86c32f38 --- /dev/null +++ b/.vscode/launch.json @@ -0,0 +1,19 @@ +{ + "version": "0.2.0", + "configurations": [ + { + "name": "PowerShell", + "type": "PowerShell", + "request": "launch", + "program": "${file}", + "args": [], + "cwd": "${file}" + }, + { + "name": "Run all tests", + "type": "PowerShell", + "request": "launch", + "program": "${workspaceRoot}/.vscode/RunAllTests.ps1" + } + ] +} diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 00000000..147ad98c --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,181 @@ +# Versions + +## Unreleased + +## 4.0.0.0 + +- BREAKING CHANGE: xScheduledTask: + - Breaking change because `Get-TargetResource` no longer outputs + `ActionExecutable` and `ScheduleType` properties when the scheduled + task does not exist. It will also include `TaskPath` in output when + scheduled task does not exist. +- xScheduledTask: + - Add support to disable built-in scheduled tasks - See [Issue #74](https://github.com/PowerShell/xComputerManagement/issues/74). + - Fix unit test mocked schedule task object structure. + - Fix error message when trigger type is unknown - See [Issue #121](https://github.com/PowerShell/xComputerManagement/issues/121). + - Moved strings into separate strings file. + - Updated to meet HQRM guidelines. +- xComputer: + - Resolved bug in Get-ComputerDomain where LocalSystem doesn't have + rights to the domain. +- Updated tests to meet Pester V4 guidelines - See [Issue #106](https://github.com/PowerShell/xComputerManagement/issues/106). +- Converted module to use auto documentation format. + +## 3.2.0.0 + +- xScheduledTask: + - Enable Execution Time Limit of task to be set to indefinite + by setting `ExecutionTimeLimit` to '00:00:00' - See [Issue #115](https://github.com/PowerShell/xComputerManagement/issues/115). +- xPowerPlan: + - Updated to meet HQRM guidelines. + - Converted calls to `throw` to use `New-InvalidOperationException` + in CommonResourceHelper. +- Move Common Resource Helper functions into modules folder. +- Changed resources to use Common Resource Helper functions. +- Moved strings for Common Resource Helper functions into separate + strings file. +- Added unit tests for Common Helper functions. + +## 3.1.0.0 + +- xOfflineDomainJoin: + - Updated to meet HQRM guidelines. +- xScheduledTask: + - Applied autoformatting to examples to improve readability. + - Added LogonType and RunLevel parameters for controlling + task execution. + - Correct `Assert-VerifiableMocks` to `Assert-VerifiableMock` + +## 3.0.0.0 + +- xComputer: Added parameter to set the local computer description along with documentation + and unit tests for this change. +- BREAKING CHANGE: xScheduledTask: + - Converted all Interval/Duration type parameters over to be string format + to prevent the Timezone the MOF file was created in from being stored. + This is to fix problems where MOF files are created in one timezone but + deployed nodes to a different timezone - See [Issue #85](https://github.com/PowerShell/xComputerManagement/issues/85) + - Added ConvertTo-TimeSpanFromScheduledTaskString function and refactored + to reduce code duplication. + - Added support for setting repetition duration to `Indefinitely`. +- xComputer: + - Moved strings to localization file. + - Updated to meet HQRM guidelines. +- xVirtualMemory: + - Refactored shared common code into new utility functions to + reduce code duplication and improve testability. + - Moved strings into localizable strings file. + - Converted calls to `throw` to use `New-InvalidOperationException` + in CommonResourceHelper. + - Improved unit test coverage. + - Updated to meet HQRM guidelines. + +## 2.1.0.0 + +- xComputer: Changed comparison that validates if we are in the correct AD + Domain to work correctly if FQDN wasn't used. +- Updated AppVeyor.yml to use AppVeyor.psm1 module in DSCResource.Tests. +- Removed Markdown.md errors. +- Added CodeCov.io support. +- xScheduledTask + - Fixed incorrect TaskPath handling - [Issue #45](https://github.com/PowerShell/xComputerManagement/issues/45) +- Change examples to meet HQRM standards and optin to Example validation + tests. +- Replaced examples in README.MD to links to Example files. +- Added the VS Code PowerShell extension formatting settings that cause PowerShell + files to be formatted as per the DSC Resource kit style guidelines - [Issue #91](https://github.com/PowerShell/xComputerManagement/issues/91). +- Opted into Common Tests 'Validate Module Files' and 'Validate Script Files'. +- Converted files with UTF8 with BOM over to UTF8 - fixes [Issue #90](https://github.com/PowerShell/xComputerManagement/issues/90). +- Updated Year to 2017 in License and Manifest - fixes [Issue #87](https://github.com/PowerShell/xComputerManagement/issues/87). +- Added .github support files - fixes [Issue #88](https://github.com/PowerShell/xComputerManagement/issues/88): + - CONTRIBUTING.md + - ISSUE_TEMPLATE.md + - PULL_REQUEST_TEMPLATE.md +- Resolved all PSScriptAnalyzer warnings and style guide warnings. +- xOfflineDomainJoin: + - Changed to use CommonResourceHelper to load localization strings. + - Renamed en-US to be correct case so that localization strings can be loaded. + - Suppress PSScriptAnalyzer rule PSAvoidGlobalVars for + `$global:DSCMachineStatus = 1`. +- xComputer: + - Suppress PSScriptAnalyzer rule PSAvoidGlobalVars for + `$global:DSCMachineStatus = 1`. +- xVirtualMemory: + - Suppress PSScriptAnalyzer rule PSAvoidGlobalVars for + `$global:DSCMachineStatus = 1`. + +## 2.0.0.0 + +- Updated resources + - BREAKING CHANGE: xScheduledTask: Added nearly all available parameters for tasks +- xVirtualMemory: + - Fixed failing tests. + +## 1.10.0.0 + +- Added resources: + - xVirtualMemory + +## 1.9.0.0 + +- Added resources + - xPowerPlan + +## 1.8.0.0 + +- Converted AppVeyor.yml to pull Pester from PSGallery instead of + Chocolatey. +- Changed AppVeyor.yml to use default image +- xScheduledTask: Fixed bug with different OS versions returning repeat interval + differently + +## 1.7.0.0 + +- Added support for enabling or disabling scheduled tasks +- The Name parameter resolves to $env:COMPUTERNAME when the value is localhost + +## 1.6.0.0 + +- Added the following resources: + - MSFT_xOfflineDomainJoin resource to join computers to an AD Domain using an + Offline Domain Join request file. + - MSFT_xScheduledTask resource to control scheduled tasks on the local server +- MSFT_xOfflineDomainJoin: Corrected localizedData.DomainAlreadyJoinedhMessage name. +- xComputer: Changed credential generation code in tests to avoid triggering + PSSA rule PSAvoidUsingConvertToSecureStringWithPlainText. + Renamed unit test file to match the name of Resource file. + +## 1.5.0.0 + +- Update Unit tests to use the standard folder structure and test templates. +- Added .gitignore to prevent commit of DSCResource.Tests. + +## 1.4.0.0 + +- Added validation to the Name parameter +- Added the JoinOU parameter which allows you to specify the organizational unit + that the computer account will be created in +- Added the CurrentOU read-only property that shows the organizational unit that + the computer account is currently in + +## 1.3.0 + +- xComputer + - Fixed issue with Test-TargetResource when not specifying Domain or + Workgroup name + - Added tests + +## 1.2.2 + +- Added types to Get/Set/Test definitions to allow xResourceDesigner validation + to succeed + +## 1.2 + +- Added functionality to enable moving computer from one domain to another +- Modified Test-DscConfiguration logics when testing domain join + +## 1.0.0.0 + +- Initial release with the following resources: + - xComputer diff --git a/DSCResources/MSFT_xComputer/MSFT_xComputer.psm1 b/Modules/xComputerManagement/DSCResources/MSFT_xComputer/MSFT_xComputer.psm1 similarity index 97% rename from DSCResources/MSFT_xComputer/MSFT_xComputer.psm1 rename to Modules/xComputerManagement/DSCResources/MSFT_xComputer/MSFT_xComputer.psm1 index 0d6ab4f0..aec77f67 100644 --- a/DSCResources/MSFT_xComputer/MSFT_xComputer.psm1 +++ b/Modules/xComputerManagement/DSCResources/MSFT_xComputer/MSFT_xComputer.psm1 @@ -572,13 +572,21 @@ function Get-ComputerDomain try { - if ($NetBios) + $domainInfo = Get-CimInstance -ClassName Win32_ComputerSystem + if ($domainInfo.PartOfDomain -eq $true) { - $domainName = $ENV:USERDOMAIN + if ($NetBios) + { + $domainName = (Get-Item -Path Env:\USERDOMAIN).Value + } + else + { + $domainName = $domainInfo.Domain + } } else { - $domainName = ([System.DirectoryServices.ActiveDirectory.Domain]::GetComputerDomain()).Name + $domainName = '' } return $domainName diff --git a/DSCResources/MSFT_xComputer/MSFT_xComputer.schema.mof b/Modules/xComputerManagement/DSCResources/MSFT_xComputer/MSFT_xComputer.schema.mof similarity index 98% rename from DSCResources/MSFT_xComputer/MSFT_xComputer.schema.mof rename to Modules/xComputerManagement/DSCResources/MSFT_xComputer/MSFT_xComputer.schema.mof index a81ddd4c..902746fd 100644 --- a/DSCResources/MSFT_xComputer/MSFT_xComputer.schema.mof +++ b/Modules/xComputerManagement/DSCResources/MSFT_xComputer/MSFT_xComputer.schema.mof @@ -1,12 +1,12 @@ -[ClassVersion("1.0.1.0"), FriendlyName("xComputer")] -class MSFT_xComputer : OMI_BaseResource -{ - [Key, Description("The desired computer name.")] String Name; - [Write, Description("The name of the domain to join.")] String DomainName; - [Write, Description("The distinguished name of the organizational unit that the computer account will be created in.")] String JoinOU; - [Write, Description("Credential to be used to join a domain."), EmbeddedInstance("MSFT_Credential")] String Credential; - [Write, Description("Credential to be used to leave a domain."), EmbeddedInstance("MSFT_Credential")] String UnjoinCredential; - [Write, Description("The name of the workgroup.")] String WorkGroupName; - [Write, Description("The value assigned here will be set as the local computer description.")] String Description; - [Read, Description("A read-only property that specifies the organizational unit that the computer account is currently in.")] String CurrentOU; -}; +[ClassVersion("1.0.1.0"), FriendlyName("xComputer")] +class MSFT_xComputer : OMI_BaseResource +{ + [Key, Description("The desired computer name.")] String Name; + [Write, Description("The name of the domain to join.")] String DomainName; + [Write, Description("The distinguished name of the organizational unit that the computer account will be created in.")] String JoinOU; + [Write, Description("Credential to be used to join a domain."), EmbeddedInstance("MSFT_Credential")] String Credential; + [Write, Description("Credential to be used to leave a domain."), EmbeddedInstance("MSFT_Credential")] String UnjoinCredential; + [Write, Description("The name of the workgroup.")] String WorkGroupName; + [Write, Description("The value assigned here will be set as the local computer description.")] String Description; + [Read, Description("A read-only property that specifies the organizational unit that the computer account is currently in.")] String CurrentOU; +}; diff --git a/Modules/xComputerManagement/DSCResources/MSFT_xComputer/README.md b/Modules/xComputerManagement/DSCResources/MSFT_xComputer/README.md new file mode 100644 index 00000000..d23b215a --- /dev/null +++ b/Modules/xComputerManagement/DSCResources/MSFT_xComputer/README.md @@ -0,0 +1,4 @@ +# Description + +The resource allows you to configure a computer by changing its name and +description and modifying its Active Directory domain or workgroup membership. diff --git a/DSCResources/MSFT_xComputer/en-US/MSFT_xComputer.strings.psd1 b/Modules/xComputerManagement/DSCResources/MSFT_xComputer/en-US/MSFT_xComputer.strings.psd1 similarity index 100% rename from DSCResources/MSFT_xComputer/en-US/MSFT_xComputer.strings.psd1 rename to Modules/xComputerManagement/DSCResources/MSFT_xComputer/en-US/MSFT_xComputer.strings.psd1 diff --git a/DSCResources/MSFT_xOfflineDomainJoin/MSFT_xOfflineDomainJoin.psm1 b/Modules/xComputerManagement/DSCResources/MSFT_xOfflineDomainJoin/MSFT_xOfflineDomainJoin.psm1 similarity index 100% rename from DSCResources/MSFT_xOfflineDomainJoin/MSFT_xOfflineDomainJoin.psm1 rename to Modules/xComputerManagement/DSCResources/MSFT_xOfflineDomainJoin/MSFT_xOfflineDomainJoin.psm1 diff --git a/DSCResources/MSFT_xOfflineDomainJoin/MSFT_xOfflineDomainJoin.schema.mof b/Modules/xComputerManagement/DSCResources/MSFT_xOfflineDomainJoin/MSFT_xOfflineDomainJoin.schema.mof similarity index 100% rename from DSCResources/MSFT_xOfflineDomainJoin/MSFT_xOfflineDomainJoin.schema.mof rename to Modules/xComputerManagement/DSCResources/MSFT_xOfflineDomainJoin/MSFT_xOfflineDomainJoin.schema.mof diff --git a/Modules/xComputerManagement/DSCResources/MSFT_xOfflineDomainJoin/README.md b/Modules/xComputerManagement/DSCResources/MSFT_xOfflineDomainJoin/README.md new file mode 100644 index 00000000..578daeae --- /dev/null +++ b/Modules/xComputerManagement/DSCResources/MSFT_xOfflineDomainJoin/README.md @@ -0,0 +1,5 @@ +# Description + +The resource allows you to join computers to an Active Directory domain using an +[Offline Domain Join](https://technet.microsoft.com/en-us/library/offline-domain-join-djoin-step-by-step(v=ws.10).aspx) +request file. diff --git a/DSCResources/MSFT_xOfflineDomainJoin/en-US/MSFT_xOfflineDomainJoin.strings.psd1 b/Modules/xComputerManagement/DSCResources/MSFT_xOfflineDomainJoin/en-US/MSFT_xOfflineDomainJoin.strings.psd1 similarity index 100% rename from DSCResources/MSFT_xOfflineDomainJoin/en-US/MSFT_xOfflineDomainJoin.strings.psd1 rename to Modules/xComputerManagement/DSCResources/MSFT_xOfflineDomainJoin/en-US/MSFT_xOfflineDomainJoin.strings.psd1 diff --git a/DSCResources/MSFT_xPowerPlan/MSFT_xPowerPlan.psm1 b/Modules/xComputerManagement/DSCResources/MSFT_xPowerPlan/MSFT_xPowerPlan.psm1 similarity index 100% rename from DSCResources/MSFT_xPowerPlan/MSFT_xPowerPlan.psm1 rename to Modules/xComputerManagement/DSCResources/MSFT_xPowerPlan/MSFT_xPowerPlan.psm1 diff --git a/DSCResources/MSFT_xPowerPlan/MSFT_xPowerPlan.schema.mof b/Modules/xComputerManagement/DSCResources/MSFT_xPowerPlan/MSFT_xPowerPlan.schema.mof similarity index 100% rename from DSCResources/MSFT_xPowerPlan/MSFT_xPowerPlan.schema.mof rename to Modules/xComputerManagement/DSCResources/MSFT_xPowerPlan/MSFT_xPowerPlan.schema.mof diff --git a/Modules/xComputerManagement/DSCResources/MSFT_xPowerPlan/README.md b/Modules/xComputerManagement/DSCResources/MSFT_xPowerPlan/README.md new file mode 100644 index 00000000..f7497b55 --- /dev/null +++ b/Modules/xComputerManagement/DSCResources/MSFT_xPowerPlan/README.md @@ -0,0 +1,3 @@ +# Description + +The resource allows specifying a power plan to activate. diff --git a/DSCResources/MSFT_xPowerPlan/en-US/MSFT_xPowerPlan.schema.mfl b/Modules/xComputerManagement/DSCResources/MSFT_xPowerPlan/en-US/MSFT_xPowerPlan.schema.mfl similarity index 98% rename from DSCResources/MSFT_xPowerPlan/en-US/MSFT_xPowerPlan.schema.mfl rename to Modules/xComputerManagement/DSCResources/MSFT_xPowerPlan/en-US/MSFT_xPowerPlan.schema.mfl index 5405b699..2a72c759 100644 --- a/DSCResources/MSFT_xPowerPlan/en-US/MSFT_xPowerPlan.schema.mfl +++ b/Modules/xComputerManagement/DSCResources/MSFT_xPowerPlan/en-US/MSFT_xPowerPlan.schema.mfl @@ -1,6 +1,6 @@ -[Description("This resource is used to activate a power plan.") : Amended,AMENDMENT, LOCALE("MS_409")] -class MSFT_xPowerPlan : OMI_BaseResource -{ - [Key, Description("Specifies the resource is a single instance, the value must be 'Yes'.") : Amended] String IsSingleInstance; - [Description("The name of the power plan to activate.") : Amended] String Name; -}; +[Description("This resource is used to activate a power plan.") : Amended,AMENDMENT, LOCALE("MS_409")] +class MSFT_xPowerPlan : OMI_BaseResource +{ + [Key, Description("Specifies the resource is a single instance, the value must be 'Yes'.") : Amended] String IsSingleInstance; + [Description("The name of the power plan to activate.") : Amended] String Name; +}; diff --git a/DSCResources/MSFT_xPowerPlan/en-US/MSFT_xPowerPlan.strings.psd1 b/Modules/xComputerManagement/DSCResources/MSFT_xPowerPlan/en-US/MSFT_xPowerPlan.strings.psd1 similarity index 100% rename from DSCResources/MSFT_xPowerPlan/en-US/MSFT_xPowerPlan.strings.psd1 rename to Modules/xComputerManagement/DSCResources/MSFT_xPowerPlan/en-US/MSFT_xPowerPlan.strings.psd1 diff --git a/DSCResources/MSFT_xScheduledTask/MSFT_xScheduledTask.psm1 b/Modules/xComputerManagement/DSCResources/MSFT_xScheduledTask/MSFT_xScheduledTask.psm1 similarity index 90% rename from DSCResources/MSFT_xScheduledTask/MSFT_xScheduledTask.psm1 rename to Modules/xComputerManagement/DSCResources/MSFT_xScheduledTask/MSFT_xScheduledTask.psm1 index b1d46743..c731e18a 100644 --- a/DSCResources/MSFT_xScheduledTask/MSFT_xScheduledTask.psm1 +++ b/Modules/xComputerManagement/DSCResources/MSFT_xScheduledTask/MSFT_xScheduledTask.psm1 @@ -26,6 +26,11 @@ Import-Module -Name (Join-Path -Path $modulePath ` -ChildPath (Join-Path -Path 'ComputerManagementDsc.ResourceHelper' ` -ChildPath 'ComputerManagementDsc.ResourceHelper.psm1')) +# Import Localization Strings +$script:localizedData = Get-LocalizedData ` + -ResourceName 'MSFT_xScheduledTask' ` + -ResourcePath (Split-Path -Parent $Script:MyInvocation.MyCommand.Path) + <# .SYNOPSIS Tests if the current resource state matches the desired resource state. @@ -215,7 +220,7 @@ function Get-TargetResource [System.String] $Description, - [Parameter(Mandatory = $true)] + [Parameter()] [System.String] $ActionExecutable, @@ -227,7 +232,7 @@ function Get-TargetResource [System.String] $ActionWorkingPath, - [Parameter(Mandatory = $true)] + [Parameter()] [System.String] [ValidateSet('Once', 'Daily', 'Weekly', 'AtStartup', 'AtLogOn')] $ScheduleType, @@ -376,24 +381,23 @@ function Get-TargetResource $TaskPath = ConvertTo-NormalizedTaskPath -TaskPath $TaskPath - Write-Verbose -Message ('Retrieving existing task ({0} in {1}).' -f $TaskName, $TaskPath) + Write-Verbose -Message ($script:localizedData.GetScheduledTaskMessage -f $TaskName, $TaskPath) $task = Get-ScheduledTask -TaskName $TaskName -TaskPath $TaskPath -ErrorAction SilentlyContinue if ($null -eq $task) { - Write-Verbose -Message ('No task found. returning empty task {0} with Ensure = "Absent".' -f $Taskname) + Write-Verbose -Message ($script:localizedData.TaskNotFoundMessage -f $TaskName, $TaskPath) return @{ - TaskName = $TaskName - ActionExecutable = $ActionExecutable - Ensure = 'Absent' - ScheduleType = $ScheduleType + TaskName = $TaskName + TaskPath = $TaskPath + Ensure = 'Absent' } } else { - Write-Verbose -Message ('Task {0} found in {1}. Retrieving settings, first action, first trigger and repetition settings.' -f $TaskName, $TaskPath) + Write-Verbose -Message ($script:localizedData.TaskFoundMessage -f $TaskName, $TaskPath) $action = $task.Actions | Select-Object -First 1 $trigger = $task.Triggers | Select-Object -First 1 @@ -434,11 +438,13 @@ function Get-TargetResource default { - New-InvalidArgumentException -Message "Trigger type $_ not recognized." -ArgumentName CimClassName + New-InvalidArgumentException ` + -Message ($script:localizedData.TriggerTypeError -f $trigger.CimClass.CimClassName) ` + -ArgumentName CimClassName } } - Write-Verbose -Message ('Detected schedule type {0} for first trigger.' -f $returnScheduleType) + Write-Verbose -Message ($script:localizedData.DetectedScheduleTypeMessage -f $returnScheduleType) $daysOfWeek = @() @@ -503,8 +509,8 @@ function Get-TargetResource RestartCount = $settings.RestartCount RestartInterval = ConvertTo-TimeSpanStringFromScheduledTaskString -TimeSpan $settings.RestartInterval RunOnlyIfNetworkAvailable = $settings.RunOnlyIfNetworkAvailable - RunLevel = [String] $task.Principal.RunLevel - LogonType = [String] $task.Principal.LogonType + RunLevel = [System.String] $task.Principal.RunLevel + LogonType = [System.String] $task.Principal.LogonType } } } @@ -678,7 +684,7 @@ function Set-TargetResource [System.String] $Description, - [Parameter(Mandatory = $true)] + [Parameter()] [System.String] $ActionExecutable, @@ -690,7 +696,7 @@ function Set-TargetResource [System.String] $ActionWorkingPath, - [Parameter(Mandatory = $true)] + [Parameter()] [System.String] [ValidateSet('Once', 'Daily', 'Weekly', 'AtStartup', 'AtLogOn')] $ScheduleType, @@ -839,7 +845,7 @@ function Set-TargetResource $TaskPath = ConvertTo-NormalizedTaskPath -TaskPath $TaskPath - Write-Verbose -Message ('Entering Set-TargetResource for {0} in {1}.' -f $TaskName, $TaskPath) + Write-Verbose -Message ($script:localizedData.SetScheduledTaskMessage -f $TaskName, $TaskPath) # Convert the strings containing time spans to TimeSpan Objects [System.TimeSpan] $RepeatInterval = ConvertTo-TimeSpanFromTimeSpanString -TimeSpanString $RepeatInterval @@ -854,30 +860,50 @@ function Set-TargetResource if ($Ensure -eq 'Present') { + <# + If the scheduled task already exists and is enabled but it needs to be disabled + and the action executable isn't specified then disable the task + #> + if ($currentValues.Ensure -eq 'Present' ` + -and $currentValues.Enable ` + -and -not $Enable ` + -and -not $PSBoundParameters.ContainsKey('ActionExecutable')) + { + Write-Verbose -Message ($script:localizedData.DisablingExistingScheduledTask -f $TaskName, $TaskPath) + Disable-ScheduledTask -TaskName $TaskName -TaskPath $TaskPath + + return + } + if ($RepetitionDuration -lt $RepeatInterval) { - $exceptionMessage = 'Repetition duration {0} is less than repetition interval {1}. Please set RepeatInterval to a value lower or equal to RepetitionDuration.' -f $RepetitionDuration, $RepeatInterval - New-InvalidArgumentException -Message $exceptionMessage -ArgumentName RepeatInterval + New-InvalidArgumentException ` + -Message ($script:localizedData.RepetitionDurationLessThanIntervalError -f $RepetitionDuration, $RepeatInterval) ` + -ArgumentName RepeatInterval } if ($ScheduleType -eq 'Daily' -and $DaysInterval -eq 0) { - $exceptionMessage = 'Schedules of the type Daily must have a DaysInterval greater than 0 (value entered: {0}).' -f $DaysInterval - New-InvalidArgumentException -Message $exceptionMessage -ArgumentName DaysInterval + New-InvalidArgumentException ` + -Message ($script:localizedData.DaysIntervalError -f $DaysInterval) ` + -ArgumentName DaysInterval } if ($ScheduleType -eq 'Weekly' -and $WeeksInterval -eq 0) { - $exceptionMessage = 'Schedules of the type Weekly must have a WeeksInterval greater than 0 (value entered: {0}).' -f $WeeksInterval - New-InvalidArgumentException -Message $exceptionMessage -ArgumentName WeeksInterval + New-InvalidArgumentException ` + -Message ($script:localizedData.WeeksIntervalError -f $WeeksInterval) ` + -ArgumentName WeeksInterval } if ($ScheduleType -eq 'Weekly' -and $DaysOfWeek.Count -eq 0) { - $exceptionMessage = 'Schedules of the type Weekly must have at least one weekday selected.' - New-InvalidArgumentException -Message $exceptionMessage -ArgumentName DaysOfWeek + New-InvalidArgumentException ` + -Message ($script:localizedData.WeekDayMissingError) ` + -ArgumentName DaysOfWeek } + # Configure the action $actionParameters = @{ Execute = $ActionExecutable } @@ -894,6 +920,11 @@ function Set-TargetResource $action = New-ScheduledTaskAction @actionParameters + $scheduledTaskArguments += @{ + Action = $action + } + + # Configure the settings $settingParameters = @{ DisallowDemandStart = $DisallowDemandStart DisallowHardTerminate = $DisallowHardTerminate @@ -941,17 +972,22 @@ function Set-TargetResource $setting = New-ScheduledTaskSettingsSet @settingParameters + $scheduledTaskArguments += @{ + Settings = $setting + } + <# On Windows Server 2012 R2 setting a blank timespan for ExecutionTimeLimit does not result in the PT0S timespan value being set. So set this if it has not been set. #> if ($PSBoundParameters.ContainsKey('ExecutionTimeLimit') -and ` - [System.String]::IsNullOrEmpty($setting.ExecutionTimeLimit)) + [System.String]::IsNullOrEmpty($setting.ExecutionTimeLimit)) { $setting.ExecutionTimeLimit = 'PT0S' } + # Configure the trigger $triggerParameters = @{} if ($RandomDelay -gt [System.TimeSpan]::FromSeconds(0)) @@ -965,6 +1001,7 @@ function Set-TargetResource { $triggerParameters.Add('Once', $true) $triggerParameters.Add('At', $StartTime) + break } @@ -973,6 +1010,7 @@ function Set-TargetResource $triggerParameters.Add('Daily', $true) $triggerParameters.Add('At', $StartTime) $triggerParameters.Add('DaysInterval', $DaysInterval) + break } @@ -980,6 +1018,7 @@ function Set-TargetResource { $triggerParameters.Add('Weekly', $true) $triggerParameters.Add('At', $StartTime) + if ($DaysOfWeek.Count -gt 0) { $triggerParameters.Add('DaysOfWeek', $DaysOfWeek) @@ -989,22 +1028,26 @@ function Set-TargetResource { $triggerParameters.Add('WeeksInterval', $WeeksInterval) } + break } 'AtStartup' { $triggerParameters.Add('AtStartup', $true) + break } 'AtLogOn' { $triggerParameters.Add('AtLogOn', $true) + if (-not [System.String]::IsNullOrWhiteSpace($User)) { $triggerParameters.Add('User', $User) } + break } } @@ -1013,19 +1056,21 @@ function Set-TargetResource if (-not $trigger) { - $exceptionMessage = 'Error creating new scheduled task trigger.' - New-InvalidOperationException -Message $exceptionMessage -ErrorRecord $_ + New-InvalidOperationException ` + -Message ($script:localizedData.TriggerCreationError) ` + -ErrorRecord $_ } if ($RepeatInterval -gt [System.TimeSpan]::Parse('0:0:0')) { # A repetition pattern is required so create it and attach it to the trigger object - Write-Verbose -Message ('Configuring trigger repetition.') + Write-Verbose -Message ($script:localizedData.ConfigureTriggerRepetitionMessage) if ($RepetitionDuration -le $RepeatInterval) { - $exceptionMessage = 'Repetition interval is set to {0} but repetition duration is {1}.' -f $RepeatInterval, $RepetitionDuration - New-InvalidArgumentException -Message $exceptionMessage -ArgumentName RepetitionDuration + New-InvalidArgumentException ` + -Message ($script:localizedData.RepetitionIntervalError -f $RepeatInterval, $RepetitionDuration) ` + -ArgumentName RepetitionDuration } $tempTriggerParameters = @{ @@ -1034,14 +1079,14 @@ function Set-TargetResource RepetitionInterval = $RepeatInterval } - Write-Verbose -Message ('Creating MSFT_TaskRepetitionPattern CIM instance to configure repetition in trigger.') + Write-Verbose -Message ($script:localizedData.CreateRepetitionPatternMessage) switch ($trigger.GetType().FullName) { 'Microsoft.PowerShell.ScheduledJob.ScheduledJobTrigger' { # This is the type of trigger object returned in Windows Server 2012 R2/Windows 8.1 and below - Write-Verbose -Message ('Creating temporary task and trigger to get MSFT_TaskRepetitionPattern CIM instance.') + Write-Verbose -Message ($script:localizedData.CreateTemporaryTaskMessage) $tempTriggerParameters.Add('RepetitionDuration', $RepetitionDuration) @@ -1056,7 +1101,7 @@ function Set-TargetResource 'Microsoft.Management.Infrastructure.CimInstance' { # This is the type of trigger object returned in Windows Server 2016/Windows 10 and above - Write-Verbose -Message ('Creating temporary trigger to get MSFT_TaskRepetitionPattern CIM instance.') + Write-Verbose -Message ($script:localizedData.CreateTemporaryTriggerMessage) if ($RepetitionDuration -gt [System.TimeSpan]::Parse('0:0:0') -and $RepetitionDuration -lt [System.TimeSpan]::MaxValue) { @@ -1073,11 +1118,15 @@ function Set-TargetResource default { New-InvalidOperationException ` - -Message ('Trigger object that was created was of unexpected type {0}.' -f $trigger.GetType().FullName) + -Message ($script:localizedData.TriggerUnexpectedTypeError -f $trigger.GetType().FullName) } } } + $scheduledTaskArguments += @{ + Trigger = $trigger + } + # Prepare the register arguments $registerArguments = @{ TaskName = $TaskName @@ -1090,7 +1139,7 @@ function Set-TargetResource $registerArguments.Add('User', $username) # If the LogonType is not specified then set it to password - if ([String]::IsNullOrEmpty($LogonType)) + if ([System.String]::IsNullOrEmpty($LogonType)) { $LogonType = 'Password' } @@ -1122,30 +1171,30 @@ function Set-TargetResource } # Create the principal object - Write-Verbose -Message ('Creating scheduled task principal for account "{0}" using logon type "{1}".' -f $username, $LogonType) + Write-Verbose -Message ($script:localizedData.CreateScheduledTaskPrincipalMessage -f $username, $LogonType) + $principal = New-ScheduledTaskPrincipal @principalArguments - $scheduledTaskArguments = @{ - Action = $action - Trigger = $trigger - Settings = $setting + $scheduledTaskArguments += @{ Principal = $principal } if ($currentValues.Ensure -eq 'Present') { - Write-Verbose -Message ('Removing previous scheduled task {0}.' -f $TaskName) + Write-Verbose -Message ($script:localizedData.RemovePreviousScheduledTaskMessage -f $TaskName, $TaskPath) + $null = Unregister-ScheduledTask -TaskName $TaskName -TaskPath $TaskPath -Confirm:$false -ErrorAction Stop } - Write-Verbose -Message ('Creating new scheduled task {0}.' -f $TaskName) + Write-Verbose -Message ($script:localizedData.CreateNewScheduledTaskMessage -f $TaskName, $TaskPath) # Create the scheduled task object $scheduledTask = New-ScheduledTask @scheduledTaskArguments -ErrorAction Stop if ($repetition) { - Write-Verbose -Message ('Setting repetition trigger settings on task {0}.' -f $TaskName) + Write-Verbose -Message ($script:localizedData.SetRepetitionTriggerMessage -f $TaskName, $TaskPath) + $scheduledTask.Triggers[0].Repetition = $repetition } @@ -1157,13 +1206,14 @@ function Set-TargetResource # Register the scheduled task $registerArguments.Add('InputObject', $scheduledTask) - Write-Verbose -Message ('Registering the scheduled task {0}.' -f $TaskName) + Write-Verbose -Message ($script:localizedData.RegisterScheduledTaskMessage -f $TaskName, $TaskPath) + $null = Register-ScheduledTask @registerArguments -ErrorAction Stop } if ($Ensure -eq 'Absent') { - Write-Verbose -Message ('Removing the scheduled task {0}.' -f $TaskName) + Write-Verbose -Message ($script:localizedData.RemoveScheduledTaskMessage -f $TaskName, $TaskPath) Unregister-ScheduledTask -TaskName $TaskName -TaskPath $TaskPath -Confirm:$false -ErrorAction Stop } @@ -1339,7 +1389,7 @@ function Test-TargetResource [System.String] $Description, - [Parameter(Mandatory = $true)] + [Parameter()] [System.String] $ActionExecutable, @@ -1351,7 +1401,7 @@ function Test-TargetResource [System.String] $ActionWorkingPath, - [Parameter(Mandatory = $true)] + [Parameter()] [System.String] [ValidateSet('Once', 'Daily', 'Weekly', 'AtStartup', 'AtLogOn')] $ScheduleType, @@ -1500,6 +1550,8 @@ function Test-TargetResource $TaskPath = ConvertTo-NormalizedTaskPath -TaskPath $TaskPath + Write-Verbose -Message ($script:localizedData.TestScheduledTaskMessage -f $TaskName, $TaskPath) + # Convert the strings containing time spans to TimeSpan Objects if ($PSBoundParameters.ContainsKey('RepeatInterval')) { @@ -1544,11 +1596,9 @@ function Test-TargetResource $PSBoundParameters['RestartInterval'] = (ConvertTo-TimeSpanFromTimeSpanString -TimeSpanString $RestartInterval).ToString() } - Write-Verbose -Message ('Testing scheduled task {0}' -f $TaskName) - $currentValues = Get-TargetResource @PSBoundParameters - Write-Verbose -Message 'Current values retrieved' + Write-Verbose -Message ($script:localizedData.GetCurrentTaskValuesMessage) if ($Ensure -eq 'Absent' -and $currentValues.Ensure -eq 'Absent') { @@ -1557,7 +1607,8 @@ function Test-TargetResource if ($null -eq $currentValues) { - Write-Verbose -Message 'Current values were null.' + Write-Verbose -Message ($script:localizedData.CurrentTaskValuesNullMessage) + return $false } @@ -1570,7 +1621,9 @@ function Test-TargetResource $desiredValues = $PSBoundParameters $desiredValues.TaskPath = $TaskPath - Write-Verbose -Message 'Testing DSC parameter state.' + + Write-Verbose -Message ($script:localizedData.TestingDscParameterStateMessage) + return Test-DscParameterState -CurrentValues $currentValues -DesiredValues $desiredValues } @@ -1670,7 +1723,7 @@ function ConvertTo-TimeSpanStringFromScheduledTaskString ) # If AllowIndefinitely is true and the timespan is empty then return Indefinitely - if ($AllowIndefinitely -eq $true -and [String]::IsNullOrEmpty($TimeSpan)) + if ($AllowIndefinitely -eq $true -and [System.String]::IsNullOrEmpty($TimeSpan)) { return 'Indefinitely' } @@ -1699,3 +1752,32 @@ function ConvertTo-TimeSpanStringFromScheduledTaskString return (New-TimeSpan -Days $days -Hours $hours -Minutes $minutes -Seconds $seconds).ToString() } + +<# + .SYNOPSIS + Helper function to disable an existing scheduled task. + + .PARAMETER TaskName + The name of the task to disable. + + .PARAMETER TaskPath + The path to the task to disable. +#> +function Disable-ScheduledTask +{ + [CmdletBinding()] + param + ( + [Parameter(Mandatory = $true)] + [System.String] + $TaskName, + + [Parameter()] + [System.String] + $TaskPath = '\' + ) + + $existingTask = Get-ScheduledTask @PSBoundParameters + $existingTask.Settings.Enabled = $false + $null = $existingTask | Register-ScheduledTask @PSBoundParameters -Force +} diff --git a/DSCResources/MSFT_xScheduledTask/MSFT_xScheduledTask.schema.mof b/Modules/xComputerManagement/DSCResources/MSFT_xScheduledTask/MSFT_xScheduledTask.schema.mof similarity index 95% rename from DSCResources/MSFT_xScheduledTask/MSFT_xScheduledTask.schema.mof rename to Modules/xComputerManagement/DSCResources/MSFT_xScheduledTask/MSFT_xScheduledTask.schema.mof index 7d84999c..8d408a90 100644 --- a/DSCResources/MSFT_xScheduledTask/MSFT_xScheduledTask.schema.mof +++ b/Modules/xComputerManagement/DSCResources/MSFT_xScheduledTask/MSFT_xScheduledTask.schema.mof @@ -4,10 +4,10 @@ class MSFT_xScheduledTask : OMI_BaseResource [Key, Description("The name of the task")] string TaskName; [Write, Description("The path to the task - defaults to the root directory")] string TaskPath; [Write, Description("The task description")] string Description; - [Required, Description("The path to the .exe for this task")] string ActionExecutable; + [Write, Description("The path to the .exe for this task")] string ActionExecutable; [Write, Description("The arguments to pass the executable")] string ActionArguments; [Write, Description("The working path to specify for the executable")] string ActionWorkingPath; - [Required, Description("When should the task be executed"), ValueMap{"Once", "Daily", "Weekly", "AtStartup", "AtLogOn"}, Values{"Once", "Daily", "Weekly", "AtStartup", "AtLogOn"}] string ScheduleType; + [Write, Description("When should the task be executed"), ValueMap{"Once", "Daily", "Weekly", "AtStartup", "AtLogOn"}, Values{"Once", "Daily", "Weekly", "AtStartup", "AtLogOn"}] string ScheduleType; [Write, Description("How many units (minutes, hours, days) between each run of this task?")] String RepeatInterval; [Write, Description("The time of day this task should start at - defaults to 12:00 AM. Not valid for AtLogon and AtStartup tasks")] DateTime StartTime; [Write, Description("Present if the task should exist, Absent if it should be removed"), ValueMap{"Present","Absent"}, Values{"Present","Absent"}] string Ensure; diff --git a/Modules/xComputerManagement/DSCResources/MSFT_xScheduledTask/README.md b/Modules/xComputerManagement/DSCResources/MSFT_xScheduledTask/README.md new file mode 100644 index 00000000..77f2b32e --- /dev/null +++ b/Modules/xComputerManagement/DSCResources/MSFT_xScheduledTask/README.md @@ -0,0 +1,5 @@ +# Description + +The resource is used to define basic run once or recurring scheduled tasks +on the local computer. It can also be used to delete or disable built-in +scheduled tasks. diff --git a/Modules/xComputerManagement/DSCResources/MSFT_xScheduledTask/en-US/MSFT_xScheduledTask.strings.psd1 b/Modules/xComputerManagement/DSCResources/MSFT_xScheduledTask/en-US/MSFT_xScheduledTask.strings.psd1 new file mode 100644 index 00000000..f80f00ed --- /dev/null +++ b/Modules/xComputerManagement/DSCResources/MSFT_xScheduledTask/en-US/MSFT_xScheduledTask.strings.psd1 @@ -0,0 +1,30 @@ +ConvertFrom-StringData @' + GetScheduledTaskMessage = Getting scheduled task '{0}' in '{1}'. + TaskNotFoundMessage = Task '{0}' not found in '{1}'. Returning an empty task with Ensure = "Absent". + TaskFoundMessage = Task '{0}' found in '{1}'. Retrieving settings, first action, first trigger and repetition settings. + TriggerTypeError = Trigger type '{0}' not recognized. + DetectedScheduleTypeMessage = Detected schedule type '{0}' for first trigger. + SetScheduledTaskMessage = Setting scheduled task '{0}' in '{1}'. + DisablingExistingScheduledTask = Disabling existing scheduled task '{0}' in '{1}'. + RepetitionDurationLessThanIntervalError = Repetition duration '{0}' is less than repetition interval '{1}'. Please set RepeatInterval to a value lower or equal to RepetitionDuration. + DaysIntervalError = DaysInterval must be greater than zero (0) for Daily schedules. DaysInterval specified is '{0}'. + WeeksIntervalError = WeeksInterval must be greater than zero (0) for Weekly schedules. WeeksInterval specified is '{0}'. + WeekDayMissingError = At least one weekday must be selected for Weekly schedule. + TriggerCreationError = Error creating new scheduled task trigger. + ConfigureTriggerRepetitionMessage = Configuring trigger repetition. + RepetitionIntervalError = Repetition interval is set to '{0}' but repetition duration is '{1}'. + CreateRepetitionPatternMessage = Creating MSFT_TaskRepetitionPattern CIM instance to configure repetition in trigger. + CreateTemporaryTaskMessage = Creating temporary task and trigger to get MSFT_TaskRepetitionPattern CIM instance. + CreateTemporaryTriggerMessage = Creating temporary trigger to get MSFT_TaskRepetitionPattern CIM instance. + TriggerUnexpectedTypeError = Trigger object that was created was of unexpected type '{0}'. + CreateScheduledTaskPrincipalMessage = Creating scheduled task principal for account '{0}' using logon type '{1}'. + RemovePreviousScheduledTaskMessage = Removing previous scheduled task '{0}' from '{1}'. + CreateNewScheduledTaskMessage = Creating new scheduled task '{0}' in '{1}'. + SetRepetitionTriggerMessage = Setting repetition trigger settings on task '{0}' in '{1}'. + RegisterScheduledTaskMessage = Registering the scheduled task '{0}' in '{1}'. + RemoveScheduledTaskMessage = Removing scheduled task '{0}' from '{1}'. + TestScheduledTaskMessage = Testing scheduled task '{0}' in '{1}'. + GetCurrentTaskValuesMessage = Current scheduled task values retrieved. + CurrentTaskValuesNullMessage = Current scheduled values were null. + TestingDscParameterStateMessage = Testing DSC parameter state. +'@ diff --git a/DSCResources/MSFT_xVirtualMemory/MSFT_xVirtualMemory.psm1 b/Modules/xComputerManagement/DSCResources/MSFT_xVirtualMemory/MSFT_xVirtualMemory.psm1 similarity index 96% rename from DSCResources/MSFT_xVirtualMemory/MSFT_xVirtualMemory.psm1 rename to Modules/xComputerManagement/DSCResources/MSFT_xVirtualMemory/MSFT_xVirtualMemory.psm1 index 1ce4d76d..0d5046a5 100644 --- a/DSCResources/MSFT_xVirtualMemory/MSFT_xVirtualMemory.psm1 +++ b/Modules/xComputerManagement/DSCResources/MSFT_xVirtualMemory/MSFT_xVirtualMemory.psm1 @@ -1,536 +1,536 @@ -[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidGlobalVars", "", Scope = "Function")] -param -( -) - -$modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' - -# Import the ComputerManagementDsc Common Modules -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'ComputerManagementDsc.Common' ` - -ChildPath 'ComputerManagementDsc.Common.psm1')) - -# Import the ComputerManagementDsc Resource Helper Module -Import-Module -Name (Join-Path -Path $modulePath ` - -ChildPath (Join-Path -Path 'ComputerManagementDsc.ResourceHelper' ` - -ChildPath 'ComputerManagementDsc.ResourceHelper.psm1')) - -# Import Localization Strings -$script:localizedData = Get-LocalizedData ` - -ResourceName 'MSFT_xVirtualMemory' ` - -ResourcePath (Split-Path -Parent $Script:MyInvocation.MyCommand.Path) - -<# - .SYNOPSIS - Returns the current state of the virtual memory configuration - - .PARAMETER Drive - The drive for which the virtual memory configuration needs to be returned - - .PARAMETER Type - The type of the virtual memory configuration -#> -function Get-TargetResource -{ - [CmdletBinding()] - [OutputType([System.Collections.Hashtable])] - param - ( - [Parameter(Mandatory = $true)] - [System.String] - $Drive, - - [Parameter(Mandatory = $true)] - [ValidateSet('AutoManagePagingFile', 'CustomSize', 'SystemManagedSize', 'NoPagingFile')] - [System.String] - $Type - ) - - Write-Verbose -Message ($script:localizedData.GettingVirtualMemoryMessage) - - $returnValue = @{ - Drive = [string]::Empty - Type = [string]::Empty - InitialSize = 0 - MaximumSize = 0 - } - - [System.Boolean] $isSystemManaged = (Get-CimInstance -ClassName 'Win32_ComputerSystem').AutomaticManagedPagefile - - if ($isSystemManaged) - { - $returnValue.Type = 'AutoManagePagingFile' - return $returnValue - } - - $driveInfo = [System.IO.DriveInfo] $Drive - - $existingPageFileSetting = Get-PageFileSetting ` - -Drive $($driveInfo.Name.Substring(0,2)) - - if (-not $existingPageFileSetting) - { - $returnValue.Type = 'NoPagingFile' - } - else - { - if ($existingPageFileSetting.InitialSize -eq 0 -and $existingPageFileSetting.MaximumSize -eq 0) - { - $returnValue.Type = 'SystemManagedSize' - } - else - { - $returnValue.Type = 'CustomSize' - } - - $returnValue.Drive = $existingPageFileSetting.Name.Substring(0, 3) - $returnValue.InitialSize = $existingPageFileSetting.InitialSize - $returnValue.MaximumSize = $existingPageFileSetting.MaximumSize - } - - return $returnValue -} - -<# - .SYNOPSIS - Sets the virtual memory settings based on the parameters supplied - - .PARAMETER Drive - The drive for which the virtual memory configuration should be set. - - .PARAMETER Type - The paging type. When set to AutoManagePagingFile, drive letters are ignored - - .PARAMETER InitialSize - The initial page file size in megabyte - - .PARAMETER MaximumSize - The maximum page file size in megabyte. May not be smaller than InitialSize -#> -function Set-TargetResource -{ - [CmdletBinding()] - param - ( - [Parameter(Mandatory = $true)] - [System.String] - $Drive, - - [Parameter(Mandatory = $true)] - [ValidateSet('AutoManagePagingFile', 'CustomSize', 'SystemManagedSize', 'NoPagingFile')] - [System.String] - $Type, - - [Parameter()] - [System.Int64] - $InitialSize, - - [Parameter()] - [System.Int64] - $MaximumSize - ) - - Write-Verbose -Message ($script:localizedData.SettingVirtualMemoryMessage) - - $systemInfo = Get-CimInstance -ClassName 'Win32_ComputerSystem' - - switch ($Type) - { - 'AutoManagePagingFile' - { - Set-AutoManagePaging -State Enable - - $global:DSCMachineStatus = 1 - - break - } - - 'CustomSize' - { - if ($systemInfo.AutomaticManagedPageFile) - { - # First Disable Automatic Managed Page File - Set-AutoManagePaging -State Disable - } - - $driveInfo = Get-DriveInfo -Drive $Drive - - $existingPageFileSetting = Get-PageFileSetting ` - -Drive $($driveInfo.Name.Substring(0,2)) - - if (-not $existingPageFileSetting) - { - $pageFileName = Join-Path ` - -Path $driveInfo.Name ` - -ChildPath 'pagefile.sys' - - New-PageFile -PageFileName $pageFileName - } - - Set-PageFileSetting ` - -Drive $driveInfo.Name.Substring(0,2) ` - -InitialSize $InitialSize ` - -MaximumSize $MaximumSize - - $global:DSCMachineStatus = 1 - - Write-Verbose -Message ($script:localizedData.EnabledCustomSizeMessage -f $Drive) - - break - } - - 'SystemManagedSize' - { - if ($systemInfo.AutomaticManagedPageFile) - { - # First Disable Automatic Managed Page File - Set-AutoManagePaging -State Disable - } - - $driveInfo = Get-DriveInfo -Drive $Drive - - $existingPageFileSetting = Get-PageFileSetting ` - -Drive $($driveInfo.Name.Substring(0,2)) - - if (-not $existingPageFileSetting) - { - $pageFileName = Join-Path ` - -Path $driveInfo.Name ` - -ChildPath 'pagefile.sys' - - New-PageFile -PageFileName $pageFileName - } - - Set-PageFileSetting ` - -Drive $driveInfo.Name.Substring(0,2) - - $global:DSCMachineStatus = 1 - - Write-Verbose -Message ($script:localizedData.EnabledSystemManagedSizeMessage -f $Drive) - - break - } - - 'NoPagingFile' - { - if ($systemInfo.AutomaticManagedPageFile) - { - # First Disable Automatic Managed Page File - Set-AutoManagePaging -State Disable - } - - $driveInfo = Get-DriveInfo -Drive $Drive - - $existingPageFileSetting = Get-PageFileSetting ` - -Drive $($driveInfo.Name.Substring(0,2)) - - if ($existingPageFileSetting) - { - Write-Verbose -Message ($script:localizedData.RemovePageFileMessage -f $existingPageFileSetting.Name) - - $null = Remove-CimInstance ` - -InputObject $existingPageFileSetting - - $global:DSCMachineStatus = 1 - } - - Write-Verbose -Message ($script:localizedData.DisabledPageFileMessage -f $Drive) - - break - } - } -} - -<# - .SYNOPSIS - Tests if virtual memory settings need to be applied based on the parameters supplied - - .PARAMETER Drive - The drive letter that should be tested - - .PARAMETER Type - The type of the virtual memory configuration - - .PARAMETER InitialSize - The initial page file size in megabyte - - .PARAMETER MaximumSize - The maximum page file size in megabyte -#> -function Test-TargetResource -{ - [CmdletBinding()] - [OutputType([System.Boolean])] - param - ( - [Parameter(Mandatory = $true)] - [System.String] - $Drive, - - [Parameter(Mandatory = $true)] - [ValidateSet('AutoManagePagingFile', 'CustomSize', 'SystemManagedSize', 'NoPagingFile')] - [System.String] - $Type, - - [Parameter()] - [System.Int64] - $InitialSize, - - [Parameter()] - [System.Int64] - $MaximumSize - ) - - Write-Verbose -Message ($script:localizedData.TestingVirtualMemoryMessage) - - $systemInfo = Get-CimInstance -ClassName 'Win32_ComputerSystem' - $inDesiredState = $false - - switch ($Type) - { - 'AutoManagePagingFile' - { - $inDesiredState = $systemInfo.AutomaticManagedPagefile - break - } - - 'CustomSize' - { - if ($systemInfo.AutomaticManagedPageFile) - { - break - } - - $driveInfo = [System.IO.DriveInfo] $Drive - - $existingPageFileSetting = Get-PageFileSetting ` - -Drive $($driveInfo.Name.Substring(0,2)) - - if (-not $existingPageFileSetting) - { - break - } - - if (-not ($existingPageFileSetting.InitialSize -eq $InitialSize -and $existingPageFileSetting.MaximumSize -eq $MaximumSize)) - { - break - } - - $inDesiredState = $true - break - } - - 'SystemManagedSize' - { - if ($systemInfo.AutomaticManagedPageFile) - { - break - } - - $driveInfo = [System.IO.DriveInfo] $Drive - - $existingPageFileSetting = Get-PageFileSetting ` - -Drive $($driveInfo.Name.Substring(0,2)) - - if (-not $existingPageFileSetting) - { - break - } - - if (-not ($existingPageFileSetting.InitialSize -eq 0 -and $existingPageFileSetting.MaximumSize -eq 0)) - { - break - } - - $inDesiredState = $true - break - } - - 'NoPagingFile' - { - if ($systemInfo.AutomaticManagedPageFile) - { - break - } - - $driveInfo = [System.IO.DriveInfo] $Drive - - $existingPageFileSetting = Get-PageFileSetting ` - -Drive $($driveInfo.Name.Substring(0,2)) - - if ($existingPageFileSetting) - { - break - } - - $inDesiredState = $true - break - } - } - - return $inDesiredState -} - -<# - .SYNOPSIS - Gets the settings for a page file assigned to a Drive. - - .PARAMETER State - The drive letter for the page file to return the settings of. -#> -function Get-PageFileSetting -{ - [CmdletBinding()] - param - ( - [Parameter(Mandatory = $true)] - [System.String] - $Drive - ) - - Write-Verbose -Message ($script:localizedData.GettingPageFileSettingsMessage -f $Drive) - - # Find existing page file settings by drive letter - return Get-CimInstance ` - -ClassName 'Win32_PageFileSetting' ` - -Filter "SettingID='pagefile.sys @ $Drive'" -} - -<# - .SYNOPSIS - Sets a new page file name. - - .PARAMETER Drive - The letter of the drive containing the page file - to change the settings of. - - .PARAMETER InitialSize - The initial size to set the page file to. - - .PARAMETER MaximumSize - The maximum size to set the page file to. -#> -function Set-PageFileSetting -{ - [CmdletBinding()] - param - ( - [Parameter(Mandatory = $true)] - [System.String] - $Drive, - - [Parameter()] - [System.Int64] - $InitialSize = 0, - - [Parameter()] - [System.Int64] - $MaximumSize = 0 - ) - - $setParams = @{ - Namespace = 'root\cimv2' - Query = "Select * from Win32_PageFileSetting where SettingID='pagefile.sys @ $Drive'" - Property = @{ - InitialSize = $InitialSize - MaximumSize = $MaximumSize - } - } - - Write-Verbose -Message ($script:localizedData.SettingPageFileSettingsMessage -f $Drive, $InitialSize, $MaximumSize) - - $null = Set-CimInstance @setParams -} - -<# - .SYNOPSIS - Enables or Disables Automatically Managed Paging. - - .PARAMETER State - Specifies if Automatically Managed Paging is enabled - or disabled. -#> -function Set-AutoManagePaging -{ - [CmdletBinding()] - param - ( - [Parameter(Mandatory = $true)] - [ValidateSet('Enable', 'Disable')] - [System.String] - $State - ) - - $setParams = @{ - Namespace = 'root\cimv2' - Query = 'Select * from Win32_ComputerSystem' - Property = @{ - AutomaticManagedPageFile = ($State -eq 'Enable') - } - } - - Write-Verbose -Message ($script:localizedData.SetAutoManagePagingMessage -f $State) - - $null = Set-CimInstance @setParams -} - -<# - .SYNOPSIS - Sets a new page file name. - - .PARAMETER PageFileName - The name of the new page file. -#> -function New-PageFile -{ - [CmdletBinding()] - param - ( - [Parameter(Mandatory = $true)] - [System.String] - $PageFileName - ) - - Write-Verbose -Message ($script:localizedData.NewPageFileMessage -f $State) - - $null = New-CimInstance ` - -Namespace 'root\cimv2' ` - -ClassName 'Win32_PageFileSetting' ` - -Property @{ - Name = $PageFileName - } -} - -<# - .SYNOPSIS - Gets the Drive info object for a specified - Drive. It will throw an exception if the drive - is invalid or does not exist. - - .PARAMETER Drive - The letter of the drive to get the drive info - for. -#> -function Get-DriveInfo -{ - [CmdletBinding()] - [OutputType([System.IO.DriveInfo])] - param - ( - [Parameter(Mandatory = $true)] - [System.String] - $Drive - ) - - $driveInfo = [System.IO.DriveInfo] $Drive - - if (-not $driveInfo.IsReady) - { - New-InvalidOperationException ` - -Message ($script:localizedData.DriveNotReadyError -f $driveInfo.Name) - } - - return $driveInfo -} - -Export-ModuleMember -Function *-TargetResource +[Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidGlobalVars", "", Scope = "Function")] +param +( +) + +$modulePath = Join-Path -Path (Split-Path -Path (Split-Path -Path $PSScriptRoot -Parent) -Parent) -ChildPath 'Modules' + +# Import the ComputerManagementDsc Common Modules +Import-Module -Name (Join-Path -Path $modulePath ` + -ChildPath (Join-Path -Path 'ComputerManagementDsc.Common' ` + -ChildPath 'ComputerManagementDsc.Common.psm1')) + +# Import the ComputerManagementDsc Resource Helper Module +Import-Module -Name (Join-Path -Path $modulePath ` + -ChildPath (Join-Path -Path 'ComputerManagementDsc.ResourceHelper' ` + -ChildPath 'ComputerManagementDsc.ResourceHelper.psm1')) + +# Import Localization Strings +$script:localizedData = Get-LocalizedData ` + -ResourceName 'MSFT_xVirtualMemory' ` + -ResourcePath (Split-Path -Parent $Script:MyInvocation.MyCommand.Path) + +<# + .SYNOPSIS + Returns the current state of the virtual memory configuration + + .PARAMETER Drive + The drive for which the virtual memory configuration needs to be returned + + .PARAMETER Type + The type of the virtual memory configuration +#> +function Get-TargetResource +{ + [CmdletBinding()] + [OutputType([System.Collections.Hashtable])] + param + ( + [Parameter(Mandatory = $true)] + [System.String] + $Drive, + + [Parameter(Mandatory = $true)] + [ValidateSet('AutoManagePagingFile', 'CustomSize', 'SystemManagedSize', 'NoPagingFile')] + [System.String] + $Type + ) + + Write-Verbose -Message ($script:localizedData.GettingVirtualMemoryMessage) + + $returnValue = @{ + Drive = [string]::Empty + Type = [string]::Empty + InitialSize = 0 + MaximumSize = 0 + } + + [System.Boolean] $isSystemManaged = (Get-CimInstance -ClassName 'Win32_ComputerSystem').AutomaticManagedPagefile + + if ($isSystemManaged) + { + $returnValue.Type = 'AutoManagePagingFile' + return $returnValue + } + + $driveInfo = [System.IO.DriveInfo] $Drive + + $existingPageFileSetting = Get-PageFileSetting ` + -Drive $($driveInfo.Name.Substring(0,2)) + + if (-not $existingPageFileSetting) + { + $returnValue.Type = 'NoPagingFile' + } + else + { + if ($existingPageFileSetting.InitialSize -eq 0 -and $existingPageFileSetting.MaximumSize -eq 0) + { + $returnValue.Type = 'SystemManagedSize' + } + else + { + $returnValue.Type = 'CustomSize' + } + + $returnValue.Drive = $existingPageFileSetting.Name.Substring(0, 3) + $returnValue.InitialSize = $existingPageFileSetting.InitialSize + $returnValue.MaximumSize = $existingPageFileSetting.MaximumSize + } + + return $returnValue +} + +<# + .SYNOPSIS + Sets the virtual memory settings based on the parameters supplied + + .PARAMETER Drive + The drive for which the virtual memory configuration should be set. + + .PARAMETER Type + The paging type. When set to AutoManagePagingFile, drive letters are ignored + + .PARAMETER InitialSize + The initial page file size in megabyte + + .PARAMETER MaximumSize + The maximum page file size in megabyte. May not be smaller than InitialSize +#> +function Set-TargetResource +{ + [CmdletBinding()] + param + ( + [Parameter(Mandatory = $true)] + [System.String] + $Drive, + + [Parameter(Mandatory = $true)] + [ValidateSet('AutoManagePagingFile', 'CustomSize', 'SystemManagedSize', 'NoPagingFile')] + [System.String] + $Type, + + [Parameter()] + [System.Int64] + $InitialSize, + + [Parameter()] + [System.Int64] + $MaximumSize + ) + + Write-Verbose -Message ($script:localizedData.SettingVirtualMemoryMessage) + + $systemInfo = Get-CimInstance -ClassName 'Win32_ComputerSystem' + + switch ($Type) + { + 'AutoManagePagingFile' + { + Set-AutoManagePaging -State Enable + + $global:DSCMachineStatus = 1 + + break + } + + 'CustomSize' + { + if ($systemInfo.AutomaticManagedPageFile) + { + # First Disable Automatic Managed Page File + Set-AutoManagePaging -State Disable + } + + $driveInfo = Get-DriveInfo -Drive $Drive + + $existingPageFileSetting = Get-PageFileSetting ` + -Drive $($driveInfo.Name.Substring(0,2)) + + if (-not $existingPageFileSetting) + { + $pageFileName = Join-Path ` + -Path $driveInfo.Name ` + -ChildPath 'pagefile.sys' + + New-PageFile -PageFileName $pageFileName + } + + Set-PageFileSetting ` + -Drive $driveInfo.Name.Substring(0,2) ` + -InitialSize $InitialSize ` + -MaximumSize $MaximumSize + + $global:DSCMachineStatus = 1 + + Write-Verbose -Message ($script:localizedData.EnabledCustomSizeMessage -f $Drive) + + break + } + + 'SystemManagedSize' + { + if ($systemInfo.AutomaticManagedPageFile) + { + # First Disable Automatic Managed Page File + Set-AutoManagePaging -State Disable + } + + $driveInfo = Get-DriveInfo -Drive $Drive + + $existingPageFileSetting = Get-PageFileSetting ` + -Drive $($driveInfo.Name.Substring(0,2)) + + if (-not $existingPageFileSetting) + { + $pageFileName = Join-Path ` + -Path $driveInfo.Name ` + -ChildPath 'pagefile.sys' + + New-PageFile -PageFileName $pageFileName + } + + Set-PageFileSetting ` + -Drive $driveInfo.Name.Substring(0,2) + + $global:DSCMachineStatus = 1 + + Write-Verbose -Message ($script:localizedData.EnabledSystemManagedSizeMessage -f $Drive) + + break + } + + 'NoPagingFile' + { + if ($systemInfo.AutomaticManagedPageFile) + { + # First Disable Automatic Managed Page File + Set-AutoManagePaging -State Disable + } + + $driveInfo = Get-DriveInfo -Drive $Drive + + $existingPageFileSetting = Get-PageFileSetting ` + -Drive $($driveInfo.Name.Substring(0,2)) + + if ($existingPageFileSetting) + { + Write-Verbose -Message ($script:localizedData.RemovePageFileMessage -f $existingPageFileSetting.Name) + + $null = Remove-CimInstance ` + -InputObject $existingPageFileSetting + + $global:DSCMachineStatus = 1 + } + + Write-Verbose -Message ($script:localizedData.DisabledPageFileMessage -f $Drive) + + break + } + } +} + +<# + .SYNOPSIS + Tests if virtual memory settings need to be applied based on the parameters supplied + + .PARAMETER Drive + The drive letter that should be tested + + .PARAMETER Type + The type of the virtual memory configuration + + .PARAMETER InitialSize + The initial page file size in megabyte + + .PARAMETER MaximumSize + The maximum page file size in megabyte +#> +function Test-TargetResource +{ + [CmdletBinding()] + [OutputType([System.Boolean])] + param + ( + [Parameter(Mandatory = $true)] + [System.String] + $Drive, + + [Parameter(Mandatory = $true)] + [ValidateSet('AutoManagePagingFile', 'CustomSize', 'SystemManagedSize', 'NoPagingFile')] + [System.String] + $Type, + + [Parameter()] + [System.Int64] + $InitialSize, + + [Parameter()] + [System.Int64] + $MaximumSize + ) + + Write-Verbose -Message ($script:localizedData.TestingVirtualMemoryMessage) + + $systemInfo = Get-CimInstance -ClassName 'Win32_ComputerSystem' + $inDesiredState = $false + + switch ($Type) + { + 'AutoManagePagingFile' + { + $inDesiredState = $systemInfo.AutomaticManagedPagefile + break + } + + 'CustomSize' + { + if ($systemInfo.AutomaticManagedPageFile) + { + break + } + + $driveInfo = [System.IO.DriveInfo] $Drive + + $existingPageFileSetting = Get-PageFileSetting ` + -Drive $($driveInfo.Name.Substring(0,2)) + + if (-not $existingPageFileSetting) + { + break + } + + if (-not ($existingPageFileSetting.InitialSize -eq $InitialSize -and $existingPageFileSetting.MaximumSize -eq $MaximumSize)) + { + break + } + + $inDesiredState = $true + break + } + + 'SystemManagedSize' + { + if ($systemInfo.AutomaticManagedPageFile) + { + break + } + + $driveInfo = [System.IO.DriveInfo] $Drive + + $existingPageFileSetting = Get-PageFileSetting ` + -Drive $($driveInfo.Name.Substring(0,2)) + + if (-not $existingPageFileSetting) + { + break + } + + if (-not ($existingPageFileSetting.InitialSize -eq 0 -and $existingPageFileSetting.MaximumSize -eq 0)) + { + break + } + + $inDesiredState = $true + break + } + + 'NoPagingFile' + { + if ($systemInfo.AutomaticManagedPageFile) + { + break + } + + $driveInfo = [System.IO.DriveInfo] $Drive + + $existingPageFileSetting = Get-PageFileSetting ` + -Drive $($driveInfo.Name.Substring(0,2)) + + if ($existingPageFileSetting) + { + break + } + + $inDesiredState = $true + break + } + } + + return $inDesiredState +} + +<# + .SYNOPSIS + Gets the settings for a page file assigned to a Drive. + + .PARAMETER State + The drive letter for the page file to return the settings of. +#> +function Get-PageFileSetting +{ + [CmdletBinding()] + param + ( + [Parameter(Mandatory = $true)] + [System.String] + $Drive + ) + + Write-Verbose -Message ($script:localizedData.GettingPageFileSettingsMessage -f $Drive) + + # Find existing page file settings by drive letter + return Get-CimInstance ` + -ClassName 'Win32_PageFileSetting' ` + -Filter "SettingID='pagefile.sys @ $Drive'" +} + +<# + .SYNOPSIS + Sets a new page file name. + + .PARAMETER Drive + The letter of the drive containing the page file + to change the settings of. + + .PARAMETER InitialSize + The initial size to set the page file to. + + .PARAMETER MaximumSize + The maximum size to set the page file to. +#> +function Set-PageFileSetting +{ + [CmdletBinding()] + param + ( + [Parameter(Mandatory = $true)] + [System.String] + $Drive, + + [Parameter()] + [System.Int64] + $InitialSize = 0, + + [Parameter()] + [System.Int64] + $MaximumSize = 0 + ) + + $setParams = @{ + Namespace = 'root\cimv2' + Query = "Select * from Win32_PageFileSetting where SettingID='pagefile.sys @ $Drive'" + Property = @{ + InitialSize = $InitialSize + MaximumSize = $MaximumSize + } + } + + Write-Verbose -Message ($script:localizedData.SettingPageFileSettingsMessage -f $Drive, $InitialSize, $MaximumSize) + + $null = Set-CimInstance @setParams +} + +<# + .SYNOPSIS + Enables or Disables Automatically Managed Paging. + + .PARAMETER State + Specifies if Automatically Managed Paging is enabled + or disabled. +#> +function Set-AutoManagePaging +{ + [CmdletBinding()] + param + ( + [Parameter(Mandatory = $true)] + [ValidateSet('Enable', 'Disable')] + [System.String] + $State + ) + + $setParams = @{ + Namespace = 'root\cimv2' + Query = 'Select * from Win32_ComputerSystem' + Property = @{ + AutomaticManagedPageFile = ($State -eq 'Enable') + } + } + + Write-Verbose -Message ($script:localizedData.SetAutoManagePagingMessage -f $State) + + $null = Set-CimInstance @setParams +} + +<# + .SYNOPSIS + Sets a new page file name. + + .PARAMETER PageFileName + The name of the new page file. +#> +function New-PageFile +{ + [CmdletBinding()] + param + ( + [Parameter(Mandatory = $true)] + [System.String] + $PageFileName + ) + + Write-Verbose -Message ($script:localizedData.NewPageFileMessage -f $State) + + $null = New-CimInstance ` + -Namespace 'root\cimv2' ` + -ClassName 'Win32_PageFileSetting' ` + -Property @{ + Name = $PageFileName + } +} + +<# + .SYNOPSIS + Gets the Drive info object for a specified + Drive. It will throw an exception if the drive + is invalid or does not exist. + + .PARAMETER Drive + The letter of the drive to get the drive info + for. +#> +function Get-DriveInfo +{ + [CmdletBinding()] + [OutputType([System.IO.DriveInfo])] + param + ( + [Parameter(Mandatory = $true)] + [System.String] + $Drive + ) + + $driveInfo = [System.IO.DriveInfo] $Drive + + if (-not $driveInfo.IsReady) + { + New-InvalidOperationException ` + -Message ($script:localizedData.DriveNotReadyError -f $driveInfo.Name) + } + + return $driveInfo +} + +Export-ModuleMember -Function *-TargetResource diff --git a/DSCResources/MSFT_xVirtualMemory/MSFT_xVirtualMemory.schema.mof b/Modules/xComputerManagement/DSCResources/MSFT_xVirtualMemory/MSFT_xVirtualMemory.schema.mof similarity index 98% rename from DSCResources/MSFT_xVirtualMemory/MSFT_xVirtualMemory.schema.mof rename to Modules/xComputerManagement/DSCResources/MSFT_xVirtualMemory/MSFT_xVirtualMemory.schema.mof index 38651f9d..6e66732e 100644 --- a/DSCResources/MSFT_xVirtualMemory/MSFT_xVirtualMemory.schema.mof +++ b/Modules/xComputerManagement/DSCResources/MSFT_xVirtualMemory/MSFT_xVirtualMemory.schema.mof @@ -1,10 +1,10 @@ - -[ClassVersion("1.0.0.0"), FriendlyName("xVirtualMemory")] -class MSFT_xVirtualMemory : OMI_BaseResource -{ - [Key, Description("The drive letter for which paging settings should be set. Can be letter only, letter and colon or letter with colon and trailing slash.")] String Drive; - [Key, Description("The type of the paging setting to use. If set to AutoManagePagingFile, the drive letter will be ignored. If set to SystemManagedSize, the values for InitialSize and MaximumSize will be ignored"), ValueMap{"AutoManagePagingFile","CustomSize","SystemManagedSize","NoPagingFile"}, Values{"AutoManagePagingFile","CustomSize","SystemManagedSize","NoPagingFile"}] String Type; - [Write, Description("The initial size of the page file in Megabyte")] Sint64 InitialSize; - [Write, Description("The maximum size of the page file in Megabyte")] Sint64 MaximumSize; -}; - + +[ClassVersion("1.0.0.0"), FriendlyName("xVirtualMemory")] +class MSFT_xVirtualMemory : OMI_BaseResource +{ + [Key, Description("The drive letter for which paging settings should be set. Can be letter only, letter and colon or letter with colon and trailing slash.")] String Drive; + [Key, Description("The type of the paging setting to use. If set to AutoManagePagingFile, the drive letter will be ignored. If set to SystemManagedSize, the values for InitialSize and MaximumSize will be ignored"), ValueMap{"AutoManagePagingFile","CustomSize","SystemManagedSize","NoPagingFile"}, Values{"AutoManagePagingFile","CustomSize","SystemManagedSize","NoPagingFile"}] String Type; + [Write, Description("The initial size of the page file in Megabyte")] Sint64 InitialSize; + [Write, Description("The maximum size of the page file in Megabyte")] Sint64 MaximumSize; +}; + diff --git a/Modules/xComputerManagement/DSCResources/MSFT_xVirtualMemory/README.md b/Modules/xComputerManagement/DSCResources/MSFT_xVirtualMemory/README.md new file mode 100644 index 00000000..0bdd7fd7 --- /dev/null +++ b/Modules/xComputerManagement/DSCResources/MSFT_xVirtualMemory/README.md @@ -0,0 +1,4 @@ +# Description + +The resource allows configuration of properties of the paging file on +the local computer. diff --git a/DSCResources/MSFT_xVirtualMemory/en-US/MSFT_xVirtualMemory.strings.psd1 b/Modules/xComputerManagement/DSCResources/MSFT_xVirtualMemory/en-US/MSFT_xVirtualMemory.strings.psd1 similarity index 100% rename from DSCResources/MSFT_xVirtualMemory/en-US/MSFT_xVirtualMemory.strings.psd1 rename to Modules/xComputerManagement/DSCResources/MSFT_xVirtualMemory/en-US/MSFT_xVirtualMemory.strings.psd1 diff --git a/Examples/xComputer/1-RenameComputerAndSetWorkgroup.ps1 b/Modules/xComputerManagement/Examples/Resources/xComputer/1-RenameComputerAndSetWorkgroup.ps1 similarity index 100% rename from Examples/xComputer/1-RenameComputerAndSetWorkgroup.ps1 rename to Modules/xComputerManagement/Examples/Resources/xComputer/1-RenameComputerAndSetWorkgroup.ps1 diff --git a/Examples/xComputer/2-JoinDomain.ps1 b/Modules/xComputerManagement/Examples/Resources/xComputer/2-JoinDomain.ps1 similarity index 100% rename from Examples/xComputer/2-JoinDomain.ps1 rename to Modules/xComputerManagement/Examples/Resources/xComputer/2-JoinDomain.ps1 diff --git a/Examples/xComputer/3-RenameComputerInDomain.ps1 b/Modules/xComputerManagement/Examples/Resources/xComputer/3-RenameComputerInDomain.ps1 similarity index 100% rename from Examples/xComputer/3-RenameComputerInDomain.ps1 rename to Modules/xComputerManagement/Examples/Resources/xComputer/3-RenameComputerInDomain.ps1 diff --git a/Examples/xComputer/4-RenameComputerInWorkgroup.ps1 b/Modules/xComputerManagement/Examples/Resources/xComputer/4-RenameComputerInWorkgroup.ps1 similarity index 100% rename from Examples/xComputer/4-RenameComputerInWorkgroup.ps1 rename to Modules/xComputerManagement/Examples/Resources/xComputer/4-RenameComputerInWorkgroup.ps1 diff --git a/Examples/xComputer/5-UnjoinDomainAndJoinWorkgroup.ps1 b/Modules/xComputerManagement/Examples/Resources/xComputer/5-UnjoinDomainAndJoinWorkgroup.ps1 similarity index 100% rename from Examples/xComputer/5-UnjoinDomainAndJoinWorkgroup.ps1 rename to Modules/xComputerManagement/Examples/Resources/xComputer/5-UnjoinDomainAndJoinWorkgroup.ps1 diff --git a/Examples/xComputer/6-SetComputerDescriptionInWorkgroup.ps1 b/Modules/xComputerManagement/Examples/Resources/xComputer/6-SetComputerDescriptionInWorkgroup.ps1 similarity index 100% rename from Examples/xComputer/6-SetComputerDescriptionInWorkgroup.ps1 rename to Modules/xComputerManagement/Examples/Resources/xComputer/6-SetComputerDescriptionInWorkgroup.ps1 diff --git a/Examples/xOfflineDomainJoin/1-JoinDomainUsingODJBlob.ps1 b/Modules/xComputerManagement/Examples/Resources/xOfflineDomainJoin/1-JoinDomainUsingODJBlob.ps1 similarity index 100% rename from Examples/xOfflineDomainJoin/1-JoinDomainUsingODJBlob.ps1 rename to Modules/xComputerManagement/Examples/Resources/xOfflineDomainJoin/1-JoinDomainUsingODJBlob.ps1 diff --git a/Examples/xPowerPlan/1-SetPowerPlan.ps1 b/Modules/xComputerManagement/Examples/Resources/xPowerPlan/1-SetPowerPlan.ps1 similarity index 100% rename from Examples/xPowerPlan/1-SetPowerPlan.ps1 rename to Modules/xComputerManagement/Examples/Resources/xPowerPlan/1-SetPowerPlan.ps1 diff --git a/Examples/xScheduledTask/1-CreateScheduledTaskOnce.ps1 b/Modules/xComputerManagement/Examples/Resources/xScheduledTask/1-CreateScheduledTaskOnce.ps1 similarity index 100% rename from Examples/xScheduledTask/1-CreateScheduledTaskOnce.ps1 rename to Modules/xComputerManagement/Examples/Resources/xScheduledTask/1-CreateScheduledTaskOnce.ps1 diff --git a/Examples/xScheduledTask/10-RunPowerShellTaskOnceAsUserInteractiveOnly.ps1 b/Modules/xComputerManagement/Examples/Resources/xScheduledTask/10-RunPowerShellTaskOnceAsUserInteractiveOnly.ps1 similarity index 100% rename from Examples/xScheduledTask/10-RunPowerShellTaskOnceAsUserInteractiveOnly.ps1 rename to Modules/xComputerManagement/Examples/Resources/xScheduledTask/10-RunPowerShellTaskOnceAsUserInteractiveOnly.ps1 diff --git a/Modules/xComputerManagement/Examples/Resources/xScheduledTask/11-DisableABuiltInTask.ps1 b/Modules/xComputerManagement/Examples/Resources/xScheduledTask/11-DisableABuiltInTask.ps1 new file mode 100644 index 00000000..9c8f203f --- /dev/null +++ b/Modules/xComputerManagement/Examples/Resources/xScheduledTask/11-DisableABuiltInTask.ps1 @@ -0,0 +1,26 @@ +<# + .EXAMPLE + This example disables the built-in scheduled task called + 'CreateExplorerShellUnelevatedTask'. +#> +Configuration Example +{ + param + ( + [Parameter()] + [System.String[]] + $NodeName = 'localhost' + ) + + Import-DscResource -ModuleName xComputerManagement + + Node $NodeName + { + xScheduledTask DisableCreateExplorerShellUnelevatedTask + { + TaskName = 'CreateExplorerShellUnelevatedTask' + TaskPath = '\' + Enable = $false + } + } +} diff --git a/Modules/xComputerManagement/Examples/Resources/xScheduledTask/12-DeleteABuiltInTask.ps1 b/Modules/xComputerManagement/Examples/Resources/xScheduledTask/12-DeleteABuiltInTask.ps1 new file mode 100644 index 00000000..f520f563 --- /dev/null +++ b/Modules/xComputerManagement/Examples/Resources/xScheduledTask/12-DeleteABuiltInTask.ps1 @@ -0,0 +1,26 @@ +<# + .EXAMPLE + This example deletes the built-in scheduled task called + 'CreateExplorerShellUnelevatedTask'. +#> +Configuration Example +{ + param + ( + [Parameter()] + [System.String[]] + $NodeName = 'localhost' + ) + + Import-DscResource -ModuleName xComputerManagement + + Node $NodeName + { + xScheduledTask DeleteCreateExplorerShellUnelevatedTask + { + TaskName = 'CreateExplorerShellUnelevatedTask' + TaskPath = '\' + Ensure = 'Absent' + } + } +} diff --git a/Examples/xScheduledTask/2-CreateScheduledTaskDaily.ps1 b/Modules/xComputerManagement/Examples/Resources/xScheduledTask/2-CreateScheduledTaskDaily.ps1 similarity index 100% rename from Examples/xScheduledTask/2-CreateScheduledTaskDaily.ps1 rename to Modules/xComputerManagement/Examples/Resources/xScheduledTask/2-CreateScheduledTaskDaily.ps1 diff --git a/Examples/xScheduledTask/3-CreateScheduledTasksDailyIndefinitely.ps1 b/Modules/xComputerManagement/Examples/Resources/xScheduledTask/3-CreateScheduledTasksDailyIndefinitely.ps1 similarity index 100% rename from Examples/xScheduledTask/3-CreateScheduledTasksDailyIndefinitely.ps1 rename to Modules/xComputerManagement/Examples/Resources/xScheduledTask/3-CreateScheduledTasksDailyIndefinitely.ps1 diff --git a/Examples/xScheduledTask/4-CreateScheduledTasksWeekly.ps1 b/Modules/xComputerManagement/Examples/Resources/xScheduledTask/4-CreateScheduledTasksWeekly.ps1 similarity index 100% rename from Examples/xScheduledTask/4-CreateScheduledTasksWeekly.ps1 rename to Modules/xComputerManagement/Examples/Resources/xScheduledTask/4-CreateScheduledTasksWeekly.ps1 diff --git a/Examples/xScheduledTask/5-CreateScheduledTasksAtLogon.ps1 b/Modules/xComputerManagement/Examples/Resources/xScheduledTask/5-CreateScheduledTasksAtLogon.ps1 similarity index 100% rename from Examples/xScheduledTask/5-CreateScheduledTasksAtLogon.ps1 rename to Modules/xComputerManagement/Examples/Resources/xScheduledTask/5-CreateScheduledTasksAtLogon.ps1 diff --git a/Examples/xScheduledTask/6-CreateScheduledTasksAtStartup.ps1 b/Modules/xComputerManagement/Examples/Resources/xScheduledTask/6-CreateScheduledTasksAtStartup.ps1 similarity index 100% rename from Examples/xScheduledTask/6-CreateScheduledTasksAtStartup.ps1 rename to Modules/xComputerManagement/Examples/Resources/xScheduledTask/6-CreateScheduledTasksAtStartup.ps1 diff --git a/Examples/xScheduledTask/7-RunPowerShellTaskEvery15Minutes.ps1 b/Modules/xComputerManagement/Examples/Resources/xScheduledTask/7-RunPowerShellTaskEvery15Minutes.ps1 similarity index 100% rename from Examples/xScheduledTask/7-RunPowerShellTaskEvery15Minutes.ps1 rename to Modules/xComputerManagement/Examples/Resources/xScheduledTask/7-RunPowerShellTaskEvery15Minutes.ps1 diff --git a/Examples/xScheduledTask/8-RunPowerShellTaskEvery15MinutesIndefinitely.ps1 b/Modules/xComputerManagement/Examples/Resources/xScheduledTask/8-RunPowerShellTaskEvery15MinutesIndefinitely.ps1 similarity index 100% rename from Examples/xScheduledTask/8-RunPowerShellTaskEvery15MinutesIndefinitely.ps1 rename to Modules/xComputerManagement/Examples/Resources/xScheduledTask/8-RunPowerShellTaskEvery15MinutesIndefinitely.ps1 diff --git a/Examples/xScheduledTask/9-RunPowerShellTaskOnceAsUserWithHighestPriveleges.ps1 b/Modules/xComputerManagement/Examples/Resources/xScheduledTask/9-RunPowerShellTaskOnceAsUserWithHighestPriveleges.ps1 similarity index 100% rename from Examples/xScheduledTask/9-RunPowerShellTaskOnceAsUserWithHighestPriveleges.ps1 rename to Modules/xComputerManagement/Examples/Resources/xScheduledTask/9-RunPowerShellTaskOnceAsUserWithHighestPriveleges.ps1 diff --git a/Examples/xVirtualMemory/1-SetVirtualMemory.ps1 b/Modules/xComputerManagement/Examples/Resources/xVirtualMemory/1-SetVirtualMemory.ps1 similarity index 100% rename from Examples/xVirtualMemory/1-SetVirtualMemory.ps1 rename to Modules/xComputerManagement/Examples/Resources/xVirtualMemory/1-SetVirtualMemory.ps1 diff --git a/Modules/ComputerManagementDsc.Common/ComputerManagementDsc.Common.psm1 b/Modules/xComputerManagement/Modules/ComputerManagementDsc.Common/ComputerManagementDsc.Common.psm1 similarity index 100% rename from Modules/ComputerManagementDsc.Common/ComputerManagementDsc.Common.psm1 rename to Modules/xComputerManagement/Modules/ComputerManagementDsc.Common/ComputerManagementDsc.Common.psm1 diff --git a/Modules/ComputerManagementDsc.Common/en-us/ComputerManagementDsc.Common.strings.psd1 b/Modules/xComputerManagement/Modules/ComputerManagementDsc.Common/en-us/ComputerManagementDsc.Common.strings.psd1 similarity index 100% rename from Modules/ComputerManagementDsc.Common/en-us/ComputerManagementDsc.Common.strings.psd1 rename to Modules/xComputerManagement/Modules/ComputerManagementDsc.Common/en-us/ComputerManagementDsc.Common.strings.psd1 diff --git a/Modules/ComputerManagementDsc.ResourceHelper/ComputerManagementDsc.ResourceHelper.psm1 b/Modules/xComputerManagement/Modules/ComputerManagementDsc.ResourceHelper/ComputerManagementDsc.ResourceHelper.psm1 similarity index 100% rename from Modules/ComputerManagementDsc.ResourceHelper/ComputerManagementDsc.ResourceHelper.psm1 rename to Modules/xComputerManagement/Modules/ComputerManagementDsc.ResourceHelper/ComputerManagementDsc.ResourceHelper.psm1 diff --git a/xComputerManagement.psd1 b/Modules/xComputerManagement/xComputerManagement.psd1 similarity index 66% rename from xComputerManagement.psd1 rename to Modules/xComputerManagement/xComputerManagement.psd1 index b409dd1f..9ee3b6bd 100644 --- a/xComputerManagement.psd1 +++ b/Modules/xComputerManagement/xComputerManagement.psd1 @@ -1,6 +1,6 @@ @{ # Version number of this module. -ModuleVersion = '3.2.0.0' +ModuleVersion = '4.0.0.0' # ID used to uniquely identify this module GUID = 'B5004952-489E-43EA-999C-F16A25355B89' @@ -49,18 +49,22 @@ PrivateData = @{ # IconUri = '' # ReleaseNotes of this module - ReleaseNotes = '* xScheduledTask: - * Enable Execution Time Limit of task to be set to indefinite - by setting `ExecutionTimeLimit` to "00:00:00" - See [Issue 115](https://github.com/PowerShell/xComputerManagement/issues/115) -* xPowerPlan: - * Updated to meet HQRM guidelines. - * Converted calls to `throw` to use `New-InvalidOperationException` - in CommonResourceHelper. -* Move Common Resource Helper functions into modules folder. -* Changed resources to use Common Resource Helper functions. -* Moved strings for Common Resource Helper functions into separate - strings file. -* Added unit tests for Common Helper functions. + ReleaseNotes = '- BREAKING CHANGE: xScheduledTask: + - Breaking change because `Get-TargetResource` no longer outputs + `ActionExecutable` and `ScheduleType` properties when the scheduled + task does not exist. It will also include `TaskPath` in output when + scheduled task does not exist. +- xScheduledTask: + - Add support to disable built-in scheduled tasks - See [Issue 74](https://github.com/PowerShell/xComputerManagement/issues/74). + - Fix unit test mocked schedule task object structure. + - Fix error message when trigger type is unknown - See [Issue 121](https://github.com/PowerShell/xComputerManagement/issues/121). + - Moved strings into separate strings file. + - Updated to meet HQRM guidelines. +- xComputer: + - Resolved bug in Get-ComputerDomain where LocalSystem doesn"t have + rights to the domain. +- Updated tests to meet Pester V4 guidelines - See [Issue 106](https://github.com/PowerShell/xComputerManagement/issues/106). +- Converted module to use auto documentation format. ' @@ -77,3 +81,4 @@ PrivateData = @{ + diff --git a/README.md b/README.md index 39e7fdff..8738501c 100644 --- a/README.md +++ b/README.md @@ -2,22 +2,28 @@ The **xComputerManagement** module contains the following resources: -* xComputer - allows you to configure a computer by changing its name and - modifying its domain or workgroup. -* xOfflineDomainJoin - allows you to join computers to an AD Domain using - an [Offline Domain Join](https://technet.microsoft.com/en-us/library/offline-domain-join-djoin-step-by-step(v=ws.10).aspx) +- **xComputer**: allows you to configure a computer by changing its name and + description and modifying its Active Directory domain or workgroup membership. +- **xOfflineDomainJoin**: allows you to join computers to an Active Directory + domain using an [Offline Domain Join](https://technet.microsoft.com/en-us/library/offline-domain-join-djoin-step-by-step(v=ws.10).aspx) request file. -* xScheduledTask - used to define basic recurring scheduled tasks on the - local computer. -* xPowerPlan - specifies a power plan to activate. -* xVirtualMemory - used to set the properties of the paging file on the - local computer. +- **xPowerPlan**: allows specifying a power plan to activate. +- **xScheduledTask**: is used to define basic run once or recurring scheduled tasks + on the local computer. It can also be used to delete or disable built-in + scheduled tasks. +- **xVirtualMemory**: allows configuration of properties of the paging file on + the local computer. This project has adopted the [Microsoft Open Source Code of Conduct](https://opensource.microsoft.com/codeofconduct/). For more information see the [Code of Conduct FAQ](https://opensource.microsoft.com/codeofconduct/faq/) or contact [opencode@microsoft.com](mailto:opencode@microsoft.com) with any additional questions or comments. +## Documentation and Examples + +For a full list of resources in xComputerManagement and examples on their use, check +out the [xComputerManagement wiki](https://github.com/PowerShell/xComputerManagement/wiki). + ## Branches ### master @@ -40,338 +46,3 @@ branch, and be released to [PowerShell Gallery](https://www.powershellgallery.co ## Contributing Please check out common DSC Resources [contributing guidelines](https://github.com/PowerShell/DscResource.Kit/blob/master/CONTRIBUTING.md). - -## xComputer - -xComputer resource has following properties: - -* Name: The desired computer name. -* DomainName: The name of the domain to join. -* JoinOU: The distinguished name of the organizational unit that the computer - account will be created in. -* WorkGroupName: The name of the workgroup. -* Credential: Credential to be used to join a domain. -* UnjoinCredential: Credential to be used to leave a domain. -* CurrentOU: A read-only property that specifies the organizational unit that - the computer account is currently in. -* Description: The value assigned here will be set as the local computer description. - -### xComputer Examples - -* [Set the Name and the Workgroup Name](/Examples/xComputer/1-RenameComputerAndSetWorkgroup.ps1) -* [Switch from a Workgroup to a Domain](/Examples/xComputer/2-JoinDomain.ps1) -* [Set the Name while staying on the Domain](/Examples/xComputer/3-RenameComputerInDomain.ps1) -* [Set the Name while staying on the Workgroup](/Examples/xComputer/4-RenameComputerInWorkgroup.ps1) -* [Switch from a Domain to a Workgroup](/Examples/xComputer/5-UnjoinDomainAndJoinWorkgroup.ps1) -* [Set a Description for the Workstation](/Examples/xComputer/6-SetComputerDescriptionInWorkgroup.ps1) - -## xOfflineDomainJoin - -xOfflineDomainJoin resource is a [Single Instance](https://msdn.microsoft.com/en-us/powershell/dsc/singleinstance) -resource that can only be used once in a configuration and has following properties: - -* IsSingleInstance: Must be set to 'Yes'. Required. -* RequestFile: The full path to the Offline Domain Join request file. Required. - -### xOfflineDomainJoin Examples - -* [Join a Domain using an ODJ Request File](/Examples/xOfflineDomainJoin/1-JoinDomainUsingODJBlob.ps1) - -## xScheduledTask - -xScheduledTask resource is used to define basic recurring scheduled tasks on the -local computer. -Tasks are created to run based on the schedule defined. -xScheduledTask has the following properties: - -* TaskName: The name of the task -* TaskPath: The path to the task - defaults to the root directory -* Description: The task description -* ActionExecutable: The path to the .exe for this task -* ActionArguments: The arguments to pass the executable -* ActionWorkingPath: The working path to specify for the executable -* ScheduleType: When should the task be executed - ("Once", "Daily", "Weekly", "AtStartup", "AtLogOn") -* RepeatInterval: How many units (minutes, hours, days) between each run of this - task? -* StartTime: The time of day this task should start at - defaults to 12:00 AM. - Not valid for AtLogon and AtStartup tasks -* Ensure: Present if the task should exist, false if it should be removed - defaults - to Present. -* Enable: True if the task should be enabled, false if it should be - disabled -* ExecuteAsCredential: The credential this task should execute as. If not - specified defaults to running as the local system account -* DaysInterval: Specifies the interval between the days in the schedule. An - interval of 1 produces a daily schedule. An interval of 2 produces an - every-other day schedule. -* RandomDelay: Specifies a random amount of time to delay the start time of the - trigger. The delay time is a random time between the time the task triggers - and the time that you specify in this setting. -* RepetitionDuration: Specifies how long the repetition pattern repeats after - the task starts. May be set to `Indefinitely` to specify an indefinite duration. -* DaysOfWeek: Specifies an array of the days of the week on which Task Scheduler - runs the task. -* WeeksInterval: Specifies the interval between the weeks in the schedule. An - interval of 1 produces a weekly schedule. An interval of 2 produces an - every-other week schedule. -* User: Specifies the identifier of the user for a trigger that starts a task - when a user logs on. -* DisallowDemandStart: Indicates whether the task is prohibited to run on demand - or not. Defaults to $false -* DisallowHardTerminate: Indicates whether the task is prohibited to be terminated - or not. Defaults to $false -* Compatibility: The task compatibility level. Defaults to Vista. Possible - values: "AT","V1","Vista","Win7","Win8" -* AllowStartIfOnBatteries: Indicates whether the task should start if the machine - is on batteries or not. Defaults to $false -* Hidden: Indicates that the task is hidden in the Task Scheduler UI. Defaults - to $false -* RunOnlyIfIdle: Indicates that Task Scheduler runs the task only when the - computer is idle. -* IdleWaitTimeout: Specifies the amount of time that Task Scheduler waits for an - idle condition to occur. DateTime ; -* NetworkName: Specifies the name of a network profile that Task Scheduler uses - to determine if the task can run. The Task Scheduler UI uses this setting for - display purposes. Specify a network name if you specify theRunOnlyIfNetworkAvailable - parameter. -* DisallowStartOnRemoteAppSession: Indicates that the task does not start if the - task is triggered to run in a Remote Applications Integrated Locally (RAIL) session. -* StartWhenAvailable: Indicates that Task Scheduler can start the task at any - time after its scheduled time has passed. -* DontStopIfGoingOnBatteries: Indicates that the task does not stop if the - computer switches to battery power. -* WakeToRun: Indicates that Task Scheduler wakes the computer before it runs the - task. -* IdleDuration: Specifies the amount of time that the computer must be in an idle - state before Task Scheduler runs the task. -* RestartOnIdle: Indicates that Task Scheduler restarts the task when the computer - cycles into an idle condition more than once. -* DontStopOnIdleEnd: Indicates that Task Scheduler does not terminate the task if - the idle condition ends before the task is completed. -* ExecutionTimeLimit: Specifies the amount of time that Task Scheduler is allowed - to complete the task. -* MultipleInstances: Specifies the policy that defines how Task Scheduler handles - multiple instances of the task. Possible values: "IgnoreNew","Parallel","Queue" -* Priority: Specifies the priority level of the task. Priority must be an integer - from 0 (highest priority) to 10 (lowest priority). The default value is 7. - Priority levels 7 and 8 are used for background tasks. Priority levels 4, 5, - and 6 are used for interactive tasks. -* RestartCount: Specifies the number of times that Task Scheduler attempts to - restart the task. -* RestartInterval: Specifies the amount of time that Task Scheduler attempts to - restart the task. -* RunOnlyIfNetworkAvailable: Indicates that Task Scheduler runs the task only - when a network is available. Task Scheduler uses the NetworkID parameter and - NetworkName parameter that you specify in this cmdlet to determine if the - network is available. -* RunLevel: Specifies the level of user rights that Task Scheduler uses to run the - tasks that are associated with the principal. Defaults to 'Limited'. -* LogonType: Specifies the security logon method that Task Scheduler uses to run - the tasks that are associated with the principal. - -### xScheduledTask Examples - -* [Create a task that starts PowerShell once every 15 minutes from 00:00 for 8 hours](/Examples/xScheduledTask/1-CreateScheduledTaskOnce.ps1) -* [Create a task that starts PowerShell daily every 15 minutes from 00:00 for 8 hours](/Examples/xScheduledTask/2-CreateScheduledTaskDaily.ps1) -* [Create a task that starts PowerShell daily every 15 minutes from 00:00 indefinitely](/Examples/xScheduledTask/3-CreateScheduledTasksDailyIndefinitely.ps1) -* [Create a task that starts PowerShell weekly on Monday, Wednesday and Saturday every 15 minutes from 00:00 for 8 hours](/Examples/xScheduledTask/4-CreateScheduledTasksWeekly.ps1) -* [Create a task that starts PowerShell at logon and runs every 15 minutes from 00:00 for 8 hours](/Examples/xScheduledTask/5-CreateScheduledTasksAtLogon.ps1) -* [Create a task that starts PowerShell at startup and runs every 15 minutes from 00:00 for 8 hours](/Examples/xScheduledTask/6-CreateScheduledTasksAtStartup.ps1) -* [Run a PowerShell script every 15 minutes for 4 days on a server](/Examples/xScheduledTask/7-RunPowerShellTaskEvery15Minutes.ps1) -* [Run a PowerShell script every 15 minutes indefinitely on a server](/Examples/xScheduledTask/8-RunPowerShellTaskEvery15MinutesIndefinitely.ps1) -* [Run a PowerShell script once as a specified user with highest privileges](/Examples/xScheduledTask/9-RunPowerShellTaskOnceAsUserWithHighestPriveleges.ps1) -* [Run a PowerShell script once as a specified user only when the user is logged on](/Examples/xScheduledTask/10-RunPowerShellTaskOnceAsUserInteractiveOnly.ps1) - -## xPowerPlan - -xPowerPlan resource has following properties: - -* IsSingleInstance: Specifies the resource is a single instance, the value must - be 'Yes'. -* Name: The name of the power plan to activate. - -### xPowerPlan Examples - -* [Sets Active Power Plan to the High Performance plan](/Examples/xPowerPlan/1-SetPowerPlan.ps1) - -## xVirtualMemory - -xVirtualMemory resource is used to set the properties of the paging file on the -local computer. -xVirtualMemory has the following properties: - -* Type: The type of the paging settings, mandatory, out of "AutoManagePagingFile", - "CustomSize","SystemManagedSize","NoPagingFile" -* Drive: The drive to enable paging on, mandatory. Ignored for "AutoManagePagingFile" -* InitialSize: The initial size in MB of the paging file. Ignored for Type - "AutoManagePagingFile" and "SystemManagedSize" -* MaximumSize: The maximum size in MB of the paging file. Ignored for Type - "AutoManagePagingFile" and "SystemManagedSize" - -### xVirtualMemory Examples - -* [Set Page File to be 2GB on C Drive](/Examples/xVirtualMemory/1-SetVirtualMemory.ps1) - -## Versions - -### Unreleased - -### 3.2.0.0 - -* xScheduledTask: - * Enable Execution Time Limit of task to be set to indefinite - by setting `ExecutionTimeLimit` to '00:00:00' - See [Issue #115](https://github.com/PowerShell/xComputerManagement/issues/115) -* xPowerPlan: - * Updated to meet HQRM guidelines. - * Converted calls to `throw` to use `New-InvalidOperationException` - in CommonResourceHelper. -* Move Common Resource Helper functions into modules folder. -* Changed resources to use Common Resource Helper functions. -* Moved strings for Common Resource Helper functions into separate - strings file. -* Added unit tests for Common Helper functions. - -### 3.1.0.0 - -* xOfflineDomainJoin: - * Updated to meet HQRM guidelines. -* xScheduledTask: - * Applied autoformatting to examples to improve readability. - * Added LogonType and RunLevel parameters for controlling - task execution. - * Correct `Assert-VerifiableMocks` to `Assert-VerifiableMock` - -### 3.0.0.0 - -* xComputer: Added parameter to set the local computer description along with documentation - and unit tests for this change. -* BREAKING CHANGE: xScheduledTask: - * Converted all Interval/Duration type parameters over to be string format - to prevent the Timezone the MOF file was created in from being stored. - This is to fix problems where MOF files are created in one timezone but - deployed nodes to a different timezone - See [Issue #85](https://github.com/PowerShell/xComputerManagement/issues/85) - * Added ConvertTo-TimeSpanFromScheduledTaskString function and refactored - to reduce code duplication. - * Added support for setting repetition duration to `Indefinitely`. -* xComputer: - * Moved strings to localization file. - * Updated to meet HQRM guidelines. -* xVirtualMemory: - * Refactored shared common code into new utility functions to - reduce code duplication and improve testability. - * Moved strings into localizable strings file. - * Converted calls to `throw` to use `New-InvalidOperationException` - in CommonResourceHelper. - * Improved unit test coverage. - * Updated to meet HQRM guidelines. - -### 2.1.0.0 - -* xComputer: Changed comparison that validates if we are in the correct AD - Domain to work correctly if FQDN wasn't used. -* Updated AppVeyor.yml to use AppVeyor.psm1 module in DSCResource.Tests. -* Removed Markdown.md errors. -* Added CodeCov.io support. -* xScheduledTask - * Fixed incorrect TaskPath handling - [Issue #45](https://github.com/PowerShell/xComputerManagement/issues/45) -* Change examples to meet HQRM standards and optin to Example validation - tests. -* Replaced examples in README.MD to links to Example files. -* Added the VS Code PowerShell extension formatting settings that cause PowerShell - files to be formatted as per the DSC Resource kit style guidelines - [Issue #91](https://github.com/PowerShell/xComputerManagement/issues/91). -* Opted into Common Tests 'Validate Module Files' and 'Validate Script Files'. -* Converted files with UTF8 with BOM over to UTF8 - fixes [Issue #90](https://github.com/PowerShell/xComputerManagement/issues/90). -* Updated Year to 2017 in License and Manifest - fixes [Issue #87](https://github.com/PowerShell/xComputerManagement/issues/87). -* Added .github support files - fixes [Issue #88](https://github.com/PowerShell/xComputerManagement/issues/88): - * CONTRIBUTING.md - * ISSUE_TEMPLATE.md - * PULL_REQUEST_TEMPLATE.md -* Resolved all PSScriptAnalyzer warnings and style guide warnings. -* xOfflineDomainJoin: - * Changed to use CommonResourceHelper to load localization strings. - * Renamed en-US to be correct case so that localization strings can be loaded. - * Suppress PSScriptAnalyzer rule PSAvoidGlobalVars for - `$global:DSCMachineStatus = 1`. -* xComputer: - * Suppress PSScriptAnalyzer rule PSAvoidGlobalVars for - `$global:DSCMachineStatus = 1`. -* xVirtualMemory: - * Suppress PSScriptAnalyzer rule PSAvoidGlobalVars for - `$global:DSCMachineStatus = 1`. - -### 2.0.0.0 - -* Updated resources - * BREAKING CHANGE: xScheduledTask: Added nearly all available parameters for tasks -* xVirtualMemory: - * Fixed failing tests. - -### 1.10.0.0 - -* Added resources: - * xVirtualMemory - -### 1.9.0.0 - -* Added resources - * xPowerPlan - -### 1.8.0.0 - -* Converted AppVeyor.yml to pull Pester from PSGallery instead of - Chocolatey. -* Changed AppVeyor.yml to use default image -* xScheduledTask: Fixed bug with different OS versions returning repeat interval - differently - -### 1.7.0.0 - -* Added support for enabling or disabling scheduled tasks -* The Name parameter resolves to $env:COMPUTERNAME when the value is localhost - -### 1.6.0.0 - -* Added the following resources: - * MSFT_xOfflineDomainJoin resource to join computers to an AD Domain using an - Offline Domain Join request file. - * MSFT_xScheduledTask resource to control scheduled tasks on the local server -* MSFT_xOfflineDomainJoin: Corrected localizedData.DomainAlreadyJoinedhMessage name. -* xComputer: Changed credential generation code in tests to avoid triggering - PSSA rule PSAvoidUsingConvertToSecureStringWithPlainText. - Renamed unit test file to match the name of Resource file. - -### 1.5.0.0 - -* Update Unit tests to use the standard folder structure and test templates. -* Added .gitignore to prevent commit of DSCResource.Tests. - -### 1.4.0.0 - -* Added validation to the Name parameter -* Added the JoinOU parameter which allows you to specify the organizational unit - that the computer account will be created in -* Added the CurrentOU read-only property that shows the organizational unit that - the computer account is currently in - -### 1.3.0 - -* xComputer - * Fixed issue with Test-TargetResource when not specifying Domain or - Workgroup name - * Added tests - -### 1.2.2 - -* Added types to Get/Set/Test definitions to allow xResourceDesigner validation - to succeed - -### 1.2 - -* Added functionality to enable moving computer from one domain to another -* Modified Test-DscConfiguration logics when testing domain join - -### 1.0.0.0 - -* Initial release with the following resources: - * xComputer diff --git a/Tests/Integration/MSFT_xScheduledTask.Config.ps1 b/Tests/Integration/MSFT_xScheduledTask.Config.ps1 index 86ccb52c..02767dd4 100644 --- a/Tests/Integration/MSFT_xScheduledTask.Config.ps1 +++ b/Tests/Integration/MSFT_xScheduledTask.Config.ps1 @@ -424,3 +424,31 @@ Configuration xScheduledTaskExecuteAsDel } } } + +Configuration xScheduledTaskDisableBuiltIn +{ + Import-DscResource -ModuleName xComputerManagement + node 'localhost' + { + xScheduledTask xScheduledTaskDisableBuiltIn + { + TaskName = 'Test task builtin' + TaskPath = '\xComputerManagement\' + Enable = $false + } + } +} + +Configuration xScheduledTaskRemoveBuiltIn +{ + Import-DscResource -ModuleName xComputerManagement + node 'localhost' + { + xScheduledTask xScheduledTaskRemoveBuiltIn + { + TaskName = 'Test task builtin' + TaskPath = '\xComputerManagement\' + Ensure = 'Absent' + } + } +} diff --git a/Tests/Integration/MSFT_xScheduledTask.Integration.Tests.ps1 b/Tests/Integration/MSFT_xScheduledTask.Integration.Tests.ps1 index 18e28249..f78335f6 100644 --- a/Tests/Integration/MSFT_xScheduledTask.Integration.Tests.ps1 +++ b/Tests/Integration/MSFT_xScheduledTask.Integration.Tests.ps1 @@ -3,7 +3,7 @@ $Global:DSCModuleName = 'xComputerManagement' $Global:DSCResourceName = 'MSFT_xScheduledTask' #region HEADER # Integration Test Template Version: 1.1.1 -[String] $script:moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) +$script:moduleRoot = Join-Path -Path $(Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path))) -ChildPath 'Modules\xComputerManagement' if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { @@ -59,7 +59,7 @@ try . $currentConfig ` -OutputPath $configDir ` -ConfigurationData $configData - } | Should Not Throw + } | Should -Not -Throw } It 'Should apply the MOF correctly' { @@ -70,11 +70,11 @@ try -Force ` -Verbose ` -ErrorAction Stop - } | Should Not Throw + } | Should -Not -Throw } It 'Should return a compliant state after being applied' { - (Test-DscConfiguration -ReferenceConfiguration $configMof -Verbose).InDesiredState | Should be $true + (Test-DscConfiguration -ReferenceConfiguration $configMof -Verbose).InDesiredState | Should -Be $true } } @@ -88,7 +88,7 @@ try . $currentConfig ` -OutputPath $configDir ` -ConfigurationData $configData - } | Should Not Throw + } | Should -Not -Throw } It 'Should apply the MOF correctly' { @@ -99,11 +99,11 @@ try -Force ` -Verbose ` -ErrorAction Stop - } | Should Not Throw + } | Should -Not -Throw } It 'Should return a compliant state after being applied' { - (Test-DscConfiguration -ReferenceConfiguration $configMof -Verbose).InDesiredState | Should be $true + (Test-DscConfiguration -ReferenceConfiguration $configMof -Verbose).InDesiredState | Should -Be $true } } @@ -117,7 +117,7 @@ try . $currentConfig ` -OutputPath $configDir ` -ConfigurationData $configData - } | Should Not Throw + } | Should -Not -Throw } It 'Should apply the MOF correctly' { @@ -128,11 +128,11 @@ try -Force ` -Verbose ` -ErrorAction Stop - } | Should Not Throw + } | Should -Not -Throw } It 'Should return a compliant state after being applied' { - (Test-DscConfiguration -ReferenceConfiguration $configMof -Verbose).InDesiredState | Should be $true + (Test-DscConfiguration -ReferenceConfiguration $configMof -Verbose).InDesiredState | Should -Be $true } } } @@ -152,7 +152,7 @@ try Set-TimeZoneId -Id 'W. Australia Standard Time' . $currentConfig ` -OutputPath $configDir - } | Should Not Throw + } | Should -Not -Throw } It 'Should apply the MOF correctly in New Zealand Standard Time Timezone' { @@ -164,35 +164,118 @@ try -Force ` -Verbose ` -ErrorAction Stop - } | Should Not Throw + } | Should -Not -Throw } It 'Should return a compliant state after being applied' { - (Test-DscConfiguration -ReferenceConfiguration $configMof -Verbose).InDesiredState | Should be $true + (Test-DscConfiguration -ReferenceConfiguration $configMof -Verbose).InDesiredState | Should -Be $true } It 'Should have set the resource and all the parameters should match' { $current = Get-DscConfiguration | Where-Object {$_.ConfigurationName -eq $currentConfig} - $current.TaskName | Should Be 'Test task once cross timezone' - $current.TaskPath | Should Be '\xComputerManagement\' - $current.ActionExecutable | Should Be 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' - $current.ScheduleType | Should Be 'Once' - $current.RepeatInterval | Should Be '00:15:00' - $current.RepetitionDuration | Should Be '23:00:00' - $current.ActionWorkingPath | Should Be (Get-Location).Path - $current.Enable | Should Be $true - $current.RandomDelay | Should Be '01:00:00' - $current.DisallowHardTerminate | Should Be $true - $current.RunOnlyIfIdle | Should Be $false - $current.Priority | Should Be 9 - $current.RunLevel | Should Be 'Limited' - $current.ExecutionTimeLimit | Should Be '00:00:00' + $current.TaskName | Should -Be 'Test task once cross timezone' + $current.TaskPath | Should -Be '\xComputerManagement\' + $current.ActionExecutable | Should -Be 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' + $current.ScheduleType | Should -Be 'Once' + $current.RepeatInterval | Should -Be '00:15:00' + $current.RepetitionDuration | Should -Be '23:00:00' + $current.ActionWorkingPath | Should -Be (Get-Location).Path + $current.Enable | Should -Be $true + $current.RandomDelay | Should -Be '01:00:00' + $current.DisallowHardTerminate | Should -Be $true + $current.RunOnlyIfIdle | Should -Be $false + $current.Priority | Should -Be 9 + $current.RunLevel | Should -Be 'Limited' + $current.ExecutionTimeLimit | Should -Be '00:00:00' } AfterAll { Set-TimeZoneId -Id $currentTimeZoneId } } + + # Simulate a "built-in" scheduled task + $action = New-ScheduledTaskAction -Execute 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' + $trigger = New-ScheduledTaskTrigger -Once -At (Get-Date) + $task = New-ScheduledTask -Action $action -Trigger $trigger + Register-ScheduledTask -InputObject $task -TaskName 'Test task builtin' -TaskPath '\xComputerManagement\' -User 'NT AUTHORITY\SYSTEM' + + Context 'Built-in task needs to be disabled' { + $currentConfig = 'xScheduledTaskDisableBuiltIn' + $configDir = (Join-Path -Path $TestDrive -ChildPath $currentConfig) + $configMof = (Join-Path -Path $configDir -ChildPath 'localhost.mof') + + It 'Should compile the MOF without throwing' { + { + . $currentConfig ` + -OutputPath $configDir ` + -ConfigurationData $configData + } | Should -Not -Throw + } + + It 'Should apply the MOF correctly' { + { + Start-DscConfiguration ` + -Path $configDir ` + -Wait ` + -Force ` + -Verbose ` + -ErrorAction Stop + } | Should -Not -Throw + } + + It 'Should return a compliant state after being applied' { + (Test-DscConfiguration -ReferenceConfiguration $configMof -Verbose).InDesiredState | Should -Be $true + } + + It 'Should have set the resource and all the parameters should match' { + $current = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq $currentConfig + } + $current.TaskName | Should -Be 'Test task builtin' + $current.TaskPath | Should -Be '\xComputerManagement\' + $current.Enable | Should -Be $false + } + } + + Context 'Built-in task needs to be removed' { + $currentConfig = 'xScheduledTaskRemoveBuiltIn' + $configDir = (Join-Path -Path $TestDrive -ChildPath $currentConfig) + $configMof = (Join-Path -Path $configDir -ChildPath 'localhost.mof') + + + It 'Should compile the MOF without throwing' { + { + . $currentConfig ` + -OutputPath $configDir ` + -ConfigurationData $configData + } | Should -Not -Throw + } + + It 'Should apply the MOF correctly' { + { + Start-DscConfiguration ` + -Path $configDir ` + -Wait ` + -Force ` + -Verbose ` + -ErrorAction Stop + } | Should -Not -Throw + } + + It 'Should return a compliant state after being applied' { + (Test-DscConfiguration -ReferenceConfiguration $configMof -Verbose).InDesiredState | Should -Be $true + } + + It 'Should have set the resource and all the parameters should match' { + $current = Get-DscConfiguration | Where-Object -FilterScript { + $_.ConfigurationName -eq $currentConfig + } + $current.TaskName | Should -Be 'Test task builtin' + $current.TaskPath | Should -Be '\xComputerManagement\' + $current.Ensure | Should -Be 'Absent' + } + } } } finally diff --git a/Tests/Integration/MSFT_xVirtualMemory.Integration.Tests.ps1 b/Tests/Integration/MSFT_xVirtualMemory.Integration.Tests.ps1 index b03eaa5c..599230cf 100644 --- a/Tests/Integration/MSFT_xVirtualMemory.Integration.Tests.ps1 +++ b/Tests/Integration/MSFT_xVirtualMemory.Integration.Tests.ps1 @@ -1,9 +1,9 @@ -$script:DSCModuleName = 'xComputerManagement' -$script:DSCResourceName = 'MSFT_xVirtualMemory' +$script:DSCModuleName = 'xComputerManagement' +$script:DSCResourceName = 'MSFT_xVirtualMemory' #region HEADER # Integration Test Template Version: 1.1.1 -[String] $script:moduleRoot = Split-Path -Parent (Split-Path -Parent $PSScriptRoot) +$script:moduleRoot = Join-Path -Path $(Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path))) -ChildPath 'Modules\xComputerManagement' if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { @@ -26,26 +26,26 @@ try . $configFile Describe "$($script:DSCResourceName)_Integration" { - + Context "Set page file to automatically managed" { $CurrentConfig = "setToAuto" $ConfigDir = (Join-Path -Path $TestDrive -ChildPath $CurrentConfig) $ConfigMof = (Join-Path -Path $ConfigDir -ChildPath "localhost.mof") - + It "should compile a MOF file without error" { { . $CurrentConfig -OutputPath $ConfigDir - } | Should Not Throw + } | Should -Not -Throw } - + It "should apply the MOF correctly" { { Start-DscConfiguration -Path $ConfigDir -Wait -Verbose -Force - } | Should Not Throw + } | Should -Not -Throw } - + It "should return a compliant state after being applied" { - (Test-DscConfiguration -ReferenceConfiguration $ConfigMof -Verbose).InDesiredState | Should be $true + (Test-DscConfiguration -ReferenceConfiguration $ConfigMof -Verbose).InDesiredState | Should -Be $true } } @@ -53,21 +53,21 @@ try $CurrentConfig = "setToCustom" $ConfigDir = (Join-Path -Path $TestDrive -ChildPath $CurrentConfig) $ConfigMof = (Join-Path -Path $ConfigDir -ChildPath "localhost.mof") - + It "should compile a MOF file without error" { { . $CurrentConfig -OutputPath $ConfigDir - } | Should Not Throw + } | Should -Not -Throw } - + It "should apply the MOF correctly" { { Start-DscConfiguration -Path $ConfigDir -Wait -Verbose -Force - } | Should Not Throw + } | Should -Not -Throw } - + It "should return a compliant state after being applied" { - (Test-DscConfiguration -ReferenceConfiguration $ConfigMof -Verbose).InDesiredState | Should be $true + (Test-DscConfiguration -ReferenceConfiguration $ConfigMof -Verbose).InDesiredState | Should -Be $true } } @@ -75,21 +75,21 @@ try $CurrentConfig = "setToSystemManaged" $ConfigDir = (Join-Path -Path $TestDrive -ChildPath $CurrentConfig) $ConfigMof = (Join-Path -Path $ConfigDir -ChildPath "localhost.mof") - + It "should compile a MOF file without error" { { . $CurrentConfig -OutputPath $ConfigDir - } | Should Not Throw + } | Should -Not -Throw } - + It "should apply the MOF correctly" { { Start-DscConfiguration -Path $ConfigDir -Wait -Verbose -Force - } | Should Not Throw + } | Should -Not -Throw } - + It "should return a compliant state after being applied" { - (Test-DscConfiguration -ReferenceConfiguration $ConfigMof -Verbose).InDesiredState | Should be $true + (Test-DscConfiguration -ReferenceConfiguration $ConfigMof -Verbose).InDesiredState | Should -Be $true } } @@ -97,21 +97,21 @@ try $CurrentConfig = "setToNone" $ConfigDir = (Join-Path -Path $TestDrive -ChildPath $CurrentConfig) $ConfigMof = (Join-Path -Path $ConfigDir -ChildPath "localhost.mof") - + It "should compile a MOF file without error" { { . $CurrentConfig -OutputPath $ConfigDir - } | Should Not Throw + } | Should -Not -Throw } - + It "should apply the MOF correctly" { { Start-DscConfiguration -Path $ConfigDir -Wait -Verbose -Force - } | Should Not Throw + } | Should -Not -Throw } - + It "should return a compliant state after being applied" { - (Test-DscConfiguration -ReferenceConfiguration $ConfigMof -Verbose).InDesiredState | Should be $true + (Test-DscConfiguration -ReferenceConfiguration $ConfigMof -Verbose).InDesiredState | Should -Be $true } } } diff --git a/Tests/TestHarness.psm1 b/Tests/TestHarness.psm1 new file mode 100644 index 00000000..861a38cb --- /dev/null +++ b/Tests/TestHarness.psm1 @@ -0,0 +1,66 @@ +function Invoke-TestHarness +{ + [CmdletBinding()] + param + ( + [System.String] + $TestResultsFile, + + [System.String] + $DscTestsPath + ) + + Write-Verbose -Message 'Commencing all xComputerManagement tests' + + $repoDir = Join-Path -Path $PSScriptRoot -ChildPath '..\' -Resolve + + $testCoverageFiles = @() + Get-ChildItem -Path "$repoDir\modules\xComputerManagement\DSCResources\**\*.psm1" -Recurse | ForEach-Object { + if ($_.FullName -notlike '*\DSCResource.Tests\*') { + $testCoverageFiles += $_.FullName + } + } + + $testResultSettings = @{ } + if ([String]::IsNullOrEmpty($TestResultsFile) -eq $false) { + $testResultSettings.Add('OutputFormat', 'NUnitXml' ) + $testResultSettings.Add('OutputFile', $TestResultsFile) + } + + Import-Module -Name "$repoDir\modules\xComputerManagement\xComputerManagement.psd1" + $testsToRun = @() + + # Run Unit Tests + $unitTestsPath = Join-Path -Path $repoDir -ChildPath 'Tests\Unit' + $testsToRun += @( (Get-ChildItem -Path $unitTestsPath).FullName ) + + # Integration Tests + $integrationTestsPath = Join-Path -Path $repoDir -ChildPath 'Tests\Integration' + $testsToRun += @( (Get-ChildItem -Path $integrationTestsPath -Filter '*.Tests.ps1').FullName ) + + # DSC Common Tests + if ($PSBoundParameters.ContainsKey('DscTestsPath') -eq $true) + { + $getChildItemParameters = @{ + Path = $DscTestsPath + Recurse = $true + Filter = '*.Tests.ps1' + } + + # Get all tests '*.Tests.ps1'. + $commonTestFiles = Get-ChildItem @getChildItemParameters + + # Remove DscResource.Tests unit and integration tests. + $commonTestFiles = $commonTestFiles | Where-Object -FilterScript { + $_.FullName -notmatch 'DSCResource.Tests\\Tests' + } + + $testsToRun += @( $commonTestFiles.FullName ) + } + + $results = Invoke-Pester -Script $testsToRun ` + -CodeCoverage $testCoverageFiles ` + -PassThru @testResultSettings + + return $results +} diff --git a/Tests/Unit/ComputerManagementDsc.Common.Tests.ps1 b/Tests/Unit/ComputerManagementDsc.Common.Tests.ps1 index b1b5f214..bc308010 100644 --- a/Tests/Unit/ComputerManagementDsc.Common.Tests.ps1 +++ b/Tests/Unit/ComputerManagementDsc.Common.Tests.ps1 @@ -4,7 +4,7 @@ Import-Module -Name (Join-Path -Path (Join-Path -Path (Split-Path $PSScriptRoot #region HEADER # Unit Test Template Version: 1.1.0 -$script:moduleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path)) +$script:moduleRoot = Join-Path -Path $(Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path))) -ChildPath 'Modules\xComputerManagement' if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { diff --git a/Tests/Unit/MSFT_xComputer.Tests.ps1 b/Tests/Unit/MSFT_xComputer.Tests.ps1 index be4fdfc9..308bfe9e 100644 --- a/Tests/Unit/MSFT_xComputer.Tests.ps1 +++ b/Tests/Unit/MSFT_xComputer.Tests.ps1 @@ -4,7 +4,7 @@ $script:DSCResourceName = 'MSFT_xComputer' Import-Module -Name (Join-Path -Path (Join-Path -Path (Split-Path $PSScriptRoot -Parent) -ChildPath 'TestHelpers') -ChildPath 'CommonTestHelper.psm1') -Global # Unit Test Template Version: 1.2.0 -$script:moduleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path)) +$script:moduleRoot = Join-Path -Path $(Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path))) -ChildPath 'Modules\xComputerManagement' if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { @@ -59,7 +59,7 @@ try -DomainName 'contoso.com' ` -WorkGroupName 'workgroup' ` -Verbose - } | Should Throw $errorRecord + } | Should -Throw $errorRecord } It 'Throws if Domain is specified without Credentials' { @@ -72,7 +72,7 @@ try -Name $env:COMPUTERNAME ` -DomainName 'contoso.com' ` -Verbose - } | Should Throw $errorRecord + } | Should -Throw $errorRecord } It 'Should return True if Domain name is same as specified' { @@ -92,7 +92,7 @@ try -Name $env:COMPUTERNAME ` -DomainName 'Contoso.com' ` -Credential $credential ` - -Verbose | Should Be $true + -Verbose | Should -Be $true } It 'Should return True if Workgroup name is same as specified' { @@ -111,7 +111,7 @@ try Test-TargetResource ` -Name $env:COMPUTERNAME ` -WorkGroupName 'workgroup' ` - -Verbose | Should Be $true + -Verbose | Should -Be $true } It 'Should return True if ComputerName and Domain name is same as specified' { @@ -131,13 +131,13 @@ try -Name $env:COMPUTERNAME ` -DomainName 'contoso.com' ` -Credential $credential ` - -Verbose | Should Be $true + -Verbose | Should -Be $true Test-TargetResource ` -Name 'localhost' ` -DomainName 'contoso.com' ` -Credential $credential ` - -Verbose | Should Be $true + -Verbose | Should -Be $true } It 'Should return True if ComputerName and Workgroup is same as specified' { @@ -156,12 +156,12 @@ try Test-TargetResource ` -Name $env:COMPUTERNAME ` -WorkGroupName 'workgroup' ` - -Verbose | Should Be $true + -Verbose | Should -Be $true Test-TargetResource ` -Name 'localhost' ` -WorkGroupName 'workgroup' ` - -Verbose | Should Be $true + -Verbose | Should -Be $true } It 'Should return True if ComputerName is same and no Domain or Workgroup specified' { @@ -179,11 +179,11 @@ try Test-TargetResource ` -Name $env:COMPUTERNAME ` - -Verbose | Should Be $true + -Verbose | Should -Be $true Test-TargetResource ` -Name 'localhost' ` - -Verbose | Should Be $true + -Verbose | Should -Be $true Mock -CommandName Get-WmiObject { [PSCustomObject] @{ @@ -199,11 +199,11 @@ try Test-TargetResource ` -Name $env:COMPUTERNAME ` - -Verbose | Should Be $true + -Verbose | Should -Be $true Test-TargetResource ` -Name 'localhost' ` - -Verbose | Should Be $true + -Verbose | Should -Be $true } It 'Should return False if ComputerName is not same and no Domain or Workgroup specified' { @@ -221,7 +221,7 @@ try Test-TargetResource ` -Name $notComputerName ` - -Verbose | Should Be $false + -Verbose | Should -Be $false Mock -CommandName Get-WmiObject -MockWith { [PSCustomObject] @{ @@ -237,7 +237,7 @@ try Test-TargetResource ` -Name $notComputerName ` - -Verbose | Should Be $false + -Verbose | Should -Be $false } It 'Should return False if Domain name is not same as specified' { @@ -257,13 +257,13 @@ try -Name $env:COMPUTERNAME ` -DomainName 'adventure-works.com' ` -Credential $credential ` - -Verbose | Should Be $false + -Verbose | Should -Be $false Test-TargetResource ` -Name 'localhost' ` -DomainName 'adventure-works.com' ` -Credential $credential ` - -Verbose | Should Be $false + -Verbose | Should -Be $false } It 'Should return False if Workgroup name is not same as specified' { @@ -282,12 +282,12 @@ try Test-TargetResource ` -Name $env:COMPUTERNAME ` -WorkGroupName 'NOTworkgroup' ` - -Verbose | Should Be $false + -Verbose | Should -Be $false Test-TargetResource ` -Name 'localhost' ` -WorkGroupName 'NOTworkgroup' ` - -Verbose | Should Be $false + -Verbose | Should -Be $false } It 'Should return False if ComputerName is not same as specified' { @@ -306,7 +306,7 @@ try Test-TargetResource ` -Name $notComputerName ` -WorkGroupName 'workgroup' ` - -Verbose | Should Be $false + -Verbose | Should -Be $false Mock -CommandName Get-WMIObject -MockWith { [PSCustomObject] @{ @@ -324,7 +324,7 @@ try -Name $notComputerName ` -DomainName 'contoso.com' ` -Credential $credential ` - -Verbose | Should Be $false + -Verbose | Should -Be $false } It 'Should return False if Computer is in Workgroup and Domain is specified' { @@ -344,13 +344,13 @@ try -Name $env:COMPUTERNAME ` -DomainName 'contoso.com' ` -Credential $credential ` - -Verbose | Should Be $false + -Verbose | Should -Be $false Test-TargetResource ` -Name 'localhost' ` -DomainName 'contoso.com' ` -Credential $credential ` - -Verbose | Should Be $false + -Verbose | Should -Be $false } It 'Should return False if ComputerName is in Domain and Workgroup is specified' { @@ -371,14 +371,14 @@ try -WorkGroupName 'Contoso' ` -Credential $credential ` -UnjoinCredential $credential ` - -Verbose | Should Be $false + -Verbose | Should -Be $false Test-TargetResource ` -Name 'localhost' ` -WorkGroupName 'Contoso' ` -Credential $credential ` -UnjoinCredential $credential ` - -Verbose | Should Be $false + -Verbose | Should -Be $false } It 'Throws if name is to long' { @@ -386,7 +386,7 @@ try Test-TargetResource ` -Name 'ThisNameIsTooLong' ` -Verbose - } | Should Throw + } | Should -Throw } It 'Throws if name contains illegal characters' { @@ -394,7 +394,7 @@ try Test-TargetResource ` -Name 'ThisIsBad<>' ` -Verbose - } | Should Throw + } | Should -Throw } It 'Should not Throw if name is localhost' { @@ -402,7 +402,7 @@ try Test-TargetResource ` -Name 'localhost' ` -Verbose - } | Should Not Throw + } | Should -Not -Throw } It 'Should return true if description is same as specified' { @@ -415,12 +415,12 @@ try Test-TargetResource ` -Name $env:COMPUTERNAME ` -Description 'This is my computer' ` - -Verbose | Should Be $true + -Verbose | Should -Be $true Test-TargetResource ` -Name 'localhost' ` -Description 'This is my computer' ` - -Verbose | Should Be $true + -Verbose | Should -Be $true } It 'Should return false if description is same as specified' { @@ -433,12 +433,12 @@ try Test-TargetResource ` -Name $env:COMPUTERNAME ` -Description 'This is my computer' ` - -Verbose | Should Be $false + -Verbose | Should -Be $false Test-TargetResource ` -Name 'localhost' ` -Description 'This is my computer' ` - -Verbose | Should Be $false + -Verbose | Should -Be $false } } @@ -448,7 +448,7 @@ try Get-TargetResource ` -Name $env:COMPUTERNAME ` -Verbose - } | Should Not Throw + } | Should -Not -Throw } It 'Should return a hashtable containing Name, DomainName, JoinOU, CurrentOU, Credential, UnjoinCredential, WorkGroupName and Description' { @@ -456,8 +456,8 @@ try -Name $env:COMPUTERNAME ` -Verbose - $Result.GetType().Fullname | Should Be 'System.Collections.Hashtable' - $Result.Keys | Sort-Object | Should Be @('Credential', 'CurrentOU', 'Description', 'DomainName', 'JoinOU', 'Name', 'UnjoinCredential', 'WorkGroupName') + $Result.GetType().Fullname | Should -Be 'System.Collections.Hashtable' + $Result.Keys | Sort-Object | Should -Be @('Credential', 'CurrentOU', 'Description', 'DomainName', 'JoinOU', 'Name', 'UnjoinCredential', 'WorkGroupName') } It 'Throws if name is to long' { @@ -465,7 +465,7 @@ try Get-TargetResource ` -Name 'ThisNameIsTooLong' ` -Verbose - } | Should Throw + } | Should -Throw } It 'Throws if name contains illegal characters' { @@ -473,7 +473,7 @@ try Get-TargetResource ` -Name 'ThisIsBad<>' ` -Verbose - } | Should Throw + } | Should -Throw } } @@ -492,7 +492,7 @@ try -DomainName 'contoso.com' ` -WorkGroupName 'workgroup' ` -Verbose - } | Should Throw $errorRecord + } | Should -Throw $errorRecord Assert-MockCalled -CommandName Rename-Computer -Exactly -Times 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly -Times 0 -Scope It @@ -508,7 +508,7 @@ try -Name $env:COMPUTERNAME ` -DomainName 'contoso.com' ` -Verbose - } | Should Throw $errorRecord + } | Should -Throw $errorRecord Assert-MockCalled -CommandName Rename-Computer -Exactly -Times 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly -Times 0 -Scope It @@ -532,7 +532,7 @@ try -DomainName 'adventure-works.com' ` -Credential $credential ` -UnjoinCredential $credential ` - -Verbose | Should BeNullOrEmpty + -Verbose | Should -BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly -Times 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly -Times 1 -Scope It -ParameterFilter { $DomainName -and $NewName } @@ -558,7 +558,7 @@ try -JoinOU 'OU=Computers,DC=contoso,DC=com' ` -Credential $credential ` -UnjoinCredential $credential ` - -Verbose | Should BeNullOrEmpty + -Verbose | Should -BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly -Times 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly -Times 1 -Scope It -ParameterFilter { $DomainName -and $NewName } @@ -582,7 +582,7 @@ try -Name $notComputerName ` -WorkGroupName 'contoso' ` -Credential $credential ` - -Verbose | Should BeNullOrEmpty + -Verbose | Should -BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly -Times 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly -Times 1 -Scope It -ParameterFilter { $WorkGroupName -and $NewName -and $credential } @@ -606,7 +606,7 @@ try -Name $notComputerName ` -DomainName 'Contoso.com' ` -Credential $credential ` - -Verbose | Should BeNullOrEmpty + -Verbose | Should -BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly -Times 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly -Times 1 -Scope It -ParameterFilter { $DomainName -and $NewName } @@ -631,7 +631,7 @@ try -DomainName 'Contoso.com' ` -JoinOU 'OU=Computers,DC=contoso,DC=com' ` -Credential $credential ` - -Verbose | Should BeNullOrEmpty + -Verbose | Should -BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly -Times 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly -Times 1 -Scope It -ParameterFilter { $DomainName -and $NewName } @@ -654,7 +654,7 @@ try Set-TargetResource ` -Name $notComputerName ` -WorkGroupName 'adventure-works' ` - -Verbose | Should BeNullOrEmpty + -Verbose | Should -BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly -Times 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly -Times 1 -Scope It -ParameterFilter { $WorkGroupName -and $NewName } @@ -679,7 +679,7 @@ try -DomainName 'adventure-works.com' ` -Credential $credential ` -UnjoinCredential $credential ` - -Verbose | Should BeNullOrEmpty + -Verbose | Should -BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly -Times 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly -Times 1 -Scope It -ParameterFilter { $DomainName } @@ -705,7 +705,7 @@ try -DomainName 'adventure-works.com' ` -Credential $credential ` -UnjoinCredential $credential ` - -Verbose | Should BeNullOrEmpty + -Verbose | Should -BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly -Times 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly -Times 1 -Scope It -ParameterFilter { $DomainName } @@ -732,7 +732,7 @@ try -JoinOU 'OU=Computers,DC=contoso,DC=com' ` -Credential $credential ` -UnjoinCredential $credential ` - -Verbose | Should BeNullOrEmpty + -Verbose | Should -BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly -Times 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly -Times 1 -Scope It -ParameterFilter { $DomainName } @@ -759,7 +759,7 @@ try -JoinOU 'OU=Computers,DC=contoso,DC=com' ` -Credential $credential ` -UnjoinCredential $credential ` - -Verbose | Should BeNullOrEmpty + -Verbose | Should -BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly -Times 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly -Times 1 -Scope It -ParameterFilter { $DomainName } @@ -784,7 +784,7 @@ try -Name $env:COMPUTERNAME ` -WorkGroupName 'Contoso' ` -UnjoinCredential $credential ` - -Verbose | Should BeNullOrEmpty + -Verbose | Should -BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly -Times 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly -Times 0 -Scope It -ParameterFilter { $NewName } @@ -809,7 +809,7 @@ try -Name 'localhost' ` -WorkGroupName 'Contoso' ` -UnjoinCredential $credential ` - -Verbose | Should BeNullOrEmpty + -Verbose | Should -BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly -Times 0 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly -Times 0 -Scope It -ParameterFilter { $NewName } @@ -833,7 +833,7 @@ try Set-TargetResource ` -Name $notComputerName ` -Credential $credential ` - -Verbose | Should BeNullOrEmpty + -Verbose | Should -BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly -Times 1 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly -Times 0 -Scope It @@ -854,7 +854,7 @@ try Set-TargetResource ` -Name $notComputerName ` - -Verbose | Should BeNullOrEmpty + -Verbose | Should -BeNullOrEmpty Assert-MockCalled -CommandName Rename-Computer -Exactly -Times 1 -Scope It Assert-MockCalled -CommandName Add-Computer -Exactly -Times 0 -Scope It @@ -865,7 +865,7 @@ try Set-TargetResource ` -Name 'ThisNameIsTooLong' ` -Verbose - } | Should Throw + } | Should -Throw } It 'Throws if name contains illegal characters' { @@ -873,7 +873,7 @@ try Set-TargetResource ` -Name 'ThisIsBad<>' ` -Verbose - } | Should Throw + } | Should -Throw } It 'Changes computer description in a workgroup' { @@ -893,7 +893,7 @@ try -Name $env:COMPUTERNAME ` -Description 'This is my computer' ` -DomainName '' ` - -Verbose | Should BeNullOrEmpty + -Verbose | Should -BeNullOrEmpty Assert-MockCalled -CommandName Set-CimInstance -Exactly -Times 1 -Scope It } @@ -913,7 +913,7 @@ try Set-TargetResource ` -Name $env:COMPUTERNAME ` - -Verbose | Should BeNullOrEmpty + -Verbose | Should -BeNullOrEmpty Set-TargetResource ` -Name $env:COMPUTERNAME ` @@ -921,11 +921,93 @@ try -Credential $credential ` -UnjoinCredential $credential ` -Description 'This is my computer' ` - -Verbose | Should BeNullOrEmpty + -Verbose | Should -BeNullOrEmpty Assert-MockCalled -CommandName Set-CimInstance -Exactly -Times 1 -Scope It } } + + Context "$($script:DSCResourceName)\Get-ComputerDomain" { + It 'Returns domain netbios or DNS name if domain member' { + Mock -CommandName Get-CimInstance -ParameterFilter { $ClassName -eq 'Win32_ComputerSystem' } -MockWith { + [PSCustomObject] @{ + Domain = 'contoso.com'; + PartOfDomain = $true + } + } + + Mock -CommandName Get-Item -ParameterFilter { $Path -eq 'Env:\USERDOMAIN' } -MockWith { + [PSCustomObject] @{ + Value = 'CONTOSO' + } + } + + $getComputerDomainParameters = @{ + netbios = $true + } + + Get-ComputerDomain @getComputerDomainParameters | Should Be 'CONTOSO' + + $getComputerDomainParameters = @{ + netbios = $false + } + + Get-ComputerDomain @getComputerDomainParameters | Should Be 'contoso.com' + + Assert-MockCalled -CommandName Get-CimInstance -Exactly -Times 2 -Scope It + Assert-MockCalled -CommandName Get-Item -Exactly -Times 1 -Scope It + } + + It 'Returns nothing if in a workgroup' { + Mock -CommandName Get-CimInstance -ParameterFilter { $ClassName -eq 'Win32_ComputerSystem' } -MockWith { + [PSCustomObject] @{ + Domain = 'WORKGROUP'; + PartOfDomain = $false + } + } + + Mock -CommandName Get-Item -ParameterFilter { $Path -eq 'Env:\USERDOMAIN' } -MockWith { + [PSCustomObject] @{ + Value = 'Computer1' + } + } + + $getComputerDomainParameters = @{ + netbios = $true + } + + Get-ComputerDomain @getComputerDomainParameters | Should Be '' + + $getComputerDomainParameters = @{ + netbios = $false + } + + Get-ComputerDomain @getComputerDomainParameters | Should Be '' + + Assert-MockCalled -CommandName Get-CimInstance -Exactly -Times 2 -Scope It + Assert-MockCalled -CommandName Get-Item -Exactly -Times 0 -Scope It + } + + It 'Returns domain DNS name when netbios not specified' { + Mock -CommandName Get-CimInstance -ParameterFilter { $ClassName -eq 'Win32_ComputerSystem' } -MockWith { + [PSCustomObject] @{ + Domain = 'contoso.com'; + PartOfDomain = $true + } + } + + Mock -CommandName Get-Item -ParameterFilter { $Path -eq 'Env:\USERDOMAIN' } -MockWith { + [PSCustomObject] @{ + Value = 'CONTOSO' + } + } + + Get-ComputerDomain | Should Be "contoso.com" + + Assert-MockCalled -CommandName Get-CimInstance -Exactly -Times 1 -Scope It + Assert-MockCalled -CommandName Get-Item -Exactly -Times 0 -Scope It + } + } } } #end InModuleScope $DSCResourceName #endregion diff --git a/Tests/Unit/MSFT_xOfflineDomainJoin.Tests.ps1 b/Tests/Unit/MSFT_xOfflineDomainJoin.Tests.ps1 index 388e1a2b..a04877c1 100644 --- a/Tests/Unit/MSFT_xOfflineDomainJoin.Tests.ps1 +++ b/Tests/Unit/MSFT_xOfflineDomainJoin.Tests.ps1 @@ -4,7 +4,7 @@ $script:DSCResourceName = 'MSFT_xOfflineDomainJoin' Import-Module -Name (Join-Path -Path (Join-Path -Path (Split-Path $PSScriptRoot -Parent) -ChildPath 'TestHelpers') -ChildPath 'CommonTestHelper.psm1') -Global # Unit Test Template Version: 1.2.0 -$script:moduleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path)) +$script:moduleRoot = Join-Path -Path $(Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path))) -ChildPath 'Modules\xComputerManagement' if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { @@ -37,8 +37,8 @@ try $result = Get-TargetResource ` @TestOfflineDomainJoin - $result.IsSingleInstance | Should Be $testOfflineDomainJoin.IsSingleInstance - $result.RequestFile | Should Be '' + $result.IsSingleInstance | Should -Be $testOfflineDomainJoin.IsSingleInstance + $result.RequestFile | Should -Be '' } } @@ -51,7 +51,7 @@ try Mock -CommandName Join-Domain It 'Should not throw exception' { - { Set-TargetResource @TestOfflineDomainJoin } | Should Not Throw + { Set-TargetResource @TestOfflineDomainJoin } | Should -Not -Throw } It 'Should do call all the mocks' { @@ -72,7 +72,7 @@ try -Message ($LocalizedData.RequestFileNotFoundError -f $testOfflineDomainJoin.RequestFile) ` -ArgumentName 'RequestFile' - { Test-TargetResource @TestOfflineDomainJoin } | Should Throw $errorRecord + { Test-TargetResource @TestOfflineDomainJoin } | Should -Throw $errorRecord } It 'Should do call all the mocks' { @@ -93,7 +93,7 @@ try } It 'Should return false' { - Test-TargetResource @TestOfflineDomainJoin | should be $false + Test-TargetResource @TestOfflineDomainJoin | Should -Be $false } It 'Should do call all the mocks' { @@ -112,7 +112,7 @@ try } It 'Should return false' { - Test-TargetResource @TestOfflineDomainJoin | should be $true + Test-TargetResource @TestOfflineDomainJoin | Should -Be $true } It 'Should do call all the mocks' { @@ -135,7 +135,7 @@ try -Message ($LocalizedData.RequestFileNotFoundError -f $testOfflineDomainJoin.RequestFile) ` -ArgumentName 'RequestFile' - { Test-TargetResource @TestOfflineDomainJoin } | Should Throw $errorRecord + { Test-TargetResource @TestOfflineDomainJoin } | Should -Throw $errorRecord } It 'Should do call all the mocks' { @@ -153,7 +153,7 @@ try } It 'Should not throw' { - { Join-Domain -RequestFile 'c:\doesnotmatter.txt' } | Should Not Throw + { Join-Domain -RequestFile 'c:\doesnotmatter.txt' } | Should -Not -Throw } It 'Should do call all the mocks' { @@ -171,7 +171,7 @@ try -Message $($LocalizedData.DjoinError -f 99) It 'Should not throw' { - { Join-Domain -RequestFile 'c:\doesnotmatter.txt' } | Should Throw $errorRecord + { Join-Domain -RequestFile 'c:\doesnotmatter.txt' } | Should -Throw $errorRecord } It 'Should do call all the mocks' { diff --git a/Tests/Unit/MSFT_xPowerPlan.Tests.ps1 b/Tests/Unit/MSFT_xPowerPlan.Tests.ps1 index aee131fc..f82c2b59 100644 --- a/Tests/Unit/MSFT_xPowerPlan.Tests.ps1 +++ b/Tests/Unit/MSFT_xPowerPlan.Tests.ps1 @@ -4,7 +4,7 @@ $script:DSCResourceName = 'MSFT_xPowerPlan' Import-Module -Name (Join-Path -Path (Join-Path -Path (Split-Path $PSScriptRoot -Parent) -ChildPath 'TestHelpers') -ChildPath 'CommonTestHelper.psm1') -Global # Unit Test Template Version: 1.2.0 -$script:moduleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path)) +$script:moduleRoot = Join-Path -Path $(Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path))) -ChildPath 'Modules\xComputerManagement' if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { @@ -55,8 +55,8 @@ try It 'Should return the same values as passed as parameters' { $result = Get-TargetResource @testParameters - $result.IsSingleInstance | Should Be 'Yes' - $result.Name | Should Be $testParameters.Name + $result.IsSingleInstance | Should -Be 'Yes' + $result.Name | Should -Be $testParameters.Name } } @@ -74,8 +74,8 @@ try It 'Should not return any plan name' { $result = Get-TargetResource @testParameters - $result.IsSingleInstance | Should Be 'Yes' - $result.Name | Should Be $null + $result.IsSingleInstance | Should -Be 'Yes' + $result.Name | Should -Be $null } } @@ -92,7 +92,7 @@ try $errorRecord = Get-InvalidOperationRecord ` -Message ($LocalizedData.PowerPlanCimError -f 'Win32_PowerPlan') - { Get-TargetResource @testParameters } | Should Throw $errorRecord + { Get-TargetResource @testParameters } | Should -Throw $errorRecord } } @@ -108,7 +108,7 @@ try $errorRecord = Get-InvalidOperationRecord ` -Message ($LocalizedData.PowerPlanNotFound -f $testParameters.Name) - { Get-TargetResource @testParameters } | Should Throw $errorRecord + { Get-TargetResource @testParameters } | Should -Throw $errorRecord } } @@ -160,7 +160,7 @@ try $errorRecord = Get-InvalidOperationRecord ` -Message ($LocalizedData.PowerPlanCimError -f 'Win32_PowerPlan') - { Set-TargetResource @testParameters } | Should Throw $errorRecord + { Set-TargetResource @testParameters } | Should -Throw $errorRecord } } @@ -177,7 +177,7 @@ try $errorRecord = Get-InvalidOperationRecord ` -Message ($LocalizedData.PowerPlanWasUnableToBeSet -f $testParameters.Name, 'Failed to set value') - { Set-TargetResource @testParameters } | Should Throw $errorRecord + { Set-TargetResource @testParameters } | Should -Throw $errorRecord } } @@ -206,7 +206,7 @@ try } It 'Should return the the state as present ($true)' { - Test-TargetResource @testParameters | Should Be $true + Test-TargetResource @testParameters | Should -Be $true } } @@ -223,7 +223,7 @@ try } It 'Should return the the state as absent ($false)' { - Test-TargetResource @testParameters | Should Be $false + Test-TargetResource @testParameters | Should -Be $false } } diff --git a/Tests/Unit/MSFT_xScheduledTask.Tests.ps1 b/Tests/Unit/MSFT_xScheduledTask.Tests.ps1 index 7abc3c75..5c24831e 100644 --- a/Tests/Unit/MSFT_xScheduledTask.Tests.ps1 +++ b/Tests/Unit/MSFT_xScheduledTask.Tests.ps1 @@ -1,18 +1,19 @@ [Diagnostics.CodeAnalysis.SuppressMessageAttribute("PSAvoidUsingConvertToSecureStringWithPlainText", "")] -param( +param +( ) -$script:DSCModuleName = 'xComputerManagement' -$script:DSCResourceName = 'MSFT_xScheduledTask' +$script:DSCModuleName = 'xComputerManagement' +$script:DSCResourceName = 'MSFT_xScheduledTask' Import-Module -Name (Join-Path -Path (Join-Path -Path (Split-Path $PSScriptRoot -Parent) -ChildPath 'TestHelpers') -ChildPath 'CommonTestHelper.psm1') -Global # Unit Test Template Version: 1.2.0 -$script:moduleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path)) +$script:moduleRoot = Join-Path -Path $(Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path))) -ChildPath 'Modules\xComputerManagement' if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` - (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) + (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { - & git @('clone','https://github.com/PowerShell/DscResource.Tests.git',(Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) + & git @('clone', 'https://github.com/PowerShell/DscResource.Tests.git', (Join-Path -Path $script:moduleRoot -ChildPath '\DSCResource.Tests\')) } Import-Module (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1') -Force @@ -34,6 +35,36 @@ try InModuleScope $script:DSCResourceName { $script:DSCResourceName = 'MSFT_xScheduledTask' + # Function to allow mocking pipeline input + function Register-ScheduledTask + { + param + ( + [Parameter()] + [switch] + $Force, + + [Parameter(ValueFromPipeline = $true)] + $InputObject, + + [Parameter()] + [System.String] + $Password, + + [Parameter()] + [System.String] + $User, + + [Parameter()] + [System.String] + $TaskName, + + [Parameter()] + [System.String] + $TaskPath + ) + } + Describe $script:DSCResourceName { BeforeAll { Mock -CommandName Register-ScheduledTask @@ -43,24 +74,24 @@ try Context 'No scheduled task exists, but it should' { $testParameters = @{ - TaskName = 'Test task' - TaskPath = '\Test\' - ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' - ScheduleType = 'Once' - RepeatInterval = (New-TimeSpan -Minutes 15).ToString() + TaskName = 'Test task' + TaskPath = '\Test\' + ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' + ScheduleType = 'Once' + RepeatInterval = (New-TimeSpan -Minutes 15).ToString() RepetitionDuration = (New-TimeSpan -Minutes 150).ToString() - Verbose = $True + Verbose = $True } - Mock -CommandName Get-ScheduledTask { return $null } + Mock -CommandName Get-ScheduledTask -MockWith { return $null } It 'Should return the correct values from Get-TargetResource' { $result = Get-TargetResource @testParameters - $result.Ensure | Should Be 'Absent' + $result.Ensure | Should -Be 'Absent' } It 'Should return false from the test method' { - Test-TargetResource @testParameters | Should Be $false + Test-TargetResource @testParameters | Should -Be $false } It 'Should create the scheduled task in the set method' { @@ -70,28 +101,29 @@ try Context 'A scheduled task exists, but it should not' { $testParameters = @{ - TaskName = 'Test task' - TaskPath = '\Test\' - ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' - ScheduleType = 'Once' - RepeatInterval = (New-TimeSpan -Minutes 15).ToString() + TaskName = 'Test task' + TaskPath = '\Test\' + ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' + ScheduleType = 'Once' + RepeatInterval = (New-TimeSpan -Minutes 15).ToString() RepetitionDuration = (New-TimeSpan -Minutes 15).ToString() - Ensure = 'Absent' - Verbose = $True + Ensure = 'Absent' + Verbose = $True } - Mock -CommandName Get-ScheduledTask { return @{ - TaskName = $testParameters.TaskName - TaskPath = $testParameters.TaskPath - Actions = @(@{ + Mock -CommandName Get-ScheduledTask -MockWith { + @{ + TaskName = $testParameters.TaskName + TaskPath = $testParameters.TaskPath + Actions = @(@{ Execute = $testParameters.ActionExecutable }) - Triggers = @(@{ + Triggers = @(@{ Repetition = @{ Duration = "PT$([System.TimeSpan]::Parse($testParameters.RepetitionDuration).TotalMinutes)M" Interval = "PT$([System.TimeSpan]::Parse($testParameters.RepeatInterval).TotalMinutes)M" } - CimClass = @{ + CimClass = @{ CimClassName = 'MSFT_TaskTimeTrigger' } }) @@ -102,11 +134,11 @@ try It 'Should return the correct values from Get-TargetResource' { $result = Get-TargetResource @testParameters - $result.Ensure | Should Be 'Present' + $result.Ensure | Should -Be 'Present' } It 'Should return false from the test method' { - Test-TargetResource @testParameters | Should Be $false + Test-TargetResource @testParameters | Should -Be $false } It 'Should remove the scheduled task in the set method' { @@ -115,66 +147,167 @@ try } } - Context 'A scheduled task doesnt exist, and it should not' { + Context 'A built-in scheduled task exists and is enabled, but it should be disabled' { $testParameters = @{ TaskName = 'Test task' TaskPath = '\Test\' - ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' - ScheduleType = 'Once' - Ensure = 'Absent' - Verbose = $True + Enable = $false + Verbose = $True } - Mock -CommandName Get-ScheduledTask { return $null } + Mock -CommandName Get-ScheduledTask -MockWith { + @{ + TaskName = $testParameters.TaskName + TaskPath = $testParameters.TaskPath + Actions = [pscustomobject] @{ + Execute = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' + } + Triggers = [pscustomobject] @{ + Repetition = @{ + Duration = "PT15M" + Interval = "PT15M" + } + CimClass = @{ + CimClassName = 'MSFT_TaskTimeTrigger' + } + } + Settings = [pscustomobject] @{ + Enabled = $true + } + } } It 'Should return the correct values from Get-TargetResource' { $result = Get-TargetResource @testParameters - $result.Ensure | Should Be 'Absent' + $result.Enable | Should -Be $true + $result.Ensure | Should -Be 'Present' } - It 'Should return true from the test method' { - Test-TargetResource @testParameters | Should Be $true + It 'Should return false from the test method' { + Test-TargetResource @testParameters | Should -Be $false + } + + It 'Should remove the scheduled task in the set method' { + Set-TargetResource @testParameters + Assert-MockCalled Register-ScheduledTask -Exactly -Times 1 } } - Context 'A scheduled task with Once based repetition exists, but has the wrong settings' { + Context 'A built-in scheduled task exists, but it should be absent' { $testParameters = @{ TaskName = 'Test task' TaskPath = '\Test\' - ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' - ScheduleType = 'Once' - RepeatInterval = (New-TimeSpan -Minutes 15).ToString() - RepetitionDuration = (New-TimeSpan -Minutes 150).ToString() - Verbose = $True + Ensure = 'Absent' + Verbose = $True } - Mock -CommandName Get-ScheduledTask { return @{ + Mock -CommandName Get-ScheduledTask -MockWith { + @{ TaskName = $testParameters.TaskName TaskPath = $testParameters.TaskPath - Actions = @(@{ + Actions = @( + [pscustomobject] @{ + Execute = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' + } + ) + Triggers = @( + [pscustomobject] @{ + Repetition = @{ + Duration = "PT15M" + Interval = "PT15M" + } + CimClass = @{ + CimClassName = 'MSFT_TaskTimeTrigger' + } + } + ) + Settings = [pscustomobject] @{ + Enabled = $true + } + } + } + + It 'Should return the correct values from Get-TargetResource' { + $result = Get-TargetResource @testParameters + $result.Enable | Should -Be $true + $result.Ensure | Should -Be 'Present' + } + + It 'Should return false from the test method' { + Test-TargetResource @testParameters | Should -Be $false + } + + It 'Should remove the scheduled task in the set method' { + Set-TargetResource @testParameters + Assert-MockCalled Unregister-ScheduledTask -Exactly -Times 1 + } + } + + Context 'A scheduled task doesnt exist, and it should not' { + $testParameters = @{ + TaskName = 'Test task' + TaskPath = '\Test\' + ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' + ScheduleType = 'Once' + Ensure = 'Absent' + Verbose = $True + } + + Mock -CommandName Get-ScheduledTask + + It 'Should return the correct values from Get-TargetResource' { + $result = Get-TargetResource @testParameters + $result.Ensure | Should -Be 'Absent' + } + + It 'Should return true from the test method' { + Test-TargetResource @testParameters | Should -Be $true + } + } + + Context 'A scheduled task with Once based repetition exists, but has the wrong settings' { + $testParameters = @{ + TaskName = 'Test task' + TaskPath = '\Test\' + ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' + ScheduleType = 'Once' + RepeatInterval = (New-TimeSpan -Minutes 15).ToString() + RepetitionDuration = (New-TimeSpan -Minutes 150).ToString() + Verbose = $True + } + + Mock -CommandName Get-ScheduledTask -MockWith { + @{ + TaskName = $testParameters.TaskName + TaskPath = $testParameters.TaskPath + Actions = @( + [pscustomobject] @{ Execute = $testParameters.ActionExecutable - }) - Triggers = @(@{ + } + ) + Triggers = @( + [pscustomobject] @{ Repetition = @{ Duration = '' Interval = "PT$(([System.TimeSpan]::Parse($testParameters.RepeatInterval).TotalMinutes) + 1)M" } - CimClass = @{ + CimClass = @{ CimClassName = 'MSFT_TaskTimeTrigger' } - }) - Principal = @{ + } + ) + Principal = [pscustomobject] @{ UserId = 'SYSTEM' } - } } + } + } It 'Should return the correct values from Get-TargetResource' { $result = Get-TargetResource @testParameters - $result.Ensure | Should Be 'Present' + $result.Ensure | Should -Be 'Present' } It 'Should return false from the test method' { - Test-TargetResource @testParameters | Should Be $false + Test-TargetResource @testParameters | Should -Be $false } It 'Should update the scheduled task in the set method' { @@ -186,83 +319,95 @@ try Context 'A scheduled task with minutes based repetition exists and has the correct settings' { $testParameters = @{ - TaskName = 'Test task' - TaskPath = '\Test\' - ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' - ScheduleType = 'Once' - RepeatInterval = (New-TimeSpan -Minutes 15).ToString() + TaskName = 'Test task' + TaskPath = '\Test\' + ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' + ScheduleType = 'Once' + RepeatInterval = (New-TimeSpan -Minutes 15).ToString() RepetitionDuration = (New-TimeSpan -Minutes 30).ToString() - Verbose = $True + Verbose = $True } - Mock -CommandName Get-ScheduledTask { return @{ - TaskName = $testParameters.TaskName - TaskPath = $testParameters.TaskPath - Actions = @(@{ + Mock -CommandName Get-ScheduledTask -MockWith { + @{ + TaskName = $testParameters.TaskName + TaskPath = $testParameters.TaskPath + Actions = @( + [pscustomobject] @{ Execute = $testParameters.ActionExecutable - }) - Triggers = @(@{ + } + ) + Triggers = @( + [pscustomobject] @{ Repetition = @{ Duration = "PT$([System.TimeSpan]::Parse($testParameters.RepetitionDuration).TotalMinutes)M" Interval = "PT$([System.TimeSpan]::Parse($testParameters.RepeatInterval).TotalMinutes)M" } - CimClass = @{ + CimClass = @{ CimClassName = 'MSFT_TaskTimeTrigger' } - }) - Principal = @{ + } + ) + Principal = [pscustomobject] @{ UserId = 'SYSTEM' } - } } + } + } It 'Should return the correct values from Get-TargetResource' { $result = Get-TargetResource @testParameters - $result.Ensure | Should Be 'Present' + $result.Ensure | Should -Be 'Present' } It 'Should return true from the test method' { - Test-TargetResource @testParameters | Should Be $true + Test-TargetResource @testParameters | Should -Be $true } } Context 'A scheduled task with hourly based repetition exists, but has the wrong settings' { $testParameters = @{ - TaskName = 'Test task' - TaskPath = '\Test\' - ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' - ScheduleType = 'Once' - RepeatInterval = (New-TimeSpan -Hours 4).ToString() + TaskName = 'Test task' + TaskPath = '\Test\' + ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' + ScheduleType = 'Once' + RepeatInterval = (New-TimeSpan -Hours 4).ToString() RepetitionDuration = (New-TimeSpan -Hours 8).ToString() - Verbose = $True + Verbose = $True } - Mock -CommandName Get-ScheduledTask { return @{ - TaskName = $testParameters.TaskName - TaskPath = $testParameters.TaskPath - Actions = @(@{ + Mock -CommandName Get-ScheduledTask -MockWith { + @{ + TaskName = $testParameters.TaskName + TaskPath = $testParameters.TaskPath + Actions = @( + [pscustomobject] @{ Execute = $testParameters.ActionExecutable - }) - Triggers = @(@{ + } + ) + Triggers = @( + [pscustomobject] @{ Repetition = @{ Duration = "PT$(([System.TimeSpan]::Parse($testParameters.RepetitionDuration).TotalHours))H" Interval = "PT$(([System.TimeSpan]::Parse($testParameters.RepeatInterval).TotalHours) + 1)H" } - CimClass = @{ + CimClass = @{ CimClassName = 'MSFT_TaskTimeTrigger' } - }) - Principal = @{ + } + ) + Principal = [pscustomobject] @{ UserId = 'SYSTEM' } - } } + } + } It 'Should return the correct values from Get-TargetResource' { $result = Get-TargetResource @testParameters - $result.Ensure | Should Be 'Present' + $result.Ensure | Should -Be 'Present' } It 'Should return false from the test method' { - Test-TargetResource @testParameters | Should Be $false + Test-TargetResource @testParameters | Should -Be $false } It 'Should update the scheduled task in the set method' { @@ -274,82 +419,94 @@ try Context 'A scheduled task with hourly based repetition exists and has the correct settings' { $testParameters = @{ - TaskName = 'Test task' - TaskPath = '\Test\' - ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' - ScheduleType = 'Once' - RepeatInterval = (New-TimeSpan -Hours 4).ToString() + TaskName = 'Test task' + TaskPath = '\Test\' + ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' + ScheduleType = 'Once' + RepeatInterval = (New-TimeSpan -Hours 4).ToString() RepetitionDuration = (New-TimeSpan -Hours 8).ToString() - Verbose = $True + Verbose = $True } - Mock -CommandName Get-ScheduledTask { return @{ - TaskName = $testParameters.TaskName - TaskPath = $testParameters.TaskPath - Actions = @(@{ + Mock -CommandName Get-ScheduledTask -MockWith { + @{ + TaskName = $testParameters.TaskName + TaskPath = $testParameters.TaskPath + Actions = @( + [pscustomobject] @{ Execute = $testParameters.ActionExecutable - }) - Triggers = @(@{ + } + ) + Triggers = @( + [pscustomobject] @{ Repetition = @{ Duration = "PT$([System.TimeSpan]::Parse($testParameters.RepetitionDuration).TotalHours)H" Interval = "PT$([System.TimeSpan]::Parse($testParameters.RepeatInterval).TotalHours)H" } - CimClass = @{ + CimClass = @{ CimClassName = 'MSFT_TaskTimeTrigger' } - }) - Principal = @{ + } + ) + Principal = [pscustomobject] @{ UserId = 'SYSTEM' } - } } + } + } It 'Should return the correct values from Get-TargetResource' { $result = Get-TargetResource @testParameters - $result.Ensure | Should Be 'Present' + $result.Ensure | Should -Be 'Present' } It 'Should return true from the test method' { - Test-TargetResource @testParameters | Should Be $true + Test-TargetResource @testParameters | Should -Be $true } } Context 'A scheduled task with daily based repetition exists, but has the wrong settings' { $testParameters = @{ - TaskName = 'Test task' - TaskPath = '\Test\' + TaskName = 'Test task' + TaskPath = '\Test\' ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' - ScheduleType = 'Daily' - DaysInterval = 3 - Verbose = $True + ScheduleType = 'Daily' + DaysInterval = 3 + Verbose = $True } - Mock -CommandName Get-ScheduledTask { return @{ - TaskName = $testParameters.TaskName - TaskPath = $testParameters.TaskPath - Actions = @(@{ + Mock -CommandName Get-ScheduledTask -MockWith { + @{ + TaskName = $testParameters.TaskName + TaskPath = $testParameters.TaskPath + Actions = @( + [pscustomobject] @{ Execute = $testParameters.ActionExecutable - }) - Triggers = @(@{ + } + ) + Triggers = @( + [pscustomobject] @{ Repetition = @{ Duration = $null Interval = "P$(($testParameters.DaysInterval) + 1)D" } - CimClass = @{ + CimClass = @{ CimClassName = 'MSFT_TaskDailyTrigger' } - }) - Principal = @{ + } + ) + Principal = [pscustomobject] @{ UserId = 'SYSTEM' } - } } + } + } It 'Should return the correct values from Get-TargetResource' { $result = Get-TargetResource @testParameters - $result.Ensure | Should Be 'Present' + $result.Ensure | Should -Be 'Present' } It 'Should return false from the test method' { - Test-TargetResource @testParameters | Should Be $false + Test-TargetResource @testParameters | Should -Be $false } It 'Should update the scheduled task in the set method' { @@ -361,80 +518,92 @@ try Context 'A scheduled task with daily based repetition exists and has the correct settings' { $testParameters = @{ - TaskName = 'Test task' - TaskPath = '\Test\' + TaskName = 'Test task' + TaskPath = '\Test\' ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' - ScheduleType = 'Daily' - DaysInterval = 3 - Verbose = $True + ScheduleType = 'Daily' + DaysInterval = 3 + Verbose = $True } - Mock -CommandName Get-ScheduledTask { return @{ - TaskName = $testParameters.TaskName - TaskPath = $testParameters.TaskPath - Actions = @(@{ + Mock -CommandName Get-ScheduledTask -MockWith { + @{ + TaskName = $testParameters.TaskName + TaskPath = $testParameters.TaskPath + Actions = @( + [pscustomobject] @{ Execute = $testParameters.ActionExecutable - }) - Triggers = @(@{ + } + ) + Triggers = @( + [pscustomobject] @{ DaysInterval = $testParameters.DaysInterval - CimClass = @{ + CimClass = @{ CimClassName = 'MSFT_TaskDailyTrigger' } - }) - Principal = @{ + } + ) + Principal = [pscustomobject] @{ UserId = 'SYSTEM' } - } } + } + } It 'Should return the correct values from Get-TargetResource' { $result = Get-TargetResource @testParameters - $result.Ensure | Should Be 'Present' + $result.Ensure | Should -Be 'Present' } It 'Should return true from the test method' { - Test-TargetResource @testParameters | Should Be $true + Test-TargetResource @testParameters | Should -Be $true } } Context 'A scheduled task exists and is configured with the wrong execution account' { $testParameters = @{ - TaskName = 'Test task' - TaskPath = '\Test\' - ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' - ScheduleType = 'Once' - RepeatInterval = (New-TimeSpan -Minutes 15).ToString() - RepetitionDuration = (New-TimeSpan -Hours 8).ToString() + TaskName = 'Test task' + TaskPath = '\Test\' + ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' + ScheduleType = 'Once' + RepeatInterval = (New-TimeSpan -Minutes 15).ToString() + RepetitionDuration = (New-TimeSpan -Hours 8).ToString() ExecuteAsCredential = New-Object System.Management.Automation.PSCredential ('DEMO\RightUser', (ConvertTo-SecureString 'ExamplePassword' -AsPlainText -Force)) - Verbose = $True + Verbose = $True } - Mock -CommandName Get-ScheduledTask { return @{ - TaskName = $testParameters.TaskName - TaskPath = $testParameters.TaskPath - Actions = @(@{ + Mock -CommandName Get-ScheduledTask -MockWith { + @{ + TaskName = $testParameters.TaskName + TaskPath = $testParameters.TaskPath + Actions = @( + [pscustomobject] @{ Execute = $testParameters.ActionExecutable - }) - Triggers = @(@{ + } + ) + Triggers = @( + [pscustomobject] @{ Repetition = @{ Duration = "PT$([System.TimeSpan]::Parse($testParameters.RepetitionDuration).TotalHours)H" Interval = "PT$([System.TimeSpan]::Parse($testParameters.RepeatInterval).TotalMinutes)M" } - CimClass = @{ + CimClass = @{ CimClassName = 'MSFT_TaskTimeTrigger' } - }) - Principal = @{ + } + ) + Principal = [pscustomobject] @{ UserId = 'WrongUser' } - } } + } + } It 'Should return the correct values from Get-TargetResource' { $result = Get-TargetResource @testParameters - $result.Ensure | Should Be 'Present' + $result.Ensure | Should -Be 'Present' } It 'Should return false from the test method' { - Test-TargetResource @testParameters | Should Be $false + Test-TargetResource @testParameters | Should -Be $false } It 'Should update the scheduled task in the set method' { @@ -446,46 +615,52 @@ try Context 'A scheduled task exists and is configured with the wrong logon type' { $testParameters = @{ - TaskName = 'Test task' - TaskPath = '\Test\' - ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' - ScheduleType = 'Once' - RepeatInterval = (New-TimeSpan -Minutes 15).ToString() - RepetitionDuration = (New-TimeSpan -Hours 8).ToString() + TaskName = 'Test task' + TaskPath = '\Test\' + ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' + ScheduleType = 'Once' + RepeatInterval = (New-TimeSpan -Minutes 15).ToString() + RepetitionDuration = (New-TimeSpan -Hours 8).ToString() ExecuteAsCredential = New-Object System.Management.Automation.PSCredential ('DEMO\RightUser', (ConvertTo-SecureString 'ExamplePassword' -AsPlainText -Force)) - LogonType = 'S4U' - Verbose = $True + LogonType = 'S4U' + Verbose = $True } - Mock -CommandName Get-ScheduledTask { return @{ - TaskName = $testParameters.TaskName - TaskPath = $testParameters.TaskPath - Actions = @(@{ + Mock -CommandName Get-ScheduledTask -MockWith { + @{ + TaskName = $testParameters.TaskName + TaskPath = $testParameters.TaskPath + Actions = [pscustomobject] @( + @{ Execute = $testParameters.ActionExecutable - }) - Triggers = @(@{ + } + ) + Triggers = @( + [pscustomobject] @{ Repetition = @{ Duration = "PT$([System.TimeSpan]::Parse($testParameters.RepetitionDuration).TotalHours)H" Interval = "PT$([System.TimeSpan]::Parse($testParameters.RepeatInterval).TotalMinutes)M" } - CimClass = @{ + CimClass = @{ CimClassName = 'MSFT_TaskTimeTrigger' } - }) - Principal = @{ - UserId = 'DEMO\RightUser' + } + ) + Principal = [pscustomobject] @{ + UserId = 'DEMO\RightUser' LogonType = 'Password' } - } } + } + } It 'Should return the correct values from Get-TargetResource' { $result = Get-TargetResource @testParameters - $result.Ensure | Should Be 'Present' - $result.LogonType | Should Be 'Password' + $result.Ensure | Should -Be 'Present' + $result.LogonType | Should -Be 'Password' } It 'Should return false from the test method' { - Test-TargetResource @testParameters | Should Be $false + Test-TargetResource @testParameters | Should -Be $false } It 'Should update the scheduled task in the set method' { @@ -497,46 +672,52 @@ try Context 'A scheduled task exists and is configured with the wrong run level' { $testParameters = @{ - TaskName = 'Test task' - TaskPath = '\Test\' - ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' - ScheduleType = 'Once' - RepeatInterval = (New-TimeSpan -Minutes 15).ToString() - RepetitionDuration = (New-TimeSpan -Hours 8).ToString() + TaskName = 'Test task' + TaskPath = '\Test\' + ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' + ScheduleType = 'Once' + RepeatInterval = (New-TimeSpan -Minutes 15).ToString() + RepetitionDuration = (New-TimeSpan -Hours 8).ToString() ExecuteAsCredential = New-Object System.Management.Automation.PSCredential ('DEMO\RightUser', (ConvertTo-SecureString 'ExamplePassword' -AsPlainText -Force)) - RunLevel = 'Highest' - Verbose = $True + RunLevel = 'Highest' + Verbose = $True } - Mock -CommandName Get-ScheduledTask { return @{ - TaskName = $testParameters.TaskName - TaskPath = $testParameters.TaskPath - Actions = @(@{ + Mock -CommandName Get-ScheduledTask -MockWith { + @{ + TaskName = $testParameters.TaskName + TaskPath = $testParameters.TaskPath + Actions = @( + [pscustomobject] @{ Execute = $testParameters.ActionExecutable - }) - Triggers = @(@{ + } + ) + Triggers = @( + [pscustomobject] @{ Repetition = @{ Duration = "PT$([System.TimeSpan]::Parse($testParameters.RepetitionDuration).TotalHours)H" Interval = "PT$([System.TimeSpan]::Parse($testParameters.RepeatInterval).TotalMinutes)M" } - CimClass = @{ + CimClass = @{ CimClassName = 'MSFT_TaskTimeTrigger' } - }) - Principal = @{ - UserId = 'DEMO\RightUser' + } + ) + Principal = [pscustomobject] @{ + UserId = 'DEMO\RightUser' RunLevel = 'Limited' } - } } + } + } It 'Should return the correct values from Get-TargetResource' { $result = Get-TargetResource @testParameters - $result.Ensure | Should Be 'Present' - $result.RunLevel | Should Be 'Limited' + $result.Ensure | Should -Be 'Present' + $result.RunLevel | Should -Be 'Limited' } It 'Should return false from the test method' { - Test-TargetResource @testParameters | Should Be $false + Test-TargetResource @testParameters | Should -Be $false } It 'Should update the scheduled task in the set method' { @@ -548,44 +729,50 @@ try Context 'A scheduled task exists and is configured with the wrong working directory' { $testParameters = @{ - TaskName = 'Test task' - TaskPath = '\Test\' - ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' - ActionWorkingPath = 'C:\Example' - ScheduleType = 'Once' - RepeatInterval = (New-TimeSpan -Minutes 15).ToString() + TaskName = 'Test task' + TaskPath = '\Test\' + ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' + ActionWorkingPath = 'C:\Example' + ScheduleType = 'Once' + RepeatInterval = (New-TimeSpan -Minutes 15).ToString() RepetitionDuration = (New-TimeSpan -Hours 8).ToString() - Verbose = $True + Verbose = $True } - Mock -CommandName Get-ScheduledTask { return @{ - TaskName = $testParameters.TaskName - TaskPath = $testParameters.TaskPath - Actions = @(@{ - Execute = $testParameters.ActionExecutable + Mock -CommandName Get-ScheduledTask -MockWith { + @{ + TaskName = $testParameters.TaskName + TaskPath = $testParameters.TaskPath + Actions = @( + [pscustomobject] @{ + Execute = $testParameters.ActionExecutable WorkingDirectory = 'C:\Wrong' - }) - Triggers = @(@{ + } + ) + Triggers = @( + [pscustomobject] @{ Repetition = @{ Duration = $null Interval = "PT$([System.TimeSpan]::Parse($testParameters.RepeatInterval).TotalMinutes)M" } - CimClass = @{ + CimClass = @{ CimClassName = 'MSFT_TaskTimeTrigger' } - }) - Principal = @{ + } + ) + Principal = [pscustomobject] @{ UserId = 'SYSTEM' } - } } + } + } It 'Should return the correct values from Get-TargetResource' { $result = Get-TargetResource @testParameters - $result.Ensure | Should Be 'Present' + $result.Ensure | Should -Be 'Present' } It 'Should return false from the test method' { - Test-TargetResource @testParameters | Should Be $false + Test-TargetResource @testParameters | Should -Be $false } It 'Should update the scheduled task in the set method' { @@ -597,44 +784,50 @@ try Context 'A scheduled task exists and is configured with the wrong executable arguments' { $testParameters = @{ - TaskName = 'Test task' - TaskPath = '\Test\' - ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' - ActionArguments = '-File "C:\something\right.ps1"' - ScheduleType = 'Once' - RepeatInterval = (New-TimeSpan -Minutes 15).ToString() + TaskName = 'Test task' + TaskPath = '\Test\' + ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' + ActionArguments = '-File "C:\something\right.ps1"' + ScheduleType = 'Once' + RepeatInterval = (New-TimeSpan -Minutes 15).ToString() RepetitionDuration = (New-TimeSpan -Hours 8).ToString() - Verbose = $True + Verbose = $True } - Mock -CommandName Get-ScheduledTask { return @{ - TaskName = $testParameters.TaskName - TaskPath = $testParameters.TaskPath - Actions = @(@{ - Execute = $testParameters.ActionExecutable + Mock -CommandName Get-ScheduledTask -MockWith { + @{ + TaskName = $testParameters.TaskName + TaskPath = $testParameters.TaskPath + Actions = @( + [pscustomobject] @{ + Execute = $testParameters.ActionExecutable Arguments = '-File "C:\something\wrong.ps1"' - }) - Triggers = @(@{ + } + ) + Triggers = @( + [pscustomobject] @{ Repetition = @{ Duration = "PT$([System.TimeSpan]::Parse($testParameters.RepetitionDuration).TotalHours)H" Interval = "PT$([System.TimeSpan]::Parse($testParameters.RepeatInterval).TotalMinutes)M" } - CimClass = @{ + CimClass = @{ CimClassName = 'MSFT_TaskTimeTrigger' } - }) - Principal = @{ + } + ) + Principal = [pscustomobject] @{ UserId = 'SYSTEM' } - } } + } + } It 'Should return the correct values from Get-TargetResource' { $result = Get-TargetResource @testParameters - $result.Ensure | Should Be 'Present' + $result.Ensure | Should -Be 'Present' } It 'Should return false from the test method' { - Test-TargetResource @testParameters | Should Be $false + Test-TargetResource @testParameters | Should -Be $false } It 'Should update the scheduled task in the set method' { @@ -646,47 +839,53 @@ try Context 'A scheduled task is enabled and should be disabled' { $testParameters = @{ - TaskName = 'Test task' - TaskPath = '\Test\' - ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' - ScheduleType = 'Once' - RepeatInterval = (New-TimeSpan -Minutes 15).ToString() + TaskName = 'Test task' + TaskPath = '\Test\' + ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' + ScheduleType = 'Once' + RepeatInterval = (New-TimeSpan -Minutes 15).ToString() RepetitionDuration = (New-TimeSpan -Hours 8).ToString() - Enable = $false - Verbose = $True + Enable = $false + Verbose = $True } - Mock -CommandName Get-ScheduledTask { return @{ - TaskName = $testParameters.TaskName - TaskPath = $testParameters.TaskPath - Actions = @(@{ - Execute = $testParameters.ActionExecutable + Mock -CommandName Get-ScheduledTask -MockWith { + @{ + TaskName = $testParameters.TaskName + TaskPath = $testParameters.TaskPath + Actions = @( + [pscustomobject] @{ + Execute = $testParameters.ActionExecutable Arguments = $testParameters.Arguments - }) - Triggers = @(@{ + } + ) + Triggers = @( + [pscustomobject] @{ Repetition = @{ Duration = "PT$([System.TimeSpan]::Parse($testParameters.RepetitionDuration).TotalHours)H" Interval = "PT$([System.TimeSpan]::Parse($testParameters.RepeatInterval).TotalMinutes)M" } - CimClass = @{ + CimClass = @{ CimClassName = 'MSFT_TaskTimeTrigger' } - }) - Settings = @(@{ - Enabled = $true - }) - Principal = @{ + } + ) + Settings = [pscustomobject] @{ + Enabled = $true + } + Principal = [pscustomobject] @{ UserId = 'SYSTEM' } - } } + } + } It 'Should return the correct values from Get-TargetResource' { $result = Get-TargetResource @testParameters - $result.Ensure | Should Be 'Present' + $result.Ensure | Should -Be 'Present' } It 'Should return false from the test method' { - Test-TargetResource @testParameters | Should Be $false + Test-TargetResource @testParameters | Should -Be $false } It 'Should update the scheduled task in the set method' { @@ -699,49 +898,55 @@ try Context 'A scheduled task is enabled without an execution time limit and but has an execution time limit set' { $testParameters = @{ - TaskName = 'Test task' - TaskPath = '\Test\' - ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' - ScheduleType = 'Once' - RepeatInterval = (New-TimeSpan -Minutes 15).ToString() + TaskName = 'Test task' + TaskPath = '\Test\' + ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' + ScheduleType = 'Once' + RepeatInterval = (New-TimeSpan -Minutes 15).ToString() RepetitionDuration = (New-TimeSpan -Hours 8).ToString() ExecutionTimeLimit = (New-TimeSpan -Seconds 0).ToString() - Enable = $true - Verbose = $True + Enable = $true + Verbose = $True } - Mock -CommandName Get-ScheduledTask { return @{ - TaskName = $testParameters.TaskName - TaskPath = $testParameters.TaskPath - Actions = @(@{ - Execute = $testParameters.ActionExecutable + Mock -CommandName Get-ScheduledTask -MockWith { + @{ + TaskName = $testParameters.TaskName + TaskPath = $testParameters.TaskPath + Actions = @( + [pscustomobject] @{ + Execute = $testParameters.ActionExecutable Arguments = $testParameters.Arguments - }) - Triggers = @(@{ + } + ) + Triggers = @( + [pscustomobject] @{ Repetition = @{ Duration = "PT$([System.TimeSpan]::Parse($testParameters.RepetitionDuration).TotalHours)H" Interval = "PT$([System.TimeSpan]::Parse($testParameters.RepeatInterval).TotalMinutes)M" } - CimClass = @{ + CimClass = @{ CimClassName = 'MSFT_TaskTimeTrigger' } - }) - Settings = @(@{ - Enabled = $true - ExecutionTimeLimit = "PT$([System.TimeSpan]::Parse($testParameters.RepeatInterval).TotalSeconds + 60)S" - }) - Principal = @{ + } + ) + Settings = [pscustomobject] @{ + Enabled = $true + ExecutionTimeLimit = "PT$([System.TimeSpan]::Parse($testParameters.RepeatInterval).TotalSeconds + 60)S" + } + Principal = [pscustomobject] @{ UserId = 'SYSTEM' } - } } + } + } It 'Should return the correct values from Get-TargetResource' { $result = Get-TargetResource @testParameters - $result.Ensure | Should Be 'Present' + $result.Ensure | Should -Be 'Present' } It 'Should return false from the test method' { - Test-TargetResource @testParameters | Should Be $false + Test-TargetResource @testParameters | Should -Be $false } It 'Should update the scheduled task in the set method' { @@ -753,151 +958,169 @@ try Context 'A scheduled task is enabled and has the correct settings' { $testParameters = @{ - TaskName = 'Test task' - TaskPath = '\Test\' - ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' - ScheduleType = 'Once' - RepeatInterval = (New-TimeSpan -Minutes 15).ToString() + TaskName = 'Test task' + TaskPath = '\Test\' + ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' + ScheduleType = 'Once' + RepeatInterval = (New-TimeSpan -Minutes 15).ToString() RepetitionDuration = (New-TimeSpan -Hours 8).ToString() - RandomDelay = (New-TimeSpan -Minutes 4).ToString() - IdleWaitTimeout = (New-TimeSpan -Minutes 5).ToString() - IdleDuration = (New-TimeSpan -Minutes 6).ToString() + RandomDelay = (New-TimeSpan -Minutes 4).ToString() + IdleWaitTimeout = (New-TimeSpan -Minutes 5).ToString() + IdleDuration = (New-TimeSpan -Minutes 6).ToString() ExecutionTimeLimit = (New-TimeSpan -Minutes 7).ToString() - RestartInterval = (New-TimeSpan -Minutes 8).ToString() - Enable = $true - Verbose = $True - } - - Mock -CommandName Get-ScheduledTask { return @{ - TaskName = $testParameters.TaskName - TaskPath = $testParameters.TaskPath - Actions = @(@{ - Execute = $testParameters.ActionExecutable + RestartInterval = (New-TimeSpan -Minutes 8).ToString() + Enable = $true + Verbose = $True + } + + Mock -CommandName Get-ScheduledTask -MockWith { + @{ + TaskName = $testParameters.TaskName + TaskPath = $testParameters.TaskPath + Actions = @( + [pscustomobject] @{ + Execute = $testParameters.ActionExecutable Arguments = $testParameters.Arguments - }) - Triggers = @(@{ - Repetition = @{ + } + ) + Triggers = @( + [pscustomobject] @{ + Repetition = @{ Duration = "PT$([System.TimeSpan]::Parse($testParameters.RepetitionDuration).TotalHours)H" Interval = "PT$([System.TimeSpan]::Parse($testParameters.RepeatInterval).TotalMinutes)M" } RandomDelay = "PT$([System.TimeSpan]::Parse($testParameters.RandomDelay).TotalMinutes)M" - CimClass = @{ + CimClass = @{ CimClassName = 'MSFT_TaskTimeTrigger' } - }) - Settings = @(@{ - Enabled = $true - IdleSettings = @{ - IdleWaitTimeout = "PT$([System.TimeSpan]::Parse($testParameters.IdleWaitTimeout).TotalMinutes)M" - IdleDuration = "PT$([System.TimeSpan]::Parse($testParameters.IdleDuration).TotalMinutes)M" - } - ExecutionTimeLimit = "PT$([System.TimeSpan]::Parse($testParameters.ExecutionTimeLimit).TotalMinutes)M" - RestartInterval = "PT$([System.TimeSpan]::Parse($testParameters.RestartInterval).TotalMinutes)M" - }) - Principal = @{ + } + ) + Settings = [pscustomobject] @{ + Enabled = $true + IdleSettings = @{ + IdleWaitTimeout = "PT$([System.TimeSpan]::Parse($testParameters.IdleWaitTimeout).TotalMinutes)M" + IdleDuration = "PT$([System.TimeSpan]::Parse($testParameters.IdleDuration).TotalMinutes)M" + } + ExecutionTimeLimit = "PT$([System.TimeSpan]::Parse($testParameters.ExecutionTimeLimit).TotalMinutes)M" + RestartInterval = "PT$([System.TimeSpan]::Parse($testParameters.RestartInterval).TotalMinutes)M" + } + Principal = [pscustomobject] @{ UserId = 'SYSTEM' } - } } + } + } It 'Should return the correct values from Get-TargetResource' { $result = Get-TargetResource @testParameters - $result.Ensure | Should Be 'Present' + $result.Ensure | Should -Be 'Present' } It 'Should return true from the test method' { - Test-TargetResource @testParameters | Should Be $true + Test-TargetResource @testParameters | Should -Be $true } } Context 'A scheduled task is disabled and has the correct settings' { $testParameters = @{ - TaskName = 'Test task' - TaskPath = '\Test\' - ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' - ScheduleType = 'Once' - RepeatInterval = (New-TimeSpan -Minutes 15).ToString() + TaskName = 'Test task' + TaskPath = '\Test\' + ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' + ScheduleType = 'Once' + RepeatInterval = (New-TimeSpan -Minutes 15).ToString() RepetitionDuration = (New-TimeSpan -Hours 8).ToString() - Enable = $false - Verbose = $True + Enable = $false + Verbose = $True } - Mock -CommandName Get-ScheduledTask { return @{ - TaskName = $testParameters.TaskName - TaskPath = $testParameters.TaskPath - Actions = @(@{ - Execute = $testParameters.ActionExecutable + Mock -CommandName Get-ScheduledTask -MockWith { + @{ + TaskName = $testParameters.TaskName + TaskPath = $testParameters.TaskPath + Actions = @( + [pscustomobject] @{ + Execute = $testParameters.ActionExecutable Arguments = $testParameters.Arguments - }) - Triggers = @(@{ + } + ) + Triggers = @( + [pscustomobject] @{ Repetition = @{ Duration = "PT$([System.TimeSpan]::Parse($testParameters.RepetitionDuration).TotalHours)H" Interval = "PT$([System.TimeSpan]::Parse($testParameters.RepeatInterval).TotalMinutes)M" } - CimClass = @{ + CimClass = @{ CimClassName = 'MSFT_TaskTimeTrigger' } - }) - Settings = @(@{ - Enabled = $false - }) - Principal = @{ + } + ) + Settings = [pscustomobject] @{ + Enabled = $false + } + Principal = [pscustomobject] @{ UserId = 'SYSTEM' } - } } + } + } It 'Should return the correct values from Get-TargetResource' { $result = Get-TargetResource @testParameters - $result.Ensure | Should Be 'Present' + $result.Ensure | Should -Be 'Present' } It 'Should return true from the test method' { - Test-TargetResource @testParameters | Should Be $true + Test-TargetResource @testParameters | Should -Be $true } } Context 'A scheduled task is disabled but should be enabled' { $testParameters = @{ - TaskName = 'Test task' - TaskPath = '\Test\' - ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' - ScheduleType = 'Once' - RepeatInterval = (New-TimeSpan -Minutes 15).ToString() + TaskName = 'Test task' + TaskPath = '\Test\' + ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' + ScheduleType = 'Once' + RepeatInterval = (New-TimeSpan -Minutes 15).ToString() RepetitionDuration = (New-TimeSpan -Hours 8).ToString() - Enable = $true - Verbose = $True + Enable = $true + Verbose = $True } - Mock -CommandName Get-ScheduledTask { return @{ - TaskName = $testParameters.TaskName - TaskPath = $testParameters.TaskPath - Actions = @(@{ - Execute = $testParameters.ActionExecutable + Mock -CommandName Get-ScheduledTask -MockWith { + @{ + TaskName = $testParameters.TaskName + TaskPath = $testParameters.TaskPath + Actions = @( + [pscustomobject] @{ + Execute = $testParameters.ActionExecutable Arguments = $testParameters.Arguments - }) - Triggers = @(@{ + } + ) + Triggers = @( + [pscustomobject] @{ Repetition = @{ Duration = "PT$([System.TimeSpan]::Parse($testParameters.RepetitionDuration).TotalHours)H" Interval = "PT$([System.TimeSpan]::Parse($testParameters.RepeatInterval).TotalMinutes)M" } - CimClass = @{ + CimClass = @{ CimClassName = 'MSFT_TaskTimeTrigger' } - }) - Settings = @(@{ - Enabled = $false - }) - Principal = @{ + } + ) + Settings = [pscustomobject] @{ + Enabled = $false + } + Principal = [pscustomobject] @{ UserId = 'SYSTEM' } - } } + } + } It 'Should return the correct values from Get-TargetResource' { $result = Get-TargetResource @testParameters - $result.Ensure | Should Be 'Present' + $result.Ensure | Should -Be 'Present' } It 'Should return false from the test method' { - Test-TargetResource @testParameters | Should Be $false + Test-TargetResource @testParameters | Should -Be $false } It 'Should update the scheduled task in the set method' { @@ -909,124 +1132,136 @@ try Context 'A Scheduled task exists, is disabled, and the optional parameter enable is not specified' -Fixture { $testParameters = @{ - TaskName = 'Test task' - TaskPath = '\Test\' - ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' - ScheduleType = 'Once' - RepeatInterval = (New-TimeSpan -Minutes 15).ToString() + TaskName = 'Test task' + TaskPath = '\Test\' + ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' + ScheduleType = 'Once' + RepeatInterval = (New-TimeSpan -Minutes 15).ToString() RepetitionDuration = (New-TimeSpan -Hours 8).ToString() - Verbose = $True + Verbose = $True } - Mock -CommandName Get-ScheduledTask { return @{ - TaskName = $testParameters.TaskName - TaskPath = $testParameters.TaskPath - Actions = @(@{ - Execute = $testParameters.ActionExecutable + Mock -CommandName Get-ScheduledTask -MockWith { + @{ + TaskName = $testParameters.TaskName + TaskPath = $testParameters.TaskPath + Actions = @( + [pscustomobject] @{ + Execute = $testParameters.ActionExecutable Arguments = $testParameters.Arguments - }) - Triggers = @(@{ + } + ) + Triggers = @( + [pscustomobject] @{ Repetition = @{ Duration = "PT$([System.TimeSpan]::Parse($testParameters.RepetitionDuration).TotalHours)H" Interval = "PT$([System.TimeSpan]::Parse($testParameters.RepeatInterval).TotalMinutes)M" } - CimClass = @{ + CimClass = @{ CimClassName = 'MSFT_TaskTimeTrigger' } - }) - Settings = @(@{ - Enabled = $false - }) - Principal = @{ + } + ) + Settings = [pscustomobject] @{ + Enabled = $false + } + Principal = [pscustomobject] @{ UserId = 'SYSTEM' } - } } + } + } It 'Should return the correct values from Get-TargetResource' { $result = Get-TargetResource @testParameters - $result.Ensure | Should Be 'Present' + $result.Ensure | Should -Be 'Present' } It 'Should return true from the test method' { - Test-TargetResource @testParameters | Should Be $true + Test-TargetResource @testParameters | Should -Be $true } } Context 'A scheduled task path is root or custom' -Fixture { It 'Should return backslash' { - ConvertTo-NormalizedTaskPath -TaskPath '\'| Should Be '\' + ConvertTo-NormalizedTaskPath -TaskPath '\'| Should -Be '\' } It 'Should add backslash at the end' { - ConvertTo-NormalizedTaskPath -TaskPath '\Test'| Should Be '\Test\' + ConvertTo-NormalizedTaskPath -TaskPath '\Test'| Should -Be '\Test\' } It 'Should add backslash at the beginning' { - ConvertTo-NormalizedTaskPath -TaskPath 'Test\'| Should Be '\Test\' + ConvertTo-NormalizedTaskPath -TaskPath 'Test\'| Should -Be '\Test\' } It 'Should add backslash at the beginning and at the end' { - ConvertTo-NormalizedTaskPath -TaskPath 'Test'| Should Be '\Test\' + ConvertTo-NormalizedTaskPath -TaskPath 'Test'| Should -Be '\Test\' } It 'Should not add backslash' { - ConvertTo-NormalizedTaskPath -TaskPath '\Test\'| Should Be '\Test\' + ConvertTo-NormalizedTaskPath -TaskPath '\Test\'| Should -Be '\Test\' } } Context 'A scheduled task exists and is configured with the wrong interval, duration & random delay parameters' { $testParameters = @{ - TaskName = 'Test task' - TaskPath = '\Test\' - ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' - ScheduleType = 'Once' - RepeatInterval = (New-TimeSpan -Minutes 20).ToString() + TaskName = 'Test task' + TaskPath = '\Test\' + ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' + ScheduleType = 'Once' + RepeatInterval = (New-TimeSpan -Minutes 20).ToString() RepetitionDuration = (New-TimeSpan -Hours 9).ToString() - RandomDelay = (New-TimeSpan -Minutes 4).ToString() - IdleWaitTimeout = (New-TimeSpan -Minutes 5).ToString() - IdleDuration = (New-TimeSpan -Minutes 6).ToString() + RandomDelay = (New-TimeSpan -Minutes 4).ToString() + IdleWaitTimeout = (New-TimeSpan -Minutes 5).ToString() + IdleDuration = (New-TimeSpan -Minutes 6).ToString() ExecutionTimeLimit = (New-TimeSpan -Minutes 7).ToString() - RestartInterval = (New-TimeSpan -Minutes 8).ToString() - Verbose = $True + RestartInterval = (New-TimeSpan -Minutes 8).ToString() + Verbose = $True } - Mock -CommandName Get-ScheduledTask { return @{ - TaskName = $testParameters.TaskName - TaskPath = $testParameters.TaskPath - Actions = @(@{ - Execute = $testParameters.ActionExecutable + Mock -CommandName Get-ScheduledTask -MockWith { + @{ + TaskName = $testParameters.TaskName + TaskPath = $testParameters.TaskPath + Actions = @( + [pscustomobject] @{ + Execute = $testParameters.ActionExecutable Arguments = $testParameters.Arguments - }) - Triggers = @(@{ - Repetition = @{ + } + ) + Triggers = @( + [pscustomobject] @{ + Repetition = @{ Duration = "PT$([System.TimeSpan]::Parse($testParameters.RepetitionDuration).TotalHours + 1)H" Interval = "PT$([System.TimeSpan]::Parse($testParameters.RepeatInterval).TotalMinutes + 1)M" } RandomDelay = "PT$([System.TimeSpan]::Parse($testParameters.RandomDelay).TotalMinutes + 1)M" - CimClass = @{ + CimClass = @{ CimClassName = 'MSFT_TaskTimeTrigger' } - }) - Settings = @{ - IdleSettings = @{ + } + ) + Settings = [pscustomobject] @{ + IdleSettings = @{ IdleWaitTimeout = "PT$([System.TimeSpan]::Parse($testParameters.IdleWaitTimeout).TotalMinutes)M" - IdleDuration = "PT$([System.TimeSpan]::Parse($testParameters.IdleDuration).TotalMinutes)M" + IdleDuration = "PT$([System.TimeSpan]::Parse($testParameters.IdleDuration).TotalMinutes)M" } ExecutionTimeLimit = "PT$([System.TimeSpan]::Parse($testParameters.ExecutionTimeLimit).TotalMinutes)M" - RestartInterval = "PT$([System.TimeSpan]::Parse($testParameters.RestartInterval).TotalMinutes)M" + RestartInterval = "PT$([System.TimeSpan]::Parse($testParameters.RestartInterval).TotalMinutes)M" } - Principal = @{ + Principal = [pscustomobject] @{ UserId = 'SYSTEM' } - } } + } + } It 'Should return the correct values from Get-TargetResource' { $result = Get-TargetResource @testParameters - $result.Ensure | Should Be 'Present' + $result.Ensure | Should -Be 'Present' } It 'Should return false from the test method' { - Test-TargetResource @testParameters | Should Be $false + Test-TargetResource @testParameters | Should -Be $false } It 'Should update the scheduled task in the set method' { @@ -1038,57 +1273,63 @@ try Context 'A scheduled task exists and is configured with the wrong idle timeout & idle duration parameters' { $testParameters = @{ - TaskName = 'Test task' - TaskPath = '\Test\' - ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' - ScheduleType = 'Once' - RepeatInterval = (New-TimeSpan -Minutes 20).ToString() + TaskName = 'Test task' + TaskPath = '\Test\' + ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' + ScheduleType = 'Once' + RepeatInterval = (New-TimeSpan -Minutes 20).ToString() RepetitionDuration = (New-TimeSpan -Hours 9).ToString() - RandomDelay = (New-TimeSpan -Minutes 4).ToString() - IdleWaitTimeout = (New-TimeSpan -Minutes 5).ToString() - IdleDuration = (New-TimeSpan -Minutes 6).ToString() + RandomDelay = (New-TimeSpan -Minutes 4).ToString() + IdleWaitTimeout = (New-TimeSpan -Minutes 5).ToString() + IdleDuration = (New-TimeSpan -Minutes 6).ToString() ExecutionTimeLimit = (New-TimeSpan -Minutes 7).ToString() - RestartInterval = (New-TimeSpan -Minutes 8).ToString() - Verbose = $True + RestartInterval = (New-TimeSpan -Minutes 8).ToString() + Verbose = $True } - Mock -CommandName Get-ScheduledTask { return @{ - TaskName = $testParameters.TaskName - TaskPath = $testParameters.TaskPath - Actions = @(@{ - Execute = $testParameters.ActionExecutable + Mock -CommandName Get-ScheduledTask -MockWith { + @{ + TaskName = $testParameters.TaskName + TaskPath = $testParameters.TaskPath + Actions = @( + [pscustomobject] @{ + Execute = $testParameters.ActionExecutable Arguments = $testParameters.Arguments - }) - Triggers = @(@{ - Repetition = @{ + } + ) + Triggers = @( + [pscustomobject] @{ + Repetition = @{ Duration = "PT$([System.TimeSpan]::Parse($testParameters.RepetitionDuration).TotalHours)H" Interval = "PT$([System.TimeSpan]::Parse($testParameters.RepeatInterval).TotalMinutes)M" } RandomDelay = "PT$([System.TimeSpan]::Parse($testParameters.RandomDelay).TotalMinutes)M" - CimClass = @{ + CimClass = @{ CimClassName = 'MSFT_TaskTimeTrigger' } - }) - Settings = @{ - IdleSettings = @{ + } + ) + Settings = [pscustomobject] @{ + IdleSettings = @{ IdleWaitTimeout = "PT$([System.TimeSpan]::Parse($testParameters.IdleWaitTimeout).TotalMinutes + 1)M" - IdleDuration = "PT$([System.TimeSpan]::Parse($testParameters.IdleDuration).TotalMinutes + 1)M" + IdleDuration = "PT$([System.TimeSpan]::Parse($testParameters.IdleDuration).TotalMinutes + 1)M" } ExecutionTimeLimit = "PT$([System.TimeSpan]::Parse($testParameters.ExecutionTimeLimit).TotalMinutes)M" - RestartInterval = "PT$([System.TimeSpan]::Parse($testParameters.RestartInterval).TotalMinutes)M" + RestartInterval = "PT$([System.TimeSpan]::Parse($testParameters.RestartInterval).TotalMinutes)M" } - Principal = @{ + Principal = [pscustomobject] @{ UserId = 'SYSTEM' } - } } + } + } It 'Should return the correct values from Get-TargetResource' { $result = Get-TargetResource @testParameters - $result.Ensure | Should Be 'Present' + $result.Ensure | Should -Be 'Present' } It 'Should return false from the test method' { - Test-TargetResource @testParameters | Should Be $false + Test-TargetResource @testParameters | Should -Be $false } It 'Should update the scheduled task in the set method' { @@ -1100,43 +1341,49 @@ try Context 'A scheduled task exists and is configured with the wrong duration parameter for an indefinite trigger' { $testParameters = @{ - TaskName = 'Test task' - TaskPath = '\Test\' - ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' - ScheduleType = 'Once' - RepeatInterval = (New-TimeSpan -Minutes 20).ToString() + TaskName = 'Test task' + TaskPath = '\Test\' + ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' + ScheduleType = 'Once' + RepeatInterval = (New-TimeSpan -Minutes 20).ToString() RepetitionDuration = 'Indefinitely' - Verbose = $True + Verbose = $True } - Mock -CommandName Get-ScheduledTask { return @{ - TaskName = $testParameters.TaskName - TaskPath = $testParameters.TaskPath - Actions = @(@{ - Execute = $testParameters.ActionExecutable + Mock -CommandName Get-ScheduledTask -MockWith { + @{ + TaskName = $testParameters.TaskName + TaskPath = $testParameters.TaskPath + Actions = @( + [pscustomobject] @{ + Execute = $testParameters.ActionExecutable Arguments = $testParameters.Arguments - }) - Triggers = @(@{ + } + ) + Triggers = @( + [pscustomobject] @{ Repetition = @{ - Duration = "PT4H" + Duration = 'PT4H' Interval = "PT$([System.TimeSpan]::Parse($testParameters.RepeatInterval).TotalMinutes)M" } - CimClass = @{ + CimClass = @{ CimClassName = 'MSFT_TaskTimeTrigger' } - }) - Principal = @{ + } + ) + Principal = [pscustomobject] @{ UserId = 'SYSTEM' } - } } + } + } It 'Should return the correct values from Get-TargetResource' { $result = Get-TargetResource @testParameters - $result.Ensure | Should Be 'Present' + $result.Ensure | Should -Be 'Present' } It 'Should return false from the test method' { - Test-TargetResource @testParameters | Should Be $false + Test-TargetResource @testParameters | Should -Be $false } It 'Should update the scheduled task in the set method' { @@ -1148,43 +1395,49 @@ try Context 'A scheduled task exists and is configured with indefinite repetition duration for a trigger but should be fixed' { $testParameters = @{ - TaskName = 'Test task' - TaskPath = '\Test\' - ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' - ScheduleType = 'Once' - RepeatInterval = (New-TimeSpan -Minutes 20).ToString() + TaskName = 'Test task' + TaskPath = '\Test\' + ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' + ScheduleType = 'Once' + RepeatInterval = (New-TimeSpan -Minutes 20).ToString() RepetitionDuration = (New-TimeSpan -Hours 9).ToString() - Verbose = $True + Verbose = $True } - Mock -CommandName Get-ScheduledTask { return @{ - TaskName = $testParameters.TaskName - TaskPath = $testParameters.TaskPath - Actions = @(@{ - Execute = $testParameters.ActionExecutable + Mock -CommandName Get-ScheduledTask -MockWith { + @{ + TaskName = $testParameters.TaskName + TaskPath = $testParameters.TaskPath + Actions = @( + [pscustomobject] @{ + Execute = $testParameters.ActionExecutable Arguments = $testParameters.Arguments - }) - Triggers = @(@{ + } + ) + Triggers = @( + [pscustomobject] @{ Repetition = @{ - Duration = "" + Duration = '' Interval = "PT$([System.TimeSpan]::Parse($testParameters.RepeatInterval).TotalMinutes)M" } - CimClass = @{ + CimClass = @{ CimClassName = 'MSFT_TaskTimeTrigger' } - }) - Principal = @{ + } + ) + Principal = [pscustomobject] @{ UserId = 'SYSTEM' } - } } + } + } It 'Should return the correct values from Get-TargetResource' { $result = Get-TargetResource @testParameters - $result.Ensure | Should Be 'Present' + $result.Ensure | Should -Be 'Present' } It 'Should return false from the test method' { - Test-TargetResource @testParameters | Should Be $false + Test-TargetResource @testParameters | Should -Be $false } It 'Should update the scheduled task in the set method' { @@ -1196,43 +1449,49 @@ try Context 'A scheduled task exists and is configured with correctly with an indefinite duration trigger' { $testParameters = @{ - TaskName = 'Test task' - TaskPath = '\Test\' - ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' - ScheduleType = 'Once' - RepeatInterval = (New-TimeSpan -Minutes 20).ToString() + TaskName = 'Test task' + TaskPath = '\Test\' + ActionExecutable = 'C:\windows\system32\WindowsPowerShell\v1.0\powershell.exe' + ScheduleType = 'Once' + RepeatInterval = (New-TimeSpan -Minutes 20).ToString() RepetitionDuration = 'Indefinitely' - Verbose = $True + Verbose = $True } - Mock -CommandName Get-ScheduledTask { return @{ - TaskName = $testParameters.TaskName - TaskPath = $testParameters.TaskPath - Actions = @(@{ - Execute = $testParameters.ActionExecutable + Mock -CommandName Get-ScheduledTask -MockWith { + @{ + TaskName = $testParameters.TaskName + TaskPath = $testParameters.TaskPath + Actions = @( + [pscustomobject] @{ + Execute = $testParameters.ActionExecutable Arguments = $testParameters.Arguments - }) - Triggers = @(@{ + } + ) + Triggers = @( + [pscustomobject] @{ Repetition = @{ - Duration = "" + Duration = '' Interval = "PT$([System.TimeSpan]::Parse($testParameters.RepeatInterval).TotalMinutes)M" } - CimClass = @{ + CimClass = @{ CimClassName = 'MSFT_TaskTimeTrigger' } - }) - Principal = @{ + } + ) + Principal = [pscustomobject] @{ UserId = 'SYSTEM' } - } } + } + } It 'Should return the correct values from Get-TargetResource' { $result = Get-TargetResource @testParameters - $result.Ensure | Should Be 'Present' + $result.Ensure | Should -Be 'Present' } It 'Should return true from the test method' { - Test-TargetResource @testParameters | Should Be $true + Test-TargetResource @testParameters | Should -Be $true } } } diff --git a/Tests/Unit/MSFT_xVirtualMemory.Tests.ps1 b/Tests/Unit/MSFT_xVirtualMemory.Tests.ps1 index 6a48cc3b..7ecd961d 100644 --- a/Tests/Unit/MSFT_xVirtualMemory.Tests.ps1 +++ b/Tests/Unit/MSFT_xVirtualMemory.Tests.ps1 @@ -5,7 +5,7 @@ $script:DSCResourceName = 'MSFT_xVirtualMemory' Import-Module -Name (Join-Path -Path (Join-Path -Path (Split-Path $PSScriptRoot -Parent) -ChildPath 'TestHelpers') -ChildPath 'CommonTestHelper.psm1') -Global # Unit Test Template Version: 1.2.0 -$script:moduleRoot = Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path)) +$script:moduleRoot = Join-Path -Path $(Split-Path -Parent (Split-Path -Parent (Split-Path -Parent $Script:MyInvocation.MyCommand.Path))) -ChildPath 'Modules\xComputerManagement' if ( (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests'))) -or ` (-not (Test-Path -Path (Join-Path -Path $script:moduleRoot -ChildPath 'DSCResource.Tests\TestHelper.psm1'))) ) { @@ -131,7 +131,7 @@ try { It 'Should return type set to AutoManagePagingFile' { $result = Get-TargetResource @testParameters - $result.Type | Should Be 'AutoManagePagingFile' + $result.Type | Should -Be 'AutoManagePagingFile' } It 'Should call the correct mocks' { @@ -154,7 +154,7 @@ try { It 'Should return type set to NoPagingFile' { $result = Get-TargetResource @testParameters - $result.Type | Should Be 'NoPagingFile' + $result.Type | Should -Be 'NoPagingFile' } It 'Should call the correct mocks' { @@ -189,8 +189,8 @@ try { It 'Should return a expected type and drive letter' { $result = Get-TargetResource @testParameters - $result.Type | Should Be 'SystemManagedSize' - $result.Drive | Should Be ([System.IO.DriveInfo] $testParameters.Drive).Name + $result.Type | Should -Be 'SystemManagedSize' + $result.Drive | Should -Be ([System.IO.DriveInfo] $testParameters.Drive).Name } It 'Should call the correct mocks' { @@ -225,8 +225,8 @@ try { It 'Should return expected type and drive letter' { $result = Get-TargetResource @testParameters - $result.Type | Should Be 'CustomSize' - $result.Drive | Should Be ([System.IO.DriveInfo] $testParameters.Drive).Name + $result.Type | Should -Be 'CustomSize' + $result.Drive | Should -Be ([System.IO.DriveInfo] $testParameters.Drive).Name } It 'Should call the correct mocks' { @@ -283,7 +283,7 @@ try { Verbose = $true } - { Set-TargetResource @testParameters } | Should Not Throw + { Set-TargetResource @testParameters } | Should -Not -Throw } It 'Should call the correct mocks' { @@ -335,7 +335,7 @@ try { Verbose = $true } - { Set-TargetResource @testParameters } | Should Not Throw + { Set-TargetResource @testParameters } | Should -Not -Throw } It 'Should call the correct mocks' { @@ -406,7 +406,7 @@ try { Verbose = $true } - { Set-TargetResource @testParameters } | Should Not Throw + { Set-TargetResource @testParameters } | Should -Not -Throw } It 'Should call the correct mocks' { @@ -473,7 +473,7 @@ try { Verbose = $true } - { Set-TargetResource @testParameters } | Should Not Throw + { Set-TargetResource @testParameters } | Should -Not -Throw } It 'Should call the correct mocks' { @@ -539,7 +539,7 @@ try { Verbose = $true } - { Set-TargetResource @testParameters } | Should Not Throw + { Set-TargetResource @testParameters } | Should -Not -Throw } It 'Should call the correct mocks' { @@ -597,7 +597,7 @@ try { Verbose = $true } - { Set-TargetResource @testParameters } | Should Not Throw + { Set-TargetResource @testParameters } | Should -Not -Throw } It 'Should call the correct mocks' { @@ -648,7 +648,7 @@ try { Verbose = $true } - { Set-TargetResource @testParameters } | Should Not Throw + { Set-TargetResource @testParameters } | Should -Not -Throw } It 'Should call the correct mocks' { @@ -693,7 +693,7 @@ try { } $result = Test-TargetResource @testParameters - $result | Should Be $true + $result | Should -Be $true } It 'Should call the correct mocks' { @@ -724,7 +724,7 @@ try { } $result = Test-TargetResource @testParameters - $result | Should Be $true + $result | Should -Be $true } It 'Should call the correct mocks' { @@ -767,7 +767,7 @@ try { } $result = Test-TargetResource @testParameters - $result | Should Be $true + $result | Should -Be $true } It 'Should call the correct mocks' { @@ -810,7 +810,7 @@ try { } $result = Test-TargetResource @testParameters - $result | Should Be $true + $result | Should -Be $true } It 'Should call the correct mocks' { @@ -844,7 +844,7 @@ try { } $result = Test-TargetResource @testParameters - $result | Should Be $false + $result | Should -Be $false } It 'Should call the correct mocks' { @@ -882,7 +882,7 @@ try { } $result = Test-TargetResource @testParameters - $result | Should Be $false + $result | Should -Be $false } It 'Should call the correct mocks' { @@ -925,7 +925,7 @@ try { } $result = Test-TargetResource @testParameters - $result | Should Be $false + $result | Should -Be $false } It 'Should call the correct mocks' { @@ -968,7 +968,7 @@ try { } $result = Test-TargetResource @testParameters - $result | Should Be $false + $result | Should -Be $false } It 'Should call the correct mocks' { @@ -1011,7 +1011,7 @@ try { } $result = Test-TargetResource @testParameters - $result | Should Be $false + $result | Should -Be $false } It 'Should call the correct mocks' { @@ -1043,9 +1043,9 @@ try { It 'Should return the expected object' { $result = Get-PageFileSetting -Drive $testDrive -Verbose - $result.InitialSize | Should Be $testInitialSize - $result.MaximumSize | Should Be $testMaximumSize - $result.Name | Should Be "$testDrive\" + $result.InitialSize | Should -Be $testInitialSize + $result.MaximumSize | Should -Be $testMaximumSize + $result.Name | Should -Be "$testDrive\" } It 'Should call the correct mocks' { @@ -1070,7 +1070,7 @@ try { -InitialSize $testInitialSize ` -MaximumSize $testMaximumSize ` -Verbose - } | Should Not Throw + } | Should -Not -Throw } It 'Should call the correct mocks' { @@ -1089,7 +1089,7 @@ try { -ParameterFilter $parameterFilterEnableAutoManagePaging It 'Should not throw an exception' { - { Set-AutoManagePaging -State Enable -Verbose } | Should Not Throw + { Set-AutoManagePaging -State Enable -Verbose } | Should -Not -Throw } It 'Should call the correct mocks' { @@ -1106,7 +1106,7 @@ try { -ParameterFilter $parameterFilterDisableAutoManagePaging It 'Should not throw an exception' { - { Set-AutoManagePaging -State Disable -Verbose } | Should Not Throw + { Set-AutoManagePaging -State Disable -Verbose } | Should -Not -Throw } It 'Should call the correct mocks' { @@ -1125,7 +1125,7 @@ try { -ParameterFilter $parameterFilterNewPageFileSetting It 'Should not throw an exception' { - { New-PageFile -PageFileName $testPageFileName -Verbose } | Should Not Throw + { New-PageFile -PageFileName $testPageFileName -Verbose } | Should -Not -Throw } It 'Should call the correct mocks' { diff --git a/appveyor.yml b/appveyor.yml index c1857782..44610415 100644 --- a/appveyor.yml +++ b/appveyor.yml @@ -6,6 +6,8 @@ install: - git clone https://github.com/PowerShell/DscResource.Tests - ps: | + $moduleName = 'xComputerManagement' + $mainModuleFolder = "Modules\$moduleName" Import-Module "$env:APPVEYOR_BUILD_FOLDER\DscResource.Tests\AppVeyor.psm1" Invoke-AppveyorInstallTask -PesterMaximumVersion 4.0.8 @@ -22,7 +24,8 @@ build: false test_script: - ps: | Invoke-AppveyorTestScriptTask ` - -ExcludeTag @() ` + -Type 'Harness' ` + -MainModulePath $mainModuleFolder ` -CodeCoverage ` -CodeCovIo @@ -33,4 +36,7 @@ test_script: # scripts to run before deployment deploy_script: - ps: | - Invoke-AppveyorAfterTestTask + Invoke-AppveyorAfterTestTask ` + -Type 'Wiki' ` + -MainModulePath $mainModuleFolder ` + -ResourceModuleName $moduleName