Assertion over each item in collection in Pester - powershell

I am doing some infrastructure testing in Pester and there is repeating scenario that I don't know how to approach.
Let's say, I want to check whether all required web roles are enabled on IIS. I have a collection of required web roles and for each of them I want to assert it is enabled.
My current code looks like this:
$requiredRoles = #(
"Web-Default-Doc",
"Web-Dir-Browsing",
"Web-Http-Errors",
"Web-Static-Content",
"Web-Http-Redirect"
)
Context "WebRoles" {
It "Has installed proper web roles" {
$requiredRoles | % {
$feature = Get-WindowsOptionalFeature -FeatureName $_ -online
$feature.State | Should Be "Enabled"
}
}
}
It works in the sense that the test will fail if any of the roles are not enabled/installed. But that is hardly useful if the output of such Pester test looks like this:
Context WebRoles
[-] Has installed proper web roles 2.69s
Expected: {Enabled}
But was: {Disabled}
283: $feature.State | Should Be "Enabled"
This result doesn't give any clue about which feature is the Disabled one.
Is there any recommended practice in these scenarios? I was thinking about some string manipulation...
Context "WebRoles" {
It "Has installed proper web roles" {
$requiredRoles | % {
$feature = Get-WindowsOptionalFeature -FeatureName $_ -online
$toCompare = "{0}_{1}" -f $feature.FeatureName,$feature.State
$toCompare | Should Be ("{0}_{1}" -f $_,"Enabled")
}
}
}
which would output:
Context WebRoles
[-] Has installed proper web roles 2.39s
Expected string length 27 but was 28. Strings differ at index 20.
Expected: {IIS-DefaultDocument_Enabled}
But was: {IIS-DefaultDocument_Disabled}
-------------------------------^
284: $toCompare | Should Be ("{0}_{1}" -f $_,"Enabled")
...which is better, but it doesn't feel very good...
Also, there is second problem with the fact that the test will stop on first fail and I would need to re-run the test after I fix each feature...
Any ideas?

Put your It inside the loop like so:
Context "WebRoles" {
$requiredRole | ForEach-Object {
It "Has installed web role $_" {
(Get-WindowsOptionalFeature -FeatureName $_ -online).State | Should Be "Enabled"
}
}
}

Related

PowerShell unable to find type of exception in try/catch block

I'm running a PowerShell Function App (~3) which uses the Az PowerShell module to manage a Storage Account. If any of the operations I carry out result in an error, I am unable to check for specific types in a try/catch block.
It is important to note that where there is no error, operations using the Az.Storage module are successful.
For example, if I were to try and delete a container that does not exist, the example below results in the following error -
Unable to find type [Microsoft.WindowsAzure.Commands.Storage.Common.ResourceNotFoundException].
To obtain the type of exception that is returned, I'm using $_.Exception.GetType().fullname.
I've also tried to add the namespace to the script that may produce the exceptions.
using namespace Microsoft.WindowsAzure.Commands.Storage.Common
Example
Class Storage
{
[AppSettings]$AppSettings = [AppSettings]::GetInstance()
[Object]$Context
Storage()
{
$key = Get-AzStorageAccountKey -ResourceGroupName $this.AppSettings.StorageAccountResourceGroup -Name $this.AppSettings.StorageAccountName
$this.Context = New-AzStorageContext -StorageAccountName $this.AppSettings.StorageAccountName -StorageAccountKey $key[0].Value
}
[void] DeleteBlobContainer([String]$name)
{
try {
Remove-AzStorageContainer -Name $name -Context $this.Context -Force -ErrorAction Stop
}
catch [Microsoft.WindowsAzure.Commands.Storage.Common.ResourceNotFoundException] {
throw [ContainerNotFoundException]::new($name)
}
catch {
throw [DustBinException]::new($_.Exception.Message)
}
}
}
Update
When calling an HTTP triggered function, I am able to see that the Az.Storage module is installed. This is expected, given operations that require the module are successful -
Get-Module -Name Az.Storage -ListAvailable | Select-Object Name, Version, ModuleBase | ConvertTo-Json
[
{
"Name": "Az.Storage",
"Version": {
"Major": 3,
"Minor": 0,
"Build": 0,
"Revision": -1,
"MajorRevision": -1,
"MinorRevision": -1
},
"ModuleBase": "C:\\Users\\dgard\\AppData\\Local\\AzureFunctions\\DustBin\\ManagedDependencies\\201202095548376.r\\Az.Storage\\3.0.0"
}
]
However, if copy the module to .\bin and include a Module manifest to require Microsoft.Azure.Storage.Common.dll, as suggested in this question, the type is still not found.
New-ModuleManifest ./Modules/StorageHelper/StorageHelper.psd1 -RootModule StorageHelper.psm1 -RequiredAssemblies .\bin\Az.Storage\3.0.0\Microsoft.Azure.Storage.Common.dll
To be sure I was adding the correct assembly, I have updated the manifest to include every single assembly in the Az.Storage module, but the type is still not found.
In my question I added an update mentioning that I had tried to add a module manifest requiring all of the Az.Storage assemblies; this was not quite correct...
I had copied the list of required assemblies from the module manifest included with the Az.Storage module, but this did not include Microsoft.Azure.PowerShell.Cmdlets.Storage.dll. Using a module manifest to require this assembly (just this one, no others required) has worked.
New-ModuleManifest ./Modules/StorageHelper/StorageHelper.psd1 -RootModule StorageHelper.psm1 -RequiredAssemblies .\bin\Az.Storage\3.0.0\Microsoft.Azure.PowerShell.Cmdlets.Storage.dll

