Desired State Configuration xWebsite - powershell

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

Related

'Provider load failure' during installation process

I execute two Powershell scripts during a installation process from a desktop application under Windows 10 IoT Enterprise.
%WINDIR%\System32\WindowsPowerShell\v1.0\PowerShell.exe -ExecutionPolicy Bypass -File ".\KeyboardFilter.ps1"
%WINDIR%\System32\WindowsPowerShell\v1.0\PowerShell.exe -ExecutionPolicy Bypass -File ".\ShellLauncher.ps1"
But the execution of the Powershell scripts is not successful. I get the following errors:
Get-WMIObject : Provider load failure
At C:\Program Files\Application\KeyboardFilter.ps1:31 char:19
+ ... $predefined = Get-WMIObject -class WEKF_PredefinedKey #CommonParams |
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [Get-WmiObject], ManagementException
+ FullyQualifiedErrorId : GetWMIManagementException,Microsoft.PowerShell.Commands.GetWmiObjectCommand
Write-Error : A positional parameter cannot be found that accepts argument 'is'.
At C:\Program Files\Application\KeyboardFilter.ps1:41 char:9
+ Write-Error $Id is not a valid predefined key
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Write-Error], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.WriteErrorCommand
enable-windowsoptionalfeature : An attempt was made to load a program with an incorrect format.
At C:\Program Files\Application\ShellLauncher.ps1:4 char:1
+ enable-windowsoptionalfeature -online -featureName Client-EmbeddedShe ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Enable-WindowsOptionalFeature], COMException
+ FullyQualifiedErrorId : Microsoft.Dism.Commands.EnableWindowsOptionalFeatureCommand
The installation process starts with administration permissions.
The first script adds key combinations to the Keyboard Filter (Windows 10 IoT feature).
The second scripts enable and configure the Shell Launcher (also Windows 10 IoT feature).
KeyboardFilter.ps1:
param (
[String] $ComputerName
)
$CommonParams = #{"namespace"="root\standardcimv2\embedded"}
$CommonParams += $PSBoundParameters
function Enable-Predefined-Key($Id) {
$predefined = Get-WMIObject -class WEKF_PredefinedKey #CommonParams |
where {
$_.Id -eq "$Id"
};
if ($predefined) {
$predefined.Enabled = 1;
$predefined.Put() | Out-Null;
Write-Host Enabled $Id
} else {
Write-Error $Id is not a valid predefined key
}
}
If I execute the Powershell scripts in a batchfile or on Powershell console, everything works fine. I also tried to execute the Powershell scripts during the installation process with Powershell x86 and x64, same errors in both cases.
Any hints, tips or solution for this problem?

Reflection Assembly Errors in Powershell

