How many status of azure deployment could be - powershell

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

Related

Loading .msg file contents Using Powershell - Null Value error

I am trying to access the metadata in a .msg file using Powershell (for example, get the sender address, subject line etc)
I have the following, simple code
Add-Type -assembly "Microsoft.Office.Interop.Outlook"
$outlook = New-Object -comObject Outlook.Application
$msg = $outlook.Session.OpenSharedItem("C:\Test\email.msg")
but I get the error
You cannot call a method on a null-valued expression. At line:4 char:1
If I run
$outlook
I get
Application :
Class :
Session :
Parent :
Assistant :
Name :
Version :
COMAddIns :
Explorers :
Inspectors :
LanguageSettings :
ProductCode :
AnswerWizard :
FeatureInstall :
Reminders :
DefaultProfileName :
IsTrusted :
Assistance :
TimeZones :
PickerDialog :
all the properties appear to be null, including .Session, which explains why I get the null value error.
What have I done wrong in creating the $outlook object?
I have tried with both Outlook running and not running and the same happens.
I have Office 365 installed and I'm using Powershell 5.1.19041.1320
I managed to fix this issue by doing a "Quick Repair" of O365 in the programs and features dialog
On Windows 10 Pro and "Microsoft 365 Apps for Business," Quick Repair also worked for me 7/15/2022 when my similar script which creates a CVS export of selected Outlook Contacts stopped working, for the same reason, namely that the assignment to $outlook completed normally, but then $outlook had no parameter values, just as you show above, leading to the same null-valued expression error.
I had not run the script for a month or more, so can't say which or what kind of update broke it.
Here is an example of a valid value for $outlook, after repair (I set Product Code to all 0s in case that value identifies my license):
Application : Microsoft.Office.Interop.Outlook.ApplicationClass
Class : olApplication
Session : Microsoft.Office.Interop.Outlook.NameSpaceClass
Parent :
Assistant : System.__ComObject
Name : Outlook
Version : 16.0.0.15330
COMAddIns : System.__ComObject
Explorers : {}
Inspectors : {System.__ComObject, System.__ComObject, System.__ComObject, System.__ComObject...}
LanguageSettings : System.__ComObject
ProductCode : {00000000-0000-0000-0000-000000000000}
AnswerWizard :
FeatureInstall : msoFeatureInstallOnDemand
Reminders : {$null, $null, $null, $null...}
DefaultProfileName : MS-2017-10
IsTrusted : False
Assistance : System.__ComObject
TimeZones : {System.__ComObject, System.__ComObject, System.__ComObject, System.__ComObject...}
PickerDialog : System.__ComObject

Readling Data from Serial Port Causes Powershell to Hang

I don't have any experience in serial port communications, but I need to come up with a PowerShell tool to query a device (display) connected through my USB port via RS232 (connected using Trendnet /Prolific USB-to-serial adapter)
I use PowerShell v 5.0
I wouldn't expect it to be a very complicated script.
Here is what I currently have
$p = Get-ItemProperty -Path "hklm:\hardware\devicemap\serialcomm\" -name "*prolific*" | Select-Object -ExpandProperty \Device\ProlificSerial*
$PowerStatus = "query power status"
$port= new-Object System.IO.Ports.SerialPort $p,9600,None,8,one
$port.DTREnable = "true"
$port.RtsEnable = "true"
$port.open()
$port.WriteLine($powerstatus)
# reading operation
$line = $port.ReadLine()
Write-Host $line
When I run this, Powershell hangs. Sometimes I get either "access to the COM port is denied" or
Exception calling "ReadLine" with "0" argument(s): "The port is closed."
Either way, I don't get any response and have to restart PowerShell every time :)
Apparently I am able to write to the port. I am able to power the display on and off from PowerShell.
When I check the port status after I write the "query power status" command, it looks like this
PS C:\WINDOWS\system32> $port
BaseStream : System.IO.Ports.SerialStream
BaudRate : 9600
BreakState : False
BytesToWrite : 0
BytesToRead : 10
CDHolding : False
CtsHolding : False
DataBits : 8
DiscardNull : False
DsrHolding : False
DtrEnable : True
Encoding : System.Text.ASCIIEncoding
Handshake : None
IsOpen : True
NewLine :
Parity : None
ParityReplace : 63
PortName : COM3
ReadBufferSize : 4096
ReadTimeout : -1
ReceivedBytesThreshold : 1
RtsEnable : True
StopBits : One
WriteBufferSize : 2048
WriteTimeout : -1
Site :
Container :
I see there are bytes sitting in the buffer but cannot get a response.
It looks like the port is still being used by the writing operation? so when I try to read, the port is busy
Please let me know what I am doing wrong. Thank you