How do I perform a logical If..then in powershell against JSON data?

I'm trying to loop through a JSON array of desired registry values, and then inspect the registry value for the correct setting.
The issue I have is that I'm not correctly defining the 'if..()' logic test in my loop. The problem code is located in the line: if($protocols[$i][$tempdisabledKVString] -eq "true")
I have the following object:
$protocolsJSON = #"
[
{
"Name": "TLS 1.2",
"Server-Enabled": True,
"Client-Enabled": True
}
]
"#
$protocols = $protocolsJSON | ConvertFrom-Json
Which fails the nested if statement below (undesired behavior)
elseif ($isDefaultDisabled -eq 0) # Protocol is manually enabled in registry (part 1.A)
{
if($protocols[$i][$tempdisabledKVString] -eq "True") # Protocol should be manually enabled in registry (part 1.B)
{
# For TLS 1.2 to be enabled and negotiated on servers that run Windows Server 2008 R2,
# you MUST create the DisabledByDefault entry in the appropriate subkey (Client, Server)
# and set it to "0". The entry will not be seen in the registry and it is set to "1" by default.
$errorString = "Warning: Protocol is only partially enabled."
$TLSProtocolResult.Errors = $errorString
}
else
{
write-host "DEBUG " $protocols[$i][$tempdisabledKVString]
write-host "DEBUG " $protocols[$i]
write-host "DEBUG " [$tempdisabledKVString]
$errorString = "Error: Protocol should be disabled."
$TLSProtocolResult.Errors = $errorString
}
}
Which produces the following output
DEBUG
DEBUG #{Name=TLS 1.2; Server-Enabled=True; Client-Enabled=True}
DEBUG [Server-Disabled]
DEBUG
DEBUG #{Name=TLS 1.2; Server-Enabled=True; Client-Enabled=True}
DEBUG [Client-Disabled]
How do I edit the IF statement so that I can test the true/false status of $protocols[$i][$tempdisabledKVString]?
The problem is you're trying to access a property as if it were a nested array.
Try this:
$protocolsJSON = #"
[
{
"Name": "TLS 1.2",
"Server-Enabled": true,
"Client-Enabled": true
}
]
"#
$protocols = $protocolsJSON | ConvertFrom-Json
$property = "Server-Enabled"
Write-Host "RESULT: $($protocols[0].$property)"
Your issue is most likely the JSON not being parsed. Try including quotes around your values. i.e. replace: "Server-Enabled": True, with "Server-Enabled": "True",.
Also, when if $tempdisabledKVString is the name of a property, you need to access it as a property rather than an index. i.e. replace $protocols[$i][$tempdisabledKVString] with $protocols[$i]."$tempdisabledKVString".
Clear-Host
$protocolsJSON = #"
[
{
"Name": "TLS 1.2",
"Server-Enabled": "True",
"Client-Enabled": "True"
}
]
"#
$protocols = $protocolsJSON | ConvertFrom-Json
$i = 0
$tempdisabledKVString = 'Server-Enabled'
if ($protocols[$i]."$tempdisabledKVString" -eq 'True') {
":)"
} else {
":("
}
In theory these issues should have caused exceptions to be thrown. For some reason you're not seeing those, or that would have prompted you to find the cause. Please check the value of $ErrorActionPreference; by default it should be set to Continue; but it looks like it may have been updated to SilentlyContinue for your session. It's OK to have this setting in some scenarios; but generally better to have errors be thrown when they occur so that you can see what's going wrong.