I have some Powershell code that takes the Apps running on an IIS server and finds the versions of .NET they are running.
$Apps = Get-WebApplication
foreach($App in $Apps) {
$binLocation = "$($App.physicalPath)\bin"
# get all dlls in bin folder
$dllFolder = Get-Item -Path $binLocation
$dlls = $dllFolder.GetFiles("*.dll")
# analyze dll .net version
$set = New-Object System.Collections.Generic.HashSet[String]
$dlls | ForEach-Object {
$set.Add([Reflection.Assembly]::ReflectionOnlyLoadFrom("$binLocation\$($_.Name)").ImageRuntimeVersion) | Out-Null
}
# print all dll .NET version
$App
$set
}
However when I run this on my server I get 2 types of error;
Exception calling "ReflectionOnlyLoadFrom" with "1" argument(s): "API restriction: The
assembly 'file:///D:\inetpub\wwwroot\OABS_ECRM\bin\WebGrease.dll' has already loaded from a
different location. It cannot be loaded from a new location within the same appdomain."
At line:13 char:74
+ $set.Add([Reflection.Assembly]::ReflectionOnlyLoadFrom ("$binLocation\$($_.Name ...
+ ~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : FileLoadException
and,
Exception calling "ReflectionOnlyLoadFrom" with "1" argument(s): "Could not load file or
assembly 'file:///D:\inetpub\wwwroot\Tablet\bin\epengine.dll' or one of its dependencies.
The module was expected to contain an assembly manifest."
At line:13 char:74
+ $set.Add([Reflection.Assembly]::ReflectionOnlyLoadFrom("$binLocation\$($_.Name ...
+ ~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : BadImageFormatException
I seem to get the .NET versions running on each app from the script but I was wondering what caused these errors and if they can be cleared. I need to solve this in powershell.
Loading multiple DLLs with the same identity into the same AppDomain will give you the first exception.
See my workaround at https://stackoverflow.com/a/62379741/920618.

Windows Powershell Dynamic State Configuration -- Scheduling Tasks -- Get an "Access is denied" error running it locally

I am new to Powershell and dynamic state configuration. I am trying to get a deployment script working that will set up a number of tasks in the Windows task scheduler. I have written the script and have been trying to run it on my local machine.
Configuration AppServerTasks {
param($NodeName)
Import-DscResource -Module StackExchangeResources
Node $NodeName
{
$trackingFilePath = "...";
$tracksFilePath = "...";
$reportingFilePath = "...";
ScheduledTask TrackTask
{
Name = "Tracks"
FilePath = $tracksFilePath
Daily = $true
Hours = 0
Minutes = 5
}
ScheduledTask TrackingTask
{
Name = "Tracking"
FilePath = $trackingFilePath
Daily = $true
Hours = 0
Minutes = 5
}
ScheduledTask ReportingTask
{
Name = "Reporting"
FilePath = $reportingFilePath
Daily = $true
Hours = 0
Minutes = 5
}
}
}
AppServerTasks -NodeName "localhost"
Start-DscConfiguration AppServerTasks -Wait -Verbose -Force
However, this is failing with "Access is denied". The error I get from this is as follows:
VERBOSE: Perform operation 'Invoke CimMethod' with following parameters, ''methodName' = SendConfigurationApply,'className' =
MSFT_DSCLocalConfigurationManager,'namespaceName' = root/Microsoft/Windows/DesiredStateConfiguration'.
VERBOSE: An LCM method call arrived from computer MEEP with user sid S-1-5-21-2331283068-2376342717-1560730737-1001.
VERBOSE: [MEEP]: LCM: [ Start Set ]
VERBOSE: [MEEP]: LCM: [ Start Resource ] [[ScheduledTask]TrackTask]
VERBOSE: [MEEP]: LCM: [ Start Test ] [[ScheduledTask]TrackTask]
VERBOSE: [MEEP]: [[ScheduledTask]TrackTask] Unable to find matching job.
VERBOSE: [MEEP]: LCM: [ End Test ] [[ScheduledTask]TrackTask] in 0.0160 seconds.
VERBOSE: [MEEP]: LCM: [ Start Set ] [[ScheduledTask]TrackTask]
Connecting to remote server MEEP failed with the following error message : Access is denied. For more information, see the
about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:) [], CimException
+ FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed
+ PSComputerName : localhost
Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an argument that is not null or
empty, and then try the command again.
+ CategoryInfo : InvalidData: (:) [], CimException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
+ PSComputerName : localhost
Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an argument that is not null or
empty, and then try the command again.
+ CategoryInfo : InvalidData: (:) [], CimException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
+ PSComputerName : localhost
VERBOSE: [MEEP]: LCM: [ End Set ] [[ScheduledTask]TrackTask] in 0.0150 seconds.
The PowerShell DSC resource StackExchange_ScheduledTask threw one or more non-terminating errors while running the
Set-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 : localhost
VERBOSE: [MEEP]: LCM: [ Start Resource ] [[ScheduledTask]TrackingTask]
VERBOSE: [MEEP]: LCM: [ Start Test ] [[ScheduledTask]TrackingTask]
VERBOSE: [MEEP]: [[ScheduledTask]TrackingTask] Unable to find matching job.
VERBOSE: [MEEP]: LCM: [ End Test ] [[ScheduledTask]TrackingTask] in 0.0000 seconds.
VERBOSE: [MEEP]: LCM: [ Start Set ] [[ScheduledTask]TrackingTask]
Connecting to remote server MEEP failed with the following error message : Access is denied. For more information, see the
about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:) [], CimException
+ FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed
+ PSComputerName : localhost
Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an argument that is not null or
empty, and then try the command again.
+ CategoryInfo : InvalidData: (:) [], CimException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
+ PSComputerName : localhost
Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an argument that is not null or
empty, and then try the command again.
+ CategoryInfo : InvalidData: (:) [], CimException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
+ PSComputerName : localhost
VERBOSE: [MEEP]: LCM: [ End Set ] [[ScheduledTask]TrackingTask] in 0.0320 seconds.
The PowerShell DSC resource StackExchange_ScheduledTask threw one or more non-terminating errors while running the
Set-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 : localhost
VERBOSE: [MEEP]: LCM: [ Start Resource ] [[ScheduledTask]ReportingTask]
VERBOSE: [MEEP]: LCM: [ Start Test ] [[ScheduledTask]ReportingTask]
VERBOSE: [MEEP]: [[ScheduledTask]ReportingTask] Unable to find matching job.
VERBOSE: [MEEP]: LCM: [ End Test ] [[ScheduledTask]ReportingTask] in 0.0000 seconds.
VERBOSE: [MEEP]: LCM: [ Start Set ] [[ScheduledTask]ReportingTask]
Connecting to remote server MEEP failed with the following error message : Access is denied. For more information, see the
about_Remote_Troubleshooting Help topic.
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:) [], CimException
+ FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed
+ PSComputerName : localhost
Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an argument that is not null or
empty, and then try the command again.
+ CategoryInfo : InvalidData: (:) [], CimException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
+ PSComputerName : localhost
Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an argument that is not null or
empty, and then try the command again.
+ CategoryInfo : InvalidData: (:) [], CimException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
+ PSComputerName : localhost
VERBOSE: [MEEP]: LCM: [ End Set ] [[ScheduledTask]ReportingTask] in 0.0150 seconds.
The PowerShell DSC resource StackExchange_ScheduledTask threw one or more non-terminating errors while running the
Set-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 : localhost
The SendConfigurationApply function did not succeed.
+ CategoryInfo : NotSpecified: (root/Microsoft/...gurationManager:String) [], CimException
+ FullyQualifiedErrorId : MI RESULT 1
+ PSComputerName : localhost
VERBOSE: Operation 'Invoke CimMethod' complete.
VERBOSE: Time taken for configuration job to complete is 0.139 seconds
I have tried Googling (as I don't know the cause of context of the problem). But it has not helped as, although others have gotten similar problems to this, the fixes suggested have not worked. I am running this in POwershell ISE as Administrator. I have tried Enable-PSRemoting -force and it is enabled. Not sure what to do next.
Your thoughts? Thanks.
Seems credentials are necessary:
$ConfigurationData = #{
AllNodes = #(
#{
NodeName="*"
PSDscAllowPlainTextPassword=$true
}
#{
NodeName="Localhost"
}
)
}
Configuration AppServerTasks {
param($NodeName,$credential)
Import-DscResource -ModuleName StackExchangeResources
Node $AllNodes.NodeName
{
$trackingFilePath = 'c:\temp\test.ps1'
ScheduledTask TrackTask
{
Name = "Tracks"
FilePath = $trackingFilePath
Daily = $true
Hours = 0
Minutes = 5
Credential = $credential
}
}
}
$c = Get-Credential
AppServerTasks -ConfigurationData $ConfigurationData -OutputPath c:\temp\localhost -credential $c
Start-DscConfiguration -ComputerName localhost -Path C:\temp\localhost -Wait -Verbose -Force

How the PowerShell Cmdlets that have a ComputerName parameter authenticate to remote computers?

Some PowerShell Cmdlets have a ComputerName parameter and I can use them to get information from remote computers. Like Get-Process, Get-Service etc. However, they don't have a Credential parameter, which in turn makes the command fail in some circumstances. Like the following example.
PS C:\Users\x\AppData\Roaming> Get-Service *sql* -ComputerName mylab.testing.com
Get-Service : Cannot open Service Control Manager on computer 'mylab.testing.com'. This operation might require other privileges.
At line:1 char:1
+ Get-Service *sql* -ComputerName mylab.testing.com
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-Service], InvalidOperationException
+ FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.GetServiceCommand
PS C:\Users\x\AppData\Roaming> Get-Error
******************************
Errors: 104
******************************
System.ComponentModel.Win32Exception (0x80004005): Access is denied
----------------------------------------------
System.Management.Automation.RuntimeException: ScriptHalted
----------------------------------------------
System.InvalidOperationException: Collection was modified; enumeration operation may not execute.
at System.Collections.ArrayList.ArrayListEnumeratorSimple.MoveNext()
at System.Management.Automation.Interpreter.FuncCallInstruction`2.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
----------------------------------------------
System.Management.Automation.RuntimeException: You cannot call a method on a null-valued expression.
at CallSite.Target(Closure , CallSite , Object )
at System.Dynamic.UpdateDelegates.UpdateAndExecute1[T0,TRet](CallSite site, T0 arg0)
at System.Management.Automation.Interpreter.DynamicInstruction`2.Run(InterpretedFrame frame)
at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
----------------------------------------------
You cannot call a method on a null-valued expression.
At line:18 char:21
+ write-host $err.Exception.ToString()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
----------------------------------------------
Collection was modified; enumeration operation may not execute.
At line:9 char:17
+ foreach($err in $Error)
+ ~~~~
+ CategoryInfo : OperationStopped: (:) [], InvalidOperationException
+ FullyQualifiedErrorId : System.InvalidOperationException
ScriptHalted
At line:22 char:9
+ throw
+ ~~~~~
+ CategoryInfo : OperationStopped: (:) [], RuntimeException
+ FullyQualifiedErrorId : ScriptHalted
PS C:\Users\x\AppData\Roaming> help Get-Service -full
Note I used a custom function Get-Error and its code is listed below.
function Get-Error
{
$errorsReported = $False
if($Error.Count -ne 0)
{
write-host "******************************"
write-host "Errors:", $Error.Count
write-host "******************************"
foreach($err in $Error)
{
$errorsReported = $True
if( $err.Exception.InnerException -ne $null)
{
write-host $err.Exception.InnerException.ToString()
}
else
{
write-host $err.Exception.ToString()
}
write-host "----------------------------------------------"
}
throw
}
}
I want to know whether my understanding is correct? Does that simply means it's impossible to authenticate to remote servers when using those commands?
Thanks.
You have to be running your PowerShell session with an account that has admin rights on the remote computer as capsch says. If the remote computer has remoting enabled, you could run the Get-Service command using Invoke-Command and remoting, which does support alternate credentials. Another alternative is to use WMI and query services that way which also supports alternate credentials.
UAC aside you by default have to be an admin of member to administer remotely
Cannot open Service Control Manager on computer

Restart IIS6 application pool - ADSI error

Not sure what the eff' is wrong! I am using Powershell 2.0 on Windows 7. Had this same script working on Windows XP , am i just missing something?
$server = "server1-vm1.prod.ds.russell.com"
$name = "Superduper_Reports"
$iis = [ADSI]"IIS://$server/W3SVC/AppPools/$name"
$iis.psbase.invoke("recycle")
Error (that invoke looks okay to me?):
Exception calling "Invoke" with "2" argument(s): "Unknown error (0x80005000)"
At line:3 char:19
+ $iis.psbase.invoke <<<< ("recycle")
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
When just running $iis variable i get this error:
The following exception occurred while retrieving member "PSComputerName": "Unknown error (0x80005000)"
+ CategoryInfo : NotSpecified: (:) [format-default], ExtendedTypeSystemException
+ FullyQualifiedErrorId : CatchFromBaseGetMember,Microsoft.PowerShell.Commands.FormatDefaultCommand
Roooarr! I'd rather use ADSI over WMI! Any help? :)
I think that you can use WebAdministration module for that
Import-Module WebAdministration
Get-Command -Module WebAdministration
Get-ChildItem IIS:
You will find a lots of Cmdlets to admin IIS and a new drive IIS:
You will find on this Microsoft Web site some explanations.
This question has a WMI script which has been stated to work.
Alternatively ADSI equivalent would look something like this ...
http://geekswithblogs.net/Lance/archive/2010/12/16/powershell-ndash-recycle-all-iis-app-pools.aspx
function Recycle-AppPools {
param(
[string] $server = "3bhs001",
[int] $mode = 1, # ManagedPipelineModes: 0 = integrated, 1 = classic
)
$iis = [adsi]"IIS://$server/W3SVC/AppPools"
$iis.psbase.children | %{
$pool = [adsi]($_.psbase.path);
if ($pool.AppPoolState -eq 2 -and $pool.ManagedPipelineMode -eq $mode) {
# AppPoolStates: 1 = starting, 2 = started, 3 = stopping, 4 = stopped
$pool.psbase.invoke("recycle")
}
}
}
You can't recycle a stopped AppPool however so you need to check for that.