IIS Administration from TFS Release automation - PowerShell script fails Get-ChildItem -Path IIS:\Sites

I'm having difficulty in using the Powershell WebAdministration Module with Powershell 5.1.
This is on a Server 2008R2 machine, running IIS 7.5
There seems to be an issue with this module in that occasionally the module requires a few ms to complete initialization after loading. The recommendation is to do a simple 'write-output' after loading to allow the server to complete the init tasks. I dont see it on all the servers I'm managing, but this particular server is consistent in its need.
There's also an issue that I found people had with Get-Sites failing that could be dealt with by wrapping in a try/catch.
However, the problem I'm seeing is that even with the identified workarounds, I'm not getting consistent results between an interactive run, and a run that is performed from TFS Automated release.
Import-Module WebAdministration
$sites="none"
Write-Output "suggested as a work around for the task dying for no apparent reason"
try {
$sites = Get-ChildItem -Path IIS:\Sites
Write-Output "part of try"
} catch {
$sites = Get-ChildItem -Path IIS:\Sites
Write-Output "part of catch"
} finally {
Write-Output $sites
Write-Output $sites.GetType()
}
When run via TFS Release automation (agent version 2.117.2, PowerShell on the target machine version 1.0.47):
2018-01-25T13:18:29.5474995Z Importing alias 'End-WebCommitDelay'.
2018-01-25T13:18:29.5474995Z
2018-01-25T13:18:29.5474995Z suggested as a work around for the task dying for no apparent reason
2018-01-25T13:18:29.5474995Z part of catch
2018-01-25T13:18:29.5474995Z
2018-01-25T13:18:29.5474995Z
2018-01-25T13:18:29.5631000Z Deployment status for machine 'DESTSERV:5985' : 'Passed'
(no sitelist is returned)
When run as an interactive process (with same user)
PS C:\Users\Install> C:\Installers\Modules\test-iis.ps1
suggested as a work around for the task dying for no apparent reason
part of try
Name ID State Physical Path Bindings
---- -- ----- ------------- --------
AppTest 2 Started E:\WebApps\AppTest http *:80:
https *:443:
Test 1 Stopped C:\inetpub\wwwroot\Test http *:80:
https
Module : CommonLanguageRuntimeLibrary
Assembly : mscorlib, Version=4.0.0.0, Culture=neutral,
PublicKeyToken=b77a5c561934e089
TypeHandle : System.RuntimeTypeHandle
DeclaringMethod :
BaseType : System.Array
UnderlyingSystemType : System.Object[]
FullName : System.Object[]
AssemblyQualifiedName : System.Object[], mscorlib, Version=4.0.0.0,
Culture=neutral,
PublicKeyToken=b77a5c561934e089
Namespace : System
GUID : 00000000-0000-0000-0000-000000000000
IsEnum : False
GenericParameterAttributes :
IsSecurityCritical : False
IsSecuritySafeCritical : False
IsSecurityTransparent : True
IsGenericTypeDefinition : False
IsGenericParameter : False
GenericParameterPosition :
IsGenericType : False
IsConstructedGenericType : False
ContainsGenericParameters : False
StructLayoutAttribute :
Name : Object[]
MemberType : TypeInfo
DeclaringType :
ReflectedType :
MetadataToken : 33554432
GenericTypeParameters : {}
DeclaredConstructors : {Void .ctor(Int32)}
DeclaredEvents : {}
DeclaredFields : {}
DeclaredMembers : {Void Set(Int32, System.Object), System.Object&
Address(Int32), System.Object Get(Int32),
Void .ctor(Int32)}
DeclaredMethods : {Void Set(Int32, System.Object), System.Object&
Address(Int32), System.Object Get(Int32)}
DeclaredNestedTypes : {}
DeclaredProperties : {}
ImplementedInterfaces : {System.ICloneable, System.Collections.IList,
System.Collections.ICollection,
System.Collections.IEnumerable...}
TypeInitializer :
IsNested : False
Attributes : AutoLayout, AnsiClass, Class, Public, Sealed,
Serializable
IsVisible : True
IsNotPublic : False
IsPublic : True
IsNestedPublic : False
IsNestedPrivate : False
IsNestedFamily : False
IsNestedAssembly : False
IsNestedFamANDAssem : False
IsNestedFamORAssem : False
IsAutoLayout : True
IsLayoutSequential : False
IsExplicitLayout : False
IsClass : True
IsInterface : False
IsValueType : False
IsAbstract : False
IsSealed : True
IsSpecialName : False
IsImport : False
IsSerializable : True
IsAnsiClass : True
IsUnicodeClass : False
IsAutoClass : False
IsArray : True
IsByRef : False
IsPointer : False
IsPrimitive : False
IsCOMObject : False
HasElementType : True
IsContextful : False
IsMarshalByRef : False
GenericTypeArguments : {}
CustomAttributes : {[System.SerializableAttribute()]}
PS C:\Users\Install>
When WebAdministration doesn't import properly it seems there is more going wrong than just a slow initialization. The IIS: provider is not functional.. it throws no error. It does return something though - the value set at the top of the script is being overwritten... I just dont get the sites list.
As can be seen by the interactive run, there are sites present, so an empty return value does not make any sense.
Updated:
All the suggested workarounds have been applied yet the Get-ChildItem in the catch fails to produce the sites list. How do I get a consistent result where I can obtain the full list of sites in IIS both interactively and through TFS Release's PowerShell on the target machine task??
I can run the script via TFS Release automation without any error and get the consistent result with the interactive process. (Agent version 2.117.1, PowerShell on the target machine version 5.1.14393.1944).
You need to set the TFS build agent service account as an local administrator account in the target machine (Just add the build agent service account to the local administrators group).
So, please have a try with that. If that still not work, just try to upgrade the PowerShell version on your target machine (may be caused by the PS version). Refer to Install PowerShell 5 in Windows Server 2008 R2 for details.
UPDATE:
Generally, the output of the scripts will not back to build process when run the PS scripts with task PowerShell on the target machines.
You need to update the script to get back the outputs (use Write-Verbose instead of Write-Output ), just try below scripts, it works for me:
Import-Module WebAdministration
$sites="none"
Write-Verbose "suggested as a work around for the task dying for no apparent reason"
try {
$sites = Get-ChildItem -Path IIS:\Sites | Out-String
Write-Verbose "part of try"
} catch {
$sites = Get-ChildItem -Path IIS:\Sites | Out-String
Write-Verbose "part of catch"
} finally {
Write-Verbose $sites -verbose
Write-Verbose $sites.GetType() -verbose
}