MongoDB migrations for .NET Core

I have a .NET Core project that works with mongoDb.
I did the research about data migrations and neither one solution works for me.
There is MongoMigrations NuGet package but it is not compatible with .NET Core.
A goal is to have some method that will check current db version and if it is not up to date, to do the certain update, for example to call some RemoveUserCollection() method or something like that.
Did anyone have the same problem, or even better a solution for that? :)
Thanks!
I've stumbled on this issue a few times myself but it takes pretty much 2mins to just manually bake it into your application startup or just script it out using javascript and deploy it like any other system change.
I've got a PowerShell script like
param([Parameter(Mandatory=$True)][string]$Hostname, [string]$Username = $null, [string]$Password = $null)
if($Username){
$authParameters = "-u $Username -p $Password --authenticationDatabase admin"
}
Write-Host "Running all migration scripts..."
$scripts = Get-Childitem | where {$_.extension -like '.js'} | foreach { $_.Name }
Invoke-Expression "c:\mongodb\bin\mongo.exe --host $Hostname $authParameters $scripts"
then I just dump a load of .js files in the same directory.
;
(function () {
var migration = { _id: ObjectId("568b9e75e1e6530a2f4d8884"), name: "Somekinda Migration (929394)" };
var testDb = db.getMongo().getDB('test');
if (!testDb.migrations.count({ _id: migration._id })) {
testDb.migrations.insert(migration);
print('running ' + migration.name)
// Do Work
testDb.people.find().snapshot().forEach(
function (alm) {
testDb.people.save(
{
modifiedAt: new Date(),
});
}
)
}
})();

Configure a DSC Resource to restart

