I want to get Outlook rules from all users and save them to file. Need to save only User/Identity property for each user to file. Getting mailbox rules with below command:
get-inboxrule -Mailbox "someuser"
It gives below output per user:
User1\4932760222472622720
User1\4452376263932772228
User1\8751003242422272538
User1\11330112527922022246
User1\11402172121922020282
User1\11424220272027238218
User1\11226228272065266254
User1\122122452224123294290
User2\11424222772022922212
User2\11226228322062262752
User2\11212345264223294290
I need to store such information to file and then read each time scripts run to compare results.
May you suggest what is the best scenario how to save such info?
Shall I use simple .txt file per user or will be more practical to use json ?
For the time being tried to save info per user to separate .txt file:
$rules = get-inboxrule -Mailbox "SomeUser"
$currentrules = @()
for ($i=0;$i -lt $rules.Length; $i++){
$currentrules = $rules[$i].Identity
$rules[$i].Identity | Out-File -Append C:\Temp\%someuser%-Identity.txt
}
$oldrules = @()
$oldrules = get-content C:\Temp\%someuser%-Identity.txt
That will gives a lot of separate files.
Is there better solution to store all this info in one file, e.g. json?
Yes, you can save your data in a single JSON file, by building up a dictionary of entries whose keys are the user names and whose values are the associated rule identities, using code such as the following (untested; could be made more efficient by avoiding +=
for "growing" an array):
$dict = [ordered] @{}
Get-Mailbox |
Get-InboxRule |
ForEach-Object -Process {
$dict[($_.Identity -split '\\')[0]] += @([string] $_.Identity)
} -End {
$dict # Output
} |
ConvertTo-Json |
Set-Content -Encoding utf8 C:\temp\AllRuleIdentities.json
However, if you're running Windows PowerShell (the legacy, ships-with-Windows, Windows-only edition of PowerShell whose latest and last version is 5.1), you won't be able to read the JSON file back into a dictionary (an ([ordered]
) [hashtable]
) with ConvertFrom-Json
- you'll get a - memory-inefficient - [pscustomobject]
instance instead.
By contrast, in PowerShell (Core) 7 you can obtain a dictionary by passing the -AsHashTable
switch to ConvertFrom-Json
.
An option that works in Windows PowerShell too is to use Export-Clixml
(and later Import-Clixml
to read the file back into a dictionary):
$dict = [ordered] @{}
Get-Mailbox |
Get-InboxRule |
ForEach-Object -Process {
$dict[($_.Identity -split '\\')[0]] += @([string] $_.Identity)
} -End {
$dict # Output
} |
Export-CliXml C:\temp\AllRuleIdentities.clixml
The caveat is that in Windows PowerShell the ordering of the keys of the original dictionary is not preserved in this case when it is read back from the file with Import-CliXml
.
This problem has been fixed in PowerShell (Core) 7.
See GitHub issue #2861 for background information.