Powershell query multidimensional hash - powershell

I'm struggling creating and querying data of an object. (I think hash table)
two environment (test and production)
two servertypes per environment (webserver and appl servers)
1 or more servers of each type
I want to store the hostnames within the applicable section. I created the following hash:
$arr =#{}
$arr.Environment = #{}
$arr.Environment.Production = #{}
$arr.Environment.Production.serverType = #{}
$arr.Environment.Production.serverType.webServer = #{}
$arr.Environment.Production.serverType.entServer = #{}
$arr.Environment.Test = #{}
$arr.Environment.Test.serverType = #{}
$arr.Environment.Test.serverType.webServer = #{}
$arr.Environment.Test.serverType.entServer = #{}
I found that I can access data like:
$serversArray.Environment.Test.serverType.webServer
I would like to know:
is this the right way of doing this? are there better / easier way to accomplish this?
how do I loop/filter this object, retrieving servernames that meet the specified criteria? Since I need to have 1. all test webservers then 2. all test appl servers etc
thanks

If you're able to save all this in one go (using variables or hardcoded strings), you should be using the native format to store it - much more readable.
See
$Optiplex = #{
'Brand' = 'Dell'
'Model' = 'Optiplex'
'Specs' = #{
'RAM' = '4 GB'
'CPU' = 'Intel i5'
'USB Ports' = '3'
'CD/DVD Drive' = 'No'
'HDD' = '320 GB - SSD'
} #Specs
} #Optiplex
From this walkthrough
You'll be able to access the variables for the hashtable in the same way, such as Optiplex.Specs.RAM to get the value for RAM.
Edit: To better answer question number 2, here's some idea on looping:
foreach ($serverTypeToKVs in $arr.Environment.Production.serverType.GetEnumerator()) {
Write-Host "ServerType $(serverTypeToKVs.Name):"
foreach ($keyVal in $serverTypeToKVs.Value.GetEnumerator()) {
# Logic if serverTypeToKVs.Name == "webServer"
# Logic if keyVal == something
# General work to be done
}
}

I found following way to achieve this:
$order = #(("Test","Production"),("webServer", "entServer"))
foreach($env in $order[0]) {
Write-Host "Environment: $env"
foreach($svr in $order[1]) {
Write-Host "ServerType: $svr"
write-host "hostnames: "$serversArray.Environment.$($env).serverType.$($svr)
}
}
This will loop the correct way/sequence and lists correct servers:
Environment: Test
ServerType: webServer
hostnames: tweb1 tweb2
ServerType: appServer
hostnames: tapp1
Environment: Production
ServerType: webServer
hostnames: pweb1 pweb2 pweb3
ServerType: appServer
hostnames: papp1 papp2 papp3 papp4

Related

How to remove a permission, a member, or a role?