Monitoring Service Fabric deployments

Im doing deployments from Jenkins job using powershell. THe job will be sucessful and the deployment starts on the cluster, but sometimes that fails and rollsback in which case I don't get notification of it.
Is there a way to monitor the upgrade from my jenkins job using a powershell cmdlet to poll the status or some way to know if it completed with a success or failure?
No clue if there is a smarter way, but you can get the upgrade state for a given application using the "Get-ServiceFabricApplicationUpgrade" cmdlet.
Get-ServiceFabricApplicationUpgrade -ApplicationName fabric:/your/awesomeApp
By pure coincidence i have an upgrade running on our cluster just now, and you get and output like the following (i have adjusted some names parameters etc):
ApplicationName : fabric:/your/awesomeApp
ApplicationTypeName : YourAwesomeApp.FabricType
TargetApplicationTypeVersion : 2017.1005.2-r20.1
ApplicationParameters : { "Param1" = "Value1";
"Param2" = "Value2";
"ActorService_MinReplicaSetSize" = "2";
"ActorService_PartitionCount" = "1";
"ActorService_TargetReplicaSetSize" = "3";
}
StartTimestampUtc : 05.10.2017 08.49.39
UpgradeState : RollingForwardInProgress
UpgradeDuration : 00:09:01
CurrentUpgradeDomainDuration : 00:00:00
NextUpgradeDomain : 4
UpgradeDomainsStatus : { "3" = "InProgress";
"0" = "Completed";
"1" = "Completed";
"2" = "Completed";
"4" = "Pending" }
UpgradeKind : Rolling
RollingUpgradeMode : Monitored
FailureAction : Rollback
ForceRestart : False
UpgradeReplicaSetCheckTimeout : 49710.06:28:15
HealthCheckWaitDuration : 00:00:00
HealthCheckStableDuration : 00:02:00
HealthCheckRetryTimeout : 00:10:00
UpgradeDomainTimeout : 00:30:00
UpgradeTimeout : 01:00:00
ConsiderWarningAsError :
MaxPercentUnhealthyPartitionsPerService :
MaxPercentUnhealthyReplicasPerPartition :
MaxPercentUnhealthyServices :
MaxPercentUnhealthyDeployedApplications :
ServiceTypeHealthPolicyMap :
This will also report if it is in a rollback state.
It might be interesting to figure out if you can get a callback/event or something from the Health Monitoring, because that is basically what causes the upgrade to rollback.

Assertion over each item in collection in Pester

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"
}
}
}