I have a DSC resource that installs dotnet feature and then installs an update to dotnet.
In the Local Configuration Manager I have set RebootNodeIfNeeded to $true.
After dotnet installs, it does not request a reboot (even used xPendingReboot module to confirm this).
Configuration WebServer
{
WindowsFeature NetFramework45Core
{
Name = "Net-Framework-45-Core"
Ensure = "Present"
}
xPendingReboot Reboot
{
Name = "Prior to upgrading Dotnet4.5.2"
}
cChocoPackageInstaller InstallDotNet452
{
name = "dotnet4.5.2"
}
}
This is a problem as dotnet doesn't work properly with our app unless the server has been rebooted and we are trying to make these reboots happen automatically no user input required.
Is there any way to make a resource push to the localdscmanager (LCM) that it needs a reboot when there's something being installed?
I have found the below command
$global:DSCMachineStatus = 1
Which sets a reboot. but I'm unsure as to how to use it to reboot right after the 4.5 module is installed.
Normally when I install .Net it works without rebooting, but if you want to force your configuration to reboot it after it installs it you can do the following. It won't work for drift (.net being removed after initial installation.) During configuration drift, the configuration will still install .net, but the script resource I added to reboot will believe it has already rebooted.
The DependsOn is very important here, you don't want this script running before the WindowsFeature has run successfully.
configuration WebServer
{
WindowsFeature NetFramework45Core
{
Name = "Net-Framework-45-Core"
Ensure = "Present"
}
Script Reboot
{
TestScript = {
return (Test-Path HKLM:\SOFTWARE\MyMainKey\RebootKey)
}
SetScript = {
New-Item -Path HKLM:\SOFTWARE\MyMainKey\RebootKey -Force
$global:DSCMachineStatus = 1
}
GetScript = { return #{result = 'result'}}
DependsOn = '[WindowsFeature]NetFramework45Core'
}
}
To get $global:DSCMachineStatus = 1 working, you first need to configure Local Configuration Manager on the remote node to allow Automatic reboots. You can do it like this:
Configuration ConfigureRebootOnNode
{
param (
[Parameter(Mandatory=$true)]
[ValidateNotNullOrEmpty()]
[String]
$NodeName
)
Node $NodeName
{
LocalConfigurationManager
{
RebootNodeIfNeeded = $true
}
}
}
ConfigureRebootOnNode -NodeName myserver
Set-DscLocalConfigurationManager .\ConfigureRebootOnNode -Wait -Verbose
(code taken from colin's alm corner)

How many status of azure deployment could be

All, I am trying to deploy my cloud service to Windows Azure. Currently It works fine. But I still try to understand the detail inside of it . Like below Power Shell script.
The script is trying to get the status of a deplpoyment in the Staging slot after New-AzureDeployment has been executed successfully.
while ($True) {
$deployment = Get-AzureDeployment -ServiceName $CloudServiceName -Slot Staging
if ($deployment.Status -ne 'Running') {
continue
}
$notReadyList = $deployment.RoleInstanceList | Where-Object InstanceStatus -ne 'ReadyRole'
if (!$notReadyList) {
break
}
$errorStatusList = #('RestartingRole';'CyclingRole';'FailedStartingRole';'FailedStartingVM';'UnresponsiveRole')
$errorList = $notReadyList | Where-Object InstanceStatus -in $errorStatusList
if ($errorList) {
throw 'Role in staging fail to start for some of these reasons:' + ($errorList | Format-List | Out-String)
}
Start-Sleep -Seconds 10
}
I have some questions about the script . Please try to help me .thanks.
What is the object type of Get-AzureDeployment return ? I search it in the Help Doc. But did't found any information about it.
How many possible status except Running the Get-AzureDeployment could return ?
Is there any possibility never break in the loop ?
Thanks.
What is the object type of Get-AzureDeployment return ? I search it in
the Help Doc. But did't found any information about it.
As mentioned in the documentation, this operation returns an object of type DeploymentInfoContext. You can find more about this object here: https://github.com/WindowsAzure/azure-sdk-tools/blob/master/WindowsAzurePowershell/src/Commands.ServiceManagement/Model/DeploymentInfoContext.cs. However if you look at the source code for Get-AzureDeployment here: https://github.com/WindowsAzure/azure-sdk-tools/blob/master/WindowsAzurePowershell/src/Commands.ServiceManagement/HostedServices/GetAzureDeployment.cs, you'll notice that it returns the following:
return new DeploymentInfoContext(d)
{
OperationId = s.Id,
OperationStatus = s.Status.ToString(),
OperationDescription = CommandRuntime.ToString(),
ServiceName = this.ServiceName
};
How many possible status except Running the Get-AzureDeployment could
return ?
You can find the list of possible statuses here: http://msdn.microsoft.com/en-us/library/windowsazure/ee460804.aspx.
Following is copied from the link above:
Is there any possibility never break in the loop ?
I'm not sure about that. I guess you will need to test it out thoroughly. The statuses may change with the newer versions of Service Management API so you would need to ensure that your code covers all possible statuses.
Get-AzureDeployment returns an object of schema shown below
SdkVersion :
RollbackAllowed : False
Slot : Production
Name :
DeploymentName : [Somename]
Url : http://[Somename].cloudapp.net/
Status : Suspended
CurrentUpgradeDomain : 0
CurrentUpgradeDomainState :
UpgradeType :
RoleInstanceList : {}
Configuration :
DeploymentId : [SomeGUID]
Label : [Somename]
VNetName : [Somename]
DnsSettings :
OSVersion :
RolesConfiguration : {[[Somename], Microsoft.WindowsAzure.Commands.ServiceManagement.Model.RoleConfiguration]}
ServiceName : [Somename]
OperationDescription : Get-AzureDeployment
OperationId : 1801bce8-73b4-5a74-9e80-e03d04ff405b
OperationStatus : Succeeded