I have this script below to add roles and members and permissions
Import-Module sqlserver
$Server = new-Object Microsoft.AnalysisServices.Tabular.Server
$Server.Connect("SERVER\INSTANCE")
$TabDB = $SERVER.Databases["DATABASENAME"]
$AddRole = new-Object Microsoft.AnalysisServices.Tabular.ModelRole
$AddRole.Name = 'NewRole1'
$AddRole.ModelPermission="Read"
$RoleMember = New-Object Microsoft.AnalysisServices.Tabular.WindowsModelRoleMember
$RoleMember.MemberName = 'DOMAIN\ACCOUNT'
$TabDB.Model.Roles.Add($AddRole)
$AddRole.Members.Add($RoleMember)
$TabDB.Update([Microsoft.AnalysisServices.UpdateOptions]::ExpandFull)
$server.Disconnect()
How can I remove a permission, a member, and a role?
I tried this at least for the role, but the console returns back "False"
$TabDB.Model.Roles.Remove($AddRole)
When working with ssas from powershell (or C# for that matter) you can use the analysisservices namespace of microsoft:
Microsoft analysisservices.
This is an object oriented way of working with ssas databases.
This is an old script I wrote for maintainers:
function addRoleToDb {
$roleName = Read-Host "How should this role be called?"
if ($global:dataBase.Roles.findByName($roleName)) {
echo "This role already exists"
return
} elseif ($roleName -eq "") {
echo "You can't give an empty name for a role."
return
}
echo "Warning: this role will start out empty and will have to be modified in order to be used. (it wil have read permission)"
[Microsoft.AnalysisServices.Role] $newRole = New-Object([Microsoft.AnalysisServices.Role])($roleName)
$global:dataBase.Roles.add($newRole)
$dbperm = $global:dataBase.DatabasePermissions.add($newRole.ID)
$dbperm.Read = [Microsoft.AnalysisServices.ReadAccess]::Allowed
$global:dataBase.Roles.Update()
$dbperm.Update()
return
}
At this point I already had a global variable database.
This is a method that would add a role to the database. Deleting the database would work practically the same, you would get the instance of the role with:
role = database.roles.findbyname()
or
role = database.roles.findbyid()
and then
role.Drop(DropOptions.AlterOrDeleteDependents);
You should check that last line before using it because the alterordeletedependants is something I now use in my c# program, I don't remember if it worked in powershell.
Good luck!

Auto creation of Service without DefaultServices on developer machines

At the recent Service Fabric Community Q&A 24th Edition there was a lot of discussion around using the DefaultService construct in the ApplicationManifest.xml and it's drawbacks. Microsoft suggested omitting this from an ApplicationManifest entirely and instead modifying the Deploy-FabricApplication.ps1 to construct a default implementation of an application so developers still have a decent F5 experience.
So I have modified the Deploy-FabricApplication.ps1 to the following (this excerpt is the bottom of the script):
if ($IsUpgrade)
{
$Action = "RegisterAndUpgrade"
if ($DeployOnly)
{
$Action = "Register"
}
$UpgradeParameters = $publishProfile.UpgradeDeployment.Parameters
if ($OverrideUpgradeBehavior -eq 'ForceUpgrade')
{
# Warning: Do not alter these upgrade parameters. It will create an inconsistency with Visual Studio's behavior.
$UpgradeParameters = #{ UnmonitoredAuto = $true; Force = $true }
}
$PublishParameters['Action'] = $Action
$PublishParameters['UpgradeParameters'] = $UpgradeParameters
$PublishParameters['UnregisterUnusedVersions'] = $UnregisterUnusedApplicationVersionsAfterUpgrade
Publish-UpgradedServiceFabricApplication #PublishParameters
}
else
{
$Action = "RegisterAndCreate"
if ($DeployOnly)
{
$Action = "Register"
}
$PublishParameters['Action'] = $Action
$PublishParameters['OverwriteBehavior'] = $OverwriteBehavior
$PublishParameters['SkipPackageValidation'] = $SkipPackageValidation
Publish-NewServiceFabricApplication #PublishParameters
#Get-ServiceFabricApplication
New-ServiceFabricService -Stateless -ApplicationName "fabric:/Acme.Hierarchy" -ServiceTypeName "Acme.Hierarchy.HierarchyServiceType" -ServiceName "fabric:/Acme.Hierarchy/Acme.Hierarchy.HierarchyService"-InstanceCount 1 -PartitionSchemeSingleton
}
The above fails with the error
FabricElementNotFoundException
However, if you uncomment the line #Get-ServiceFabricApplication you will see that it does in fact return an application of
ApplicationName : fabric:/Acme.Hierarchy
ApplicationTypeName : Acme.HierarchyType
ApplicationTypeVersion : 1.0.0
ApplicationParameters : { "_WFDebugParams_" = "[{"CodePackageName":"Code","Cod
ePackageLinkFolder":null,"ConfigPackageName":null,"Con
figPackageLinkFolder":null,"DataPackageName":null,"Dat
aPackageLinkFolder":null,"LockFile":null,"WorkingFolde
r":null,"ServiceManifestName":"Quantium.RetailToolkit.
Fabric.Hierarchy.HierarchyServicePkg","EntryPointType"
:"Main","DebugExePath":"C:\\Program Files
(x86)\\Microsoft Visual Studio\\2017\\Professional\\Co
mmon7\\Packages\\Debugger\\VsDebugLaunchNotify.exe","D
ebugArguments":"
{6286e1ef-907b-4371-961c-d833ab9509dd} -p [ProcessId]
-tid [ThreadId]","DebugParametersFile":null}]";
"Acme.Hierarchy.HierarchyServ
ice_InstanceCount" = "1" }
Create application succeeded.
and running the command that fails after the publish script has finished works perfectly.
Does anyone have a solution as to how I can get a good developer experience by not using DefaultServices and instead using Powershell scripts?
Thanks in advance
I have updated the answer to add more details why the default services should not be used (In production only).
On service fabric, you have two options to create your services:
The Declarative way, done via Default Services feature where you describe services that should run as part of your application using the ApplicationManifest.
and the Dynamic(Imperative) way using powershell commands to create these services once the application is deployed.
The declarative way bring you the convenience of defining the expected structure of your application, so that Service Fabric does the job of creating and starting instances of your services according to the declaration in the ApplicationManifest. The convenience it gives you is very useful for development purposes, imagine if every time you had to debug an application, it had to: Build > Package > Deployed to Service Fabric > You had to manually start the many services that define your application. This would be too inconvenient, so that is why default service become handy.
Another scenario is when your application definition immutable, that means, the same number of services and instances will stay the same without variation throughout the time it is deployed in production.
But we know this is high unlikely that these definitions will keep the same throughout the years or even hours in a day, because the idea of microservices is that they should be scalable and flexible, so that we can tweak the configuration of individual services independent of each other.
By using default services, would be too complex for the orchestration logic identify what changes has been made on your services compared to the default specified in the original deployment, and in cases of conflict, which configuration should have priority, for example:
The deployed default services define a service with 5 instances, after it is deployed you execute an powershell script to update to 10 instances, then a new application upgrade comes in with the default services having 5 instances or a new value of 8, what should happen? which one is the correct?
You add an extra named services (service of same type with other name) to an existing deployment that is not defined in the default services, what happens when the new deployment comes in and say that this service should not be expected? Delete it? And the data? How this service should be removed from production? If I removed by mistake during development?
A new version deletes an existing service, the deployment fails, how the old service should be recreated? And if there was any data there to be migrated as part of the deployment?
A service has been renamed. How do I track that it was renamed instead of removing the old and adding a new one?
These is some of the many issues that can happen. This is why you should move away from default services and create them dynamically(imperatively), with dynamic services, service fabric will receive an upgrade command and what will happen is:
"This is my new application type package with new service type
definitions, whatever version you get deployed there, replace for this
version and keep the same configuration".
If a new configuration is required, you will provide as parameters for the deployment to override the old values or change it on a separate command. This will make things much simpler, as SF won't have to worry about different configurations and will just apply package changes to deployed services.
You can also find a nice info about these issues on these links:
How not to use service fabric default services
Service Fabric Q&A 10
Service Fabric Q&A 11
Regarding your main question:
Does anyone have a solution as to how I can get a good developer
experience by not using DefaultServices and instead using Powershell
scripts?
if you want a good experience you should use the default services, it is intended for this, give the developer a good experience without worrying about services required to run at startup.
The trick is, during your CI process, you should remove the default services from the application manifest before you pack your application, so that you don't face the drawbacks later.
Removing the defaultServices during CI (Like VSTS Build), you have the benefits of defaultServices on dev environment, don't have to maintain the powershell script versions(if a new version comes along) and the removal of the default services is a very simple powershell script added as a build step. Other than that, everything keeps the same.
Ps: I don't have a real script at hand now, but will be very simple like this:
$appManifest = "C:\Temp\ApplicationManifest.xml" #you pass as parameter
[xml]$xml = Get-Content $appManifest
$xml.ApplicationManifest.DefaultServices.RemoveAll()
$xml.save($appManifest)
The solution here is to use a script named Start-Service.ps1 in the Scripts folder in Application project.
Below is an example script for the Data Aggregation sample Microsoft have provided.
$cloud = $false
$singleNode = $true
$constrainedNodeTypes = $false
$lowkey = "-9223372036854775808"
$highkey = "9223372036854775807"
$countyLowKey = 0
$countyHighKey = 57000
$appName = "fabric:/DataAggregation"
$appType = "DataAggregationType"
$appInitialVersion = "1.0.0"
if($singleNode)
{
$webServiceInstanceCount = -1
$deviceCreationInstanceCount = -1
$countyServicePartitionCount = 1
$deviceActorServicePartitionCount = 1
$doctorServicePartitionCount = 1
}
else
{
$webServiceInstanceCount = #{$true=-1;$false=1}[$cloud -eq $true]
$deviceCreationInstanceCount = #{$true=-1;$false=1}[$cloud -eq $true]
$countyServicePartitionCount = #{$true=10;$false=5}[$cloud -eq $true]
$deviceActorServicePartitionCount = #{$true=15;$false=5}[$cloud -eq $true]
$doctorServicePartitionCount = #{$true=100;$false=5}[$cloud -eq $true]
if($constrainedNodeTypes)
{
$webServiceConstraint = "NodeType == "
$countyServiceConstraint = "NodeType == "
$nationalServiceConstraint = "NodeType == "
$deviceServiceConstraint = "NodeType == "
$doctorServiceConstraint = "NodeType == "
$deviceCreationServiceConstraint = "NodeType == "
}
else
{
$webServiceConstraint = ""
$countyServiceConstraint = ""
$nationalServiceConstraint = ""
$deviceServiceConstraint = ""
$doctorServiceConstraint = ""
$deviceCreationServiceConstraint = ""
}
}
$webServiceType = "DataAggregation.WebServiceType"
$webServiceName = "DataAggregation.WebService"
$nationalServiceType = "DataAggregation.NationalServiceType"
$nationalServiceName = "DataAggregation.NationalService"
$nationalServiceReplicaCount = #{$true=1;$false=3}[$singleNode -eq $true]
$countyServiceType = "DataAggregation.CountyServiceType"
$countyServiceName = "DataAggregation.CountyService"
$countyServiceReplicaCount = #{$true=1;$false=3}[$singleNode -eq $true]
$deviceCreationServiceType = "DataAggregation.DeviceCreationServiceType"
$deviceCreationServiceName = "DataAggregation.DeviceCreationService"
$doctorServiceType = "DataAggregation.DoctorServiceType"
$doctorServiceName = "DataAggregation.DoctorService"
$doctorServiceReplicaCount = #{$true=1;$false=3}[$singleNode -eq $true]
$deviceActorServiceType = "DeviceActorServiceType"
$deviceActorServiceName= "DataAggregation.DeviceActorService"
$deviceActorReplicaCount = #{$true=1;$false=3}[$singleNode -eq $true]
New-ServiceFabricService -ServiceTypeName $webServiceType -Stateless -ApplicationName $appName -ServiceName "$appName/$webServiceName" -PartitionSchemeSingleton -InstanceCount $webServiceInstanceCount -PlacementConstraint $webServiceConstraint -ServicePackageActivationMode ExclusiveProcess
#create national
New-ServiceFabricService -ServiceTypeName $nationalServiceType -Stateful -HasPersistedState -ApplicationName $appName -ServiceName "$appName/$nationalServiceName" -PartitionSchemeSingleton -MinReplicaSetSize $nationalServiceReplicaCount -TargetReplicaSetSize $nationalServiceReplicaCount -PlacementConstraint $nationalServiceConstraint -ServicePackageActivationMode ExclusiveProcess
#create county
New-ServiceFabricService -ServiceTypeName $countyServiceType -Stateful -HasPersistedState -ApplicationName $appName -ServiceName "$appName/$countyServiceName" -PartitionSchemeUniformInt64 -LowKey $countyLowKey -HighKey $countyHighKey -PartitionCount $countyServicePartitionCount -MinReplicaSetSize $countyServiceReplicaCount -TargetReplicaSetSize $countyServiceReplicaCount -PlacementConstraint $countyServiceConstraint -ServicePackageActivationMode ExclusiveProcess
#create doctor
New-ServiceFabricService -ServiceTypeName $doctorServiceType -Stateful -HasPersistedState -ApplicationName $appName -ServiceName "$appName/$doctorServiceName" -PartitionSchemeUniformInt64 -LowKey $lowkey -HighKey $highkey -PartitionCount $doctorServicePartitionCount -MinReplicaSetSize $doctorServiceReplicaCount -TargetReplicaSetSize $doctorServiceReplicaCount -PlacementConstraint $doctorServiceConstraint -ServicePackageActivationMode ExclusiveProcess
#create device
New-ServiceFabricService -ServiceTypeName $deviceActorServiceType -Stateful -HasPersistedState -ApplicationName $appName -ServiceName "$appName/$deviceActorServiceName" -PartitionSchemeUniformInt64 -LowKey $lowkey -HighKey $highkey -PartitionCount $deviceActorServicePartitionCount -MinReplicaSetSize $deviceActorReplicaCount -TargetReplicaSetSize $deviceActorReplicaCount -PlacementConstraint $deviceServiceConstraint -ServicePackageActivationMode ExclusiveProcess -Verbose
#create device creation
New-ServiceFabricService -ServiceTypeName $deviceCreationServiceType -Stateless -ApplicationName $appName -ServiceName "$appName/$deviceCreationServiceName" -PartitionSchemeSingleton -InstanceCount $deviceCreationInstanceCount -PlacementConstraint $deviceCreationServiceConstraint -ServicePackageActivationMode ExclusiveProcess

PowerShell Active Directory list all Multi-Valued attributes

not sure if I'm chaing the wild goose here but as per subject I'd need to get a list of AD attributes, for the user ObjectClass, that are multie valued.
For example the proxyAddresses exchange specific attribute is multi valued where extensionAttribute* only accept a single string.
We use a heavily customized schema and while I could go through each attribute documentation I'd rather get a list of aforementioned attributes via PowerShell.
I've tried using ldp.exe but could not achive desired results and was wondering if there is a way to do this via PowerShell or .Net managed code.
Thanks in advance for any help/pointer.
So you have to query the Schema part of the directory and look for objectClass attributeSchema and attribute isSingleValued (FALSE). The part of the distinguichName wichh is invariant is : CN=Schema,CN=Configuration.
try first with CSV :
csvde -f MultivaluedAttributes.csv -d CN=Schema,CN=Configuration,DC=MySubdomain,DC=MyDomain,DC=com -r "(&(objectclass=attributeSchema)(isSingleValued=FALSE))" -l lDAPDisplayName
Here is the powershell code.
# LDAPSchemaQuery.PS1
try
{
$dn = New-Object System.DirectoryServices.DirectoryEntry ("LDAP://179.22.21.01/CN=Schema,CN=Configuration,DC=MyDomain,DC=MyExt","MyUser", 'MyPassword')
# Query into the Schema
# csvde -f MultivaluedAttributes.csv -d CN=Schema,CN=Configuration,DC=office,DC=coyotesystems,DC=com -r "(&(objectclass=attributeSchema)(isSingleValued=FALSE))" -l lDAPDisplayName
$Rech = new-object System.DirectoryServices.DirectorySearcher($dn)
#$Rech.filter = "(&(objectclass=user)(mail=*)(!(UserAccountControl:1.2.840.113556.1.4.803:=2)))"
$Rech.filter = "(&(objectclass=attributeSchema)(isSingleValued=FALSE))"
$Rech.SearchScope = "subtree"
$dumy=$Rech.PropertiesToLoad.Add("lDAPDisplayName")
$adAttributes = $Rech.findall()
foreach ($adAttribute in $adAttributes)
{
$multivaluedAttribute = try{$adAttribute.Properties["lDAPDisplayName"]}catch{""}
$multivaluedAttribute
}
}
catch
{
Write-Verbose "LDAPSchemaQuery : PB with $($adAttribute.Path)"
}

Function to return smallest db is not working

I have some PoSH function that I found online that will return the smallest exchange database. In testing the script I found that it does not work as intended; that is the smallest database returned is not actually correct.
This is the code:
#http://izzy.org/scripts/Exchange/Admin/Create-Mailbox.ps1
$DBFilter = "MBX_*" # Limit databases to only those that start with "Primary"
Function Get-SmallestDB {
Try {
$MBXDbs = Get-MailboxDatabase | ? {$_.Identity -like $DBFilter }
$MBXDBCount = $PSSessions.Count
}
Catch {
$MBXDBCount = 0
}
If (!$MBXDbs) {ExitScript "find databases with a name that matches a filter of [$DBFilter]." $False}
# Loop through each of the MBXDbs
ForEach ($MBXDB in $MBXDbs) {
# Get current mailboxes sizes by summing the size of all mailboxes and "Deleted Items" in the database
$TotalItemSize = Get-MailboxStatistics -Database $MBXDB | %{$_.TotalItemSize.Value.ToMB()} | Measure-Object -sum
$TotalDeletedItemSize = Get-MailboxStatistics -Database $MBXDB.DistinguishedName | %{$_.TotalDeletedItemSize.Value.ToMB()} | Measure-Object -sum
$TotalDBSize = $TotalItemSize.Sum + $TotalDeletedItemSize.Sum
Write-Host "$MBXDB $($TotalItemSize.Sum) $($TotalDeletedItemSize.Sum) $TotalDBSize"
# Compare the sizes to find the smallest DB
If (($TotalDBSize -lt $SmallestDBsize) -or ($SmallestDBsize -eq $null)) {
$SmallestDBsize = $DBsize
$SmallestDB = $MBXDB }}
return $SmallestDB }
Basically when i run this in my Exchange environment it returns "MBX_20" as $SmallestDB. But I added some debug code (Write-Host to output values for $($TotalItemSize.Sum, $($TotalDeletedItemSize.Sum) and $TotalDBSize and the results are:
MBX_1 140561 5180 145741
MBX_2 190865 15882 206747
MBX_3 174393 1714 176107
MBX_4 122362 6479 128841
MBX_5 108833 15409 124242
MBX_6 196569 13793 210362
MBX_7 114298 2144 116442
MBX_8 140896 21558 162454
MBX_9 160024 13364 173388
MBX_10 188268 6046 194314
MBX_11 132256 15300 147556
MBX_12 173262 6486 179748
MBX_13 101107 3761 104868
MBX_14 131453 4930 136383
MBX_15 134682 4424 139106
MBX_16 146767 12484 159251
MBX_17 155224 2074 157298
MBX_18 117147 12270 129417
MBX_19 129101 6597 135698
MBX_20 134675 9059 143734
As you can see MBX_20 with 143734 is NOT the smallest db. I am now trying to fix the code but I am not very good with PoSH. Any tips?
Taking from my comment, I think it's a typo and
$SmallestDBsize = $DBsize
should be
$SmallestDBsize = $TotalDBSize

How do I retrieve PR_RULE_ACTIONS via PowerShell and the EWS Managed API?

I have need of retrieving and inspecting the delegate forwarding rule (the built-in delegate commands in EWS being inadequate for my needs since they choke on groups being used as delegates).
I am able to successfully locate the rule created by "Schedule+ EMS Interface". However, I am unable to retrieve PR_RULE_ACTIONS. Turning on tracing.
I see that the PidTagRuleMsgProvider property is getting returned just fine, but PR_RULE_ACTIONS never does.
I suspect that I am using the wrong MAPI property type in the propertyset definition, but I've gone through everything listed at http://msdn.microsoft.com/en-us/library/exchangewebservices.mapipropertytypetype(v=exchg.140).aspx . Any clues?
Here is the relevant snippet of code:
# Setup Basic EWS Properties for Message Search - Used to locate Hidden Forwarding Rule
$searchFilterForwardRule = New-Object Microsoft.Exchange.WebServices.Data.SearchFilter+ContainsSubstring([Microsoft.Exchange.WebServices.Data.ItemSchema]::ItemClass, "IPM.Rule", [Microsoft.Exchange.WebServices.Data.ContainmentMode]::Prefixed, [Microsoft.Exchange.WebServices.Data.ComparisonMode]::Exact)
$itemViewForwardRule = New-Object Microsoft.Exchange.WebServices.Data.ItemView(30, 0, [Microsoft.Exchange.Webservices.Data.OffsetBasePoint]::Beginning)
$itemViewForwardRule.PropertySet = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties, [Microsoft.Exchange.WebServices.Data.ItemSchema]::ItemClass, [Microsoft.Exchange.WebServices.Data.ItemSchema]::Subject)
$itemViewForwardRule.Traversal = [Microsoft.Exchange.WebServices.Data.ItemTraversal]::Associated
# Properties for Hidden Delegate Forwarding Rule
$PID_TAG_RULE_MSG_PROVIDER = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x65EB,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String)
$PID_TAG_RULE_ACTIONS = New-Object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x6680,[Microsoft.Exchange.WebServices.Data.MapiPropertyType]::Binary)
# Property Set for Delegate Forward Rule
$propertySetForwardRule = New-Object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties, $PID_TAG_RULE_MSG_PROVIDER)
$forwardRuleExists = $false
$findResults = $service.FindItems([Microsoft.Exchange.Webservices.Data.WellKnownFolderName]::Inbox, $searchFilterForwardRule, $itemViewForwardRule)
If ($findResults.TotalCount -lt 1) {
Write-Error "Failed to find rule" "Error"
} Else {
Foreach ($item in $findResults.Items) {
$item.Load($propertySetForwardRule)
If ($item.ExtendedProperties.Count -ge 1) {
If ($item.ExtendedProperties[0].Value -eq "Schedule+ EMS Interface") {
$forwardRuleExists = $true
write-host "Delegate forwarding rule found." -ForegroundColor Cyan
$propertySetForwardRule.Add($PID_TAG_RULE_ACTIONS)
$item.Load($propertySetForwardRule)
Write-Host "Attempting to retrieve x6680 PR_RULE_ACTIONS (PidTagRuleActions)" -ForegroundColor Cyan
$PR_RULE_ACTIONS = $null
if($Item.TryGetProperty($Pid_Tag_Rule_Actions,[ref]$PR_RULE_ACTIONS)){
return $PR_RULE_ACTIONS
} # endif
else {write-host "TryGetProperty for PR_RULE_ACTIONS failed!" -ForegroundColor Red
} # endelse
} # End If - Correct Message
} # End If - Has Extended Properties
} # End ForEach
} # End If - Message Count
Glen Scales was able to set me on the right path. It turns out that PR_RULE_ACTIONS is not exposed via EWS, but the same data exposed via an attribute called PR_EXTENDED_RULE_ACTIONS. Now I'm happily slinging code to parse the binary blob.
http://msdn.microsoft.com/en-us/library/ee218391(v=EXCHG.80).aspx
The property tag for PR_RULE_ACTIONS is 0x668000FE. You can see it (and the property data) in OutlookSpy (I am its author) - go to the Inbox folder, click IMAPIFolder button, go to the PR_RULES_TABLE tab, select the rule, double click on the PR_RULE_ACTIONS property.
Note that PT_ACTIONS MAPI type (0x000FE) is only accessing in Extended MAPI, I don't think EWS will be able to return it.