Powershell DSC Cannot invoke the Invoke-DscResource cmdlet - powershell

I'm trying to use DSC to configure the nodes in my service fabric cluster virtual machine scale set. Doing some registry edits, to keep it small I only show one below. When I run the functions manually by themselves they work fine. When trying to nest them inside one function I get an error.
configuration ServiceFabricNode {
Node localhost
{
SSLPerfectForwardSecrecyTLS12 ConfigureSSL {}
ServiceFabricAntivirusExclusions AntiVirusExclusions {}
}
}
configuration SSLPerfectForwardSecrecyTLS12 {
Import-DscResource –ModuleName PSDesiredStateConfiguration
Import-DscResource -ModuleName GraniResource
# Disable Multi-Protocol Unified Hello
Registry "DisableServerMultiProtocolUnifiedHello"
{
Key = "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\Multi-Protocol
Unified Hello\Server"
ValueName = "Enabled"
ValueType = "Dword"
ValueData = "0"
Ensure = "Present"
Force = $true
}
}
configuration ServiceFabricAntivirusExclusions {
Import-DscResource -ModuleName WindowsDefender
[string[]]$exclusionPath = "C:\Program Files\Microsoft Service abric\","D:\SvcFab\";
Invoke-DscResource -Name WindowsDefender -ModuleName WindowsDefender -Method Set -Property #{ IsSingleInstance = 'Yes'; ExclusionPath = $exclusionPath }
[string[]]$exlusionProcess = "Fabric.exe","FabricHost.exe","FabricInstallerService.exe","FabricSetup.exe","FabricDeployer.exe","ImageBuilder.exe","FabricGateway.exe","FabricDCA.exe","FabricFAS.exe","FabricUOS.exe","FabricRM.exe","FileStoreService.exe";
Invoke-DscResource -Name WindowsDefender -ModuleName WindowsDefender -Method Set -Property #{ IsSingleInstance = 'Yes'; ExclusionProcess = $exlusionProcess }
}
ServiceFabricNode
Results into
Compilation errors occurred while processing configuration 'ServiceFabricNode'. Please review the errors reported in error stream and modify your configuration code
appropriately.
At C:\Windows\system32\WindowsPowerShell\v1.0\Modules\PSDesiredStateConfiguration\PSDesiredStateConfiguration.psm1:3917 char:5
+ throw $ErrorRecord
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (ServiceFabricNode:String) [], InvalidOperationException
+ FullyQualifiedErrorId : FailToProcessConfiguration
With debug enabled it shows the real exception
Cannot invoke the Invoke-DscResource cmdlet. The Invoke-DscResource cmdlet is in progress and must return before Invoke-DscResource can be invoked. Use -Force option if
that is available to cancel the current operation.
+ CategoryInfo : NotSpecified: (root/Microsoft/...gurationManager:String) [], CimException
+ FullyQualifiedErrorId : MI RESULT 1
+ PSComputerName : localhost
I cannot find a -Force option and Google seems to filter out all errors for Invoke-DscResource or I'm the first one using it. Does anyone know a solution? Maybe I don't have to use Invoke-DscResource for the WindowsDefender module, but I don't see another way.

I figured it out with the following blog information http://nanalakshmanan.com/blog/Composite-Resources-Explained/
WindowsDefender is a Composite-Resource
configuration ServiceFabricAntivirusExclusions
{
Import-DscResource -ModuleName WindowsDefender
[string[]]$exclusionPath = "C:\Program Files\Microsoft Service Fabric\","D:\SvcFab\";
[string[]]$exlusionProcess = "Fabric.exe","FabricHost.exe","FabricInstallerService.exe","FabricSetup.exe","FabricDeployer.exe","ImageBuilder.exe","FabricGateway.exe","FabricDCA.exe","FabricFAS.exe","FabricUOS.exe","FabricRM.exe","FileStoreService.exe";
WindowsDefender x
{
IsSingleInstance = 'Yes';
ExclusionPath = $exclusionPath;
ExclusionProcess = $exlusionProcess;
}
}

Related

Could not find the module 'cChocoInstaller' when I try to compile my DSC configuration

I'm trying to get Chocolatey installed to manage packages on a a windows VM using Powershell DSC.
I've prepared my configuration file
Configuration chocandfirefox {
Import-DscResource -ModuleName cChoco
Import-DscResource -ModuleName cChocoInstaller
Import-DscResource -ModuleName cChocoPackageInstaller
Node 'localhost' {
cChocoInstaller installChoco
{
InstallDir = "c:\ProgramData\chocolatey"
}
cChocoPackageInstaller installGit
{
Name = "firefox"
DependsOn = "[cChocoInstaller]installChoco"
}
}
}
But when I try to compile it to a .mof, I'm told
> + Import-DscResource -ModuleName cChocoInstaller
> + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Could not find the module 'cChocoInstaller'. At
> C:\Users\auser\Documents\PowerShell\DSC\Configuration_chocandfirefox.ps1:4
> char:5
> + Import-DscResource -ModuleName cChocoPackageInstaller
> + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Could not find the module 'cChocoPackageInstaller'.
> + CategoryInfo : ParserError: (:) [], ParseException
> + FullyQualifiedErrorId : ModuleNotFoundDuringParse
I'm sure I'm missing something fundamental but I've worked through docs on DSC and Chocolatey and can't spot it.
You should only need to import cChoco.
Looking at one of the examples provided in the GitHub repository, we can see:
Configuration InstallChoco
{
Import-DscResource -Module cChoco
Node "localhost"
{
cChocoInstaller InstallChoco
{
InstallDir = "c:\choco"
}
# ...
}
}
They're using cChocoInstaller after only importing cChoco. cChocoInstaller is a resource within the module cChoco.

Getting terraform null_resource local-exec to run a powershell install-module

this probably evil to do, but in order to setup a managed identity in our azure db we are using the null_resource like this:
# https://www.terraform.io/docs/providers/null/resource.html
# This technique was stolen from https://stackoverflow.com/a/54523391/442773
resource "null_resource" "create-sql-user" {
triggers = {
db = azurerm_sql_database.x.id
}
# https://www.terraform.io/docs/provisioners/local-exec.html
provisioner "local-exec" {
# https://learn.microsoft.com/en-us/powershell/module/sqlserver/Invoke-Sqlcmd?view=sqlserver-ps
# Adding the Managed Identity to the database as a user and assign it the roles of db_datareader and db_datawriter
# NOTE: This is using the executing users credentials to connect to the db, this may not work if this is executed from a service principal within a devops pipeline
# NOTE: this requires powershell to have the SqlServer module installed. We tried a bunch of things to make it so it'd auto install the module but couldn't get it to work
command = <<EOF
Invoke-Sqlcmd `
-Query "CREATE USER [${azurerm_app_service.x.name}] FROM EXTERNAL PROVIDER; ALTER ROLE db_datareader ADD MEMBER [${azurerm_app_service.x.name}]; ALTER ROLE db_datawriter ADD MEMBER [${azurerm_app_service.x.name}];" `
-ConnectionString "Server=tcp:${azurerm_sql_server.x.fully_qualified_domain_name},1433;Initial Catalog=${azurerm_sql_database.x.name};Persist Security Info=False;MultipleActiveResultSets=False;Encrypt=True;TrustServerCertificate=False;Authentication=Active Directory Integrated;" `
EOF
interpreter = ["PowerShell", "-Command"]
}
}
the problem is the requirement to have Invoke-Sqlcmd available, but that's there only by Install-Module SqlServer out of band w/ terraform. I tried a few different things in the command to make this happen. like:
# https://www.terraform.io/docs/provisioners/local-exec.html
provisioner "local-exec" {
# https://learn.microsoft.com/en-us/powershell/module/sqlserver/Invoke-Sqlcmd?view=sqlserver-ps
# Adding the Managed Identity to the database as a user and assign it the roles of db_datareader and db_datawriter
command = "Install-Module -Name SqlServer -AcceptLicense -SkipPublisherCheck -Force -AllowClobber -Scope CurrentUser;"
interpreter = ["PowerShell", "-ExecutionPolicy", "Bypass", "-Command"]
}
Error: Error running command 'Install-Module -Name SqlServer -AcceptLicense -SkipPublisherCheck -Force -AllowClobber -Scope CurrentUser;': exit status 1. Output: Install-Module : The 'Install-Module' command was found in the module 'PowerShellGet', but the module could not be loaded. For more information, run 'Import-Module PowerShellGet'.
so switching the command to
command = "Import-Module PowerShellGet; Install-Module -Name SqlServer -AcceptLicense -SkipPublisherCheck -Force -AllowClobber -Scope CurrentUser;"
but that lead to this output
Error: Error running command 'Import-Module PowerShellGet; Install-Module -Name SqlServer -AcceptLicense -SkipPublisherCheck -Force -AllowClobber -Scope CurrentUser;': exit status 1. Output: Import-Module : The specified module 'C:\program
files\powershell\6\Modules\PackageManagement\fullclr\Microsoft.PackageManagement.dll' was not loaded because no valid
module file was found in any module directory.
At line:1 char:1
+ Import-Module PowerShellGet; Install-Module -Name SqlServer -AcceptLi ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ResourceUnavailable: (C:\program file...eManagement.dll:String) [Import-Module], FileNot
FoundException
+ FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand
PackageManagement\Get-PackageProvider : The term 'PackageManagement\Get-PackageProvider' is not recognized as the name
of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included,
verify that the path is correct and try again.
At C:\program files\powershell\6\Modules\PowerShellGet\PSModule.psm1:2926 char:26
+ ... $nugetProvider = PackageManagement\Get-PackageProvider -ErrorA ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (PackageManagement\Get-PackageProvider:String) [], CommandNotFoundExcept
ion
+ FullyQualifiedErrorId : CommandNotFoundException
PackageManagement\Get-PackageProvider : The term 'PackageManagement\Get-PackageProvider' is not recognized as the name
of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included,
verify that the path is correct and try again.
At C:\program files\powershell\6\Modules\PowerShellGet\PSModule.psm1:2940 char:40
+ ... ailableNugetProviders = PackageManagement\Get-PackageProvider -Name $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (PackageManagement\Get-PackageProvider:String) [], CommandNotFoundExcept
ion
+ FullyQualifiedErrorId : CommandNotFoundException
Exception calling "ShouldContinue" with "2" argument(s): "Object reference not set to an instance of an object."
At C:\program files\powershell\6\Modules\PowerShellGet\PSModule.psm1:3115 char:8
+ if($Force -or $psCmdlet.ShouldContinue($shouldContinueQueryMessag ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : NullReferenceException
Install-Module : NuGet provider is required to interact with NuGet-based repositories. Please ensure that '2.8.5.201'
or newer version of NuGet provider is installed.
At line:1 char:30
+ ... erShellGet; Install-Module -Name SqlServer -AcceptLicense -SkipPublis ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Install-Module], InvalidOperationException
+ FullyQualifiedErrorId : CouldNotInstallNuGetProvider,Install-Module
one thing i'm wondering is if powershell versions 6 vs 5 is getting in the way here somehow...
EDIT:
I believe you're using the wrong intepreter, try switching Powershell to pwsh to use powershell 6 as an interpreter.
provisioner "local-exec" {
...
interpreter = ["pwsh", "-Command"]
...
}
I'm unsure about the underlying infrastructure where you require powershell to run. It seems like you're using powershell 6.
I also use a null-provider resource, calling into a script, passing in arguments and then creating a user. One advantage of that is that I know which powershell verson I am running (core) as the trigger command is pwsh.
I'll show you how I'm creating the null resource and a snippet of the script, in the hopes it might help.
Null resource for calling a script responsible for creating the user
resource "null_resource" "create_sql_user" {
provisioner "local-exec" {
command = ".'${path.module}\\scripts\\create-sql-user.ps1' -password \"${random_password.sql_password.result}\" -username \"${var.sql_username}\" -sqlSaConnectionString \"${var.sql_server_connectionstring}\" -databaseName \"${azurerm_sql_database.db.name}\" "
interpreter = ["pwsh", "-Command"]
}
depends_on = [azurerm_sql_database.db]
}
create-sql-user.ps1
[CmdletBinding()]
param (
[Parameter(Mandatory = $true)]
[string]
$password,
[Parameter(Mandatory = $true)]
[string]
$username,
[Parameter(Mandatory = $true)]
[string]
$sqlSaConnectionString
)
Install-Module -Name SqlServer -Force
$sqlCmd = "CREATE LOGIN $username WITH PASSWORD = '$password'; ALTER LOGIN $username enable"
Invoke-Sqlcmd -ConnectionString $sqlSaConnectionString -Query $sqlCmd
...
Extras:
In this case I'm generating the sql password using the random resource. One can use similar approach for username:
resource "random_password" "sql_password" {
length = 54
special = true
override_special = "$%#&*()"
}

PowerShell module not dot-sourcing / importing functions as expected

Update 1:
Originally, I posted this with the title: "Scripts ignoring error handling in PowerShell module" as that is the current issue, however it seems more of a module issue, so I have renamed the title.
Update 2:
After a comment that made me question Azure cmdlets, I've tested with the most basic of scripts (added to the module) and the findings are the same, in that the error is not passed to the calling script, however, adding -errorVariable to Get-Service does return something (other than WriteErrorException) that I could probably harness in the handling of the error:
function Test-MyError($Variable)
{
Try
{
Get-Service -Name $variable -ErrorAction Stop -ErrorVariable bar
#Get-AzureRmSubscription -SubscriptionName $variable -ErrorAction Stop
}
Catch
{
Write-Error $error[0]
$bar
}
}
returns:
Test-MyError "Foo"
Test-MyError : Exception of type 'Microsoft.PowerShell.Commands.WriteErrorException' was thrown.
At line:3 char:1
+ Test-MyError "Foo"
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Test-MyError
The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: Cannot find any service with service name 'foo'.
However, if I run "Test-MyError" in ISE, then call the function, I get:
Test-MyError "Foo"
Test-MyError : Cannot find any service with service name 'Foo'.
At line:3 char:1
+ Test-MyError "Foo"
+ ~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Test-MyError
The running command stopped because the preference variable "ErrorActionPreference" or common parameter is set to Stop: Cannot find any service with service name 'Foo'.
So I am not sure what is happening when running "Test-MyError" in ISE and calling it, against it being dot-sourced in the PSM1 file and then calling it?
Do I now have to use -ErrorVariable and handle on that?
Original Question:
I have two functions in a module: Get-Subscription and Get-AllSubscriptions. Each function sits in its own PS1 file and the PSM1 file dot-sources them. The module seems fine as the module scripts are accessible using intelisense and the module loads without issue. I've used this structure in many modules and I haven't come across this problem before. (Although I wonder if MS have changed the way modules work in PS 5.1 as I have noticed using FunctionsToExport='x','y','Z' and Export-ModuleMember don't seem to behave the same way as they used to.)
Get-AllSubscriptions calls Get-Subscription.
If I am not logged into Azure, Get-Subscription should throw an error which is handled, prompting me to log in. This works as expected, if I call Get-Subscription from the Get-Subscription.ps1.
However, when I call Get-Subscription from the a new PS1 file, Get-AllSubscriptions or from the powershell console, it doesn't work. It iterates all the way through the do..until loop, without "handling" the errors as I would expect. On each iteration, it seems to throw a generic error:
Get-Subscription : Exception of type 'Microsoft.PowerShell.Commands.WriteErrorException' was thrown.
However, I do see the last error, Get-Subscription : Unable to find requested subscription after 3 login attempts.
If I execute Get-Subscription in ISE, then call Get-Subscription in a new PS1 file or from Get-AllSubscriptions, it works as expected, however, once I re-import the module (Import-Module AzureVnetTools -Force -Verbose), it goes back to the incorrect behaviour.
If I dot-source Get-Subscription, inside the caller script, it works, but why? This is what should happen with the module's PSM1.
Can anyone help me work out what I am doing wrong here?
(PS 5.1, Windows 7)
Get-Subscription:
function Get-Subscription
{
[cmdletbinding()]
Param
(
[string]$SubscriptionName,
[string]$UserName,
[string]$code
)
$c=1
Write-Verbose "Checking access to '$SubscriptionName' with user '$UserName'..."
Do
{
Write-Verbose "Attempt $c"
Try
{
$oSubscription = Get-AzureRmSubscription -SubscriptionName $SubscriptionName -ErrorAction Stop -WarningAction SilentlyContinue
Write-Verbose "Subscription found: $($oSubscription.SubscriptionName)."
}
Catch
{
if($error[0].Exception.Message -like "*Please verify that the subscription exists in this tenant*")
{
Write-Verbose "Cannot find subscription '$SubscriptionName' with provided credentials."
$account = Login-AzureRmAccount -Credential (Get-Credential -UserName $Username -Message "Subscription '$SubscriptionName' user' password:")
}
elseif($error[0].Exception.Message -like "*Run Login-AzureRmAccount to login*")
{
Write-Verbose "No logged in session found. Please log in."
$account = Login-AzureRmAccount -Credential (Get-Credential -UserName $Username -Message "Subscription '$SubscriptionName' user' password:")
}
else
{
Write-Error $error[0]
}
}
$c++
}
until(($oSubscription) -or ($c -eq 4))
if($c -eq 4)
{
Write-Error "Unable to find requested subscription after $($c-1) login attempts."
break
}
$oSubscription | Add-Member -MemberType NoteProperty -Name Code -Value $code
$oSubscription
}
Get-AllSubscriptions:
function Get-AllSubscriptions
{
[cmdletbinding()]
param
(
[string]$MasterSubscription,
[string]$MasterSubscriptionCode,
[string]$MasterSubscriptionUsername,
[string]$ChildSubscription,
[string]$ChildSubscriptionCode,
[string]$ChildSubscriptionUsername
)
Write-Verbose "Getting all subscriptions..."
$oAllSubscriptions = #()
$oMasterSubscription = Get-Subscription -SubscriptionName $MasterSubscription -UserName $MasterSubscriptionUsername -code $MasterSubscriptionCode -Verbose
$oChildSubscription = Get-Subscription -SubscriptionName $ChildSubscription -UserName $ChildSubscriptionUsername -code $ChildSubscriptionCode -Verbose
$oAllSubscriptions = ($oMasterSubscription,$oChildSubscription)
$oAllSubscriptions
}
Test:
$splat2 = #{
SubscriptionName = "SomeSubscription"
Code = "S02"
Username = "some.user#somewhere.com"
}
#Write-Output "Dot-source:"
#. "D:\Temp\PS.Modules\AzureVnetTools\functions\public\Get-Subscription.ps1"
Get-Subscription #splat2 -verbose
Output:
Get-Subscription #splat2 -verbose
VERBOSE: Checking access to 'SomeSubscription' with user 'some.user#somewhere.com'...
VERBOSE: Attempt 1
Get-Subscription : Exception of type 'Microsoft.PowerShell.Commands.WriteErrorException' was thrown.
At line:7 char:1
+ Get-Subscription #splat2 -verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-Subscription
VERBOSE: Attempt 2
Get-Subscription : Exception of type 'Microsoft.PowerShell.Commands.WriteErrorException' was thrown.
At line:7 char:1
+ Get-Subscription #splat2 -verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-Subscription
VERBOSE: Attempt 3
Get-Subscription : Exception of type 'Microsoft.PowerShell.Commands.WriteErrorException' was thrown.
At line:7 char:1
+ Get-Subscription #splat2 -verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-Subscription
Get-Subscription : Unable to find requested subscription after 3 login attempts.
At line:7 char:1
+ Get-Subscription #splat2 -verbose
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Get-Subscription
AzureVnetTools.psm1
#Get public and private function definition files.
$Public = #( Get-ChildItem -Path $PSScriptRoot\Functions\Public\*.ps1 -ErrorAction SilentlyContinue )
$Private = #( Get-ChildItem -Path $PSScriptRoot\Functions\Private\*.ps1 -ErrorAction SilentlyContinue )
#Dot source the files
Foreach($import in #($Public + $Private))
{
#write-error $import.fullname
Try
{
#Write-Host "Dot-sourcing file: $($import.fullname)."
. $import.fullname
}
Catch
{
Write-Error -Message "Failed to import function $($import.fullname): $_"
}
}
Export-ModuleMember -Function $Public.Basename
AzureVnetTools.psd1 (Relevant section):
FunctionsToExport = '*'
-ErrorAction Stop -WarningAction SilentlyContinue
Is it a warning that's being thrown instead of an error?
So my specific problem was that I was relying on handling the error and doing something based on that. The problem was caused by the way PowerShell's Write-Error works (or not) as I learned from the reply here, given by #Alek.
It simply wasn't passing the actual error back to the calling script. As #Alex suggested, I replaced Write-Error with $PSCmdlet.WriteError(). Although this didn't totally work.
In the Catch{} block, I then changed $error[0] to $_ and the full error was returned to the calling script / function.
I went one further and wrote a reusable function, added to my module:
function Write-PsError
{
[cmdletbinding()]
Param
(
[Exception]$Message,
[Management.Automation.ErrorCategory]$ErrorCategory = "NotSpecified"
)
$arguments = #(
$Message
$null #errorid
[Management.Automation.ErrorCategory]::$ErrorCategory
$null
)
$ErrorRecord = New-Object -TypeName "Management.Automation.ErrorRecord" -ArgumentList $arguments
$PSCmdlet.WriteError($ErrorRecord)
}
Which seems to be working well at the moment. I especially like the way intellisense picks up all the ErrorCategories. Not sure what or how ISE (PS 5.1 / Win 7) does that. I thought I was going to have to add my own dynamic parameter.
HTH.

How to set up client in Powershell 5.0 DSC Pull Mode

I have 2 servers set up for DSC, Both running Powershell 5.0 and Server 12 R2, DSCPULL is configured as a DSC Pull Server over HTTP, DSCIIS is the client.
On DSCIIS i am trying to set it up so that it downloads the config from the Pull server via a configuration names, i have taken code from the MSDN website and altered slightly to my requirements but it still isn't working.
[DSCLocalConfigurationManager()]
configuration PullClientConfigID
{
Node localhost
{
Settings
{
RefreshMode = 'Pull'
RefreshFrequencyMins = 30
RebootNodeIfNeeded = $true
}
ConfigurationRepositoryWeb DSCPULL
{
ServerURL = 'http://DSCPULL:8080/PSDSCPullServer.svc'
RegistrationKey = 'test'
ConfigurationNames = #('WebServer')
AllowUnsecureConnection = $true
}
}
}
PullClientConfigID -OutputPath c:\Configs\TargetNodes
Start-DscConfiguration C:\Configs\TargetNodes -ComputerName localhost -wait -Verbose
The error i receive is
Start-DscConfiguration : The computer-specific MOF file for computer localhost does not exist in the current directory.
At line:1 char:1
+ Start-DscConfiguration C:\Configs\TargetNodes -ComputerName localhost ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Start-DscConfiguration], ArgumentException
+ FullyQualifiedErrorId : System.ArgumentException,Microsoft.PowerShell.DesiredStateConfiguration.Commands.StartDscConfiguration
Command
I have tried changing "Node Localhost" to the server name and then run the last line with the correct "ComputerName" but i get the same error.
I should have been using Set-DSCLocalConfigurationManager not Start-DSCConfiguration
Set-DSCLocalConfigurationManager localhost –Path C:\Configs\TargetNodes –Verbose

Desired State Configuration xWebsite

I am running into a problem. When I go to create a website I get an error. Has anyone else ever ran into this issue?
VERBOSE: [CONT10SQLTEST]: [[xWebsite]CMSAuth] Physical Path of Website CMSAuth does not match the desired state.
Cannot find path 'IIS:\Sites\CMSAuth' because it does not exist.
+ CategoryInfo : ObjectNotFound: (IIS:\Sites\CMSAuth:) [], CimException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetItemPropertyCommand
+ PSComputerName : CONT10SQLTEST
VERBOSE: [CONT10SQLTEST]: LCM: [ End Test ] [[xWebsite]CMSAuth] in 1.9830 seconds.
The PowerShell provider MSFT_xWebsite threw one or more non-terminating errors while running the Test-TargetResource functionality. These errors are logged to the ETW channel called
Microsoft-Windows-DSC/Operational. Refer to this channel for more details.
+ CategoryInfo : InvalidOperation: (:) [], CimException
+ FullyQualifiedErrorId : NonTerminatingErrorFromProvider
+ PSComputerName : CONT10SQLTEST
VERBOSE: [CONT10SQLTEST]: LCM: [ End Set ]
The SendConfigurationApply function did not succeed.
+ CategoryInfo : NotSpecified: (root/Microsoft/...gurationManager:String) [], CimException
+ FullyQualifiedErrorId : MI RESULT 1
+ PSComputerName : CONT10SQLTEST
configuration iis
{
node $env:computername
{
xWebsite CMSAuth
{
Ensure = "Present"
Name = "CMSAuth"
State = "Started"
ApplicationPool = "CMSAuthAppPool"
PhysicalPath = "E:\websites\CMSAuth\Website"
BindingInfo = MSFT_xWebBindingInformation
{
Protocol = "HTTP"
Port = 80
HostName = "*"
}
}
}
}
I've seen it.
I am using DSC Resource wave 4 / WebAdministration 1.2.
I fixed it by going in to the MSFT_xWebsite.psm1 file and replacing:
$Website = Get-Website -Name $Name with $Website = Get-Website | Where Name -eq $Name
Get-Website -Name $Name returns all websites on the host, so the library thinks the site exists, but then fails when getting the properties in Test-TargetResource
I loaded the module directly, using Import-Module MSFT_xWebsite.psm1, and executed the functions to figure out what was failing. The error I got running the module function directly helped me find the failing catch block via the error message. The line numbers were still useless.
Hope that helps.
If you don't want to edit the module yourself as described in the answer above, you can use the corresponding module cWebAdministration from PowerShell.org. It fixes the issue and can be imported alongside xWebAdministration if you need more modules than the two of cWebAdministration (cWebSite and cAppPool):
Import-DscResource -ModuleName cWebAdministration
Import-DscResource -ModuleName xWebAdministration