Posts RSS Comments RSS 117 Posts and 170 Comments till now

Exchange: Get-Mailbox (Return Info)

So many times I have been on the bus on the way home or somewhere that I did not have an Exchange 2007 server available and I would see a question I knew I could answer if I just had the properties returned from a given Exchange CMDLet. I am finally sick of that and decided I would post the Get-Member info for the most used Exchange CMDLets.

For size reasons I will post each CMDLet on its own entry and put in category
http://bsonposh.com/modules/wordpress/?cat=18

For More Info on Exchange CMDLets see
http://technet.microsoft.com/en-us/library/bb124413(EXCHG.80).aspx

  1.   TypeName: Microsoft.Exchange.Data.Directory.Management.Mailbox
  2.  
  3. Name                                 MemberType Definition
  4. —-                                 ———- ———-
  5. AcceptMessagesOnlyFrom               Property   Microsoft.Exchange.Data.MultiValuedProperty`1[[Microsoft.Exchange.Da
  6. AcceptMessagesOnlyFromDLMembers      Property   Microsoft.Exchange.Data.MultiValuedProperty`1[[Microsoft.Exchange.Da
  7. AddressListMembership                Property   Microsoft.Exchange.Data.MultiValuedProperty`1[[Microsoft.Exchange.Da
  8. Alias                                Property   System.String Alias {get;set;}
  9. AntispamBypassEnabled                Property   System.Boolean AntispamBypassEnabled {get;set;}
  10. CustomAttribute1                     Property   System.String CustomAttribute1 {get;set;}
  11. CustomAttribute10                    Property   System.String CustomAttribute10 {get;set;}
  12. CustomAttribute11                    Property   System.String CustomAttribute11 {get;set;}
  13. CustomAttribute12                    Property   System.String CustomAttribute12 {get;set;}
  14. CustomAttribute13                    Property   System.String CustomAttribute13 {get;set;}
  15. CustomAttribute14                    Property   System.String CustomAttribute14 {get;set;}
  16. CustomAttribute15                    Property   System.String CustomAttribute15 {get;set;}
  17. CustomAttribute2                     Property   System.String CustomAttribute2 {get;set;}
  18. CustomAttribute3                     Property   System.String CustomAttribute3 {get;set;}
  19. CustomAttribute4                     Property   System.String CustomAttribute4 {get;set;}
  20. CustomAttribute5                     Property   System.String CustomAttribute5 {get;set;}
  21. CustomAttribute6                     Property   System.String CustomAttribute6 {get;set;}
  22. CustomAttribute7                     Property   System.String CustomAttribute7 {get;set;}
  23. CustomAttribute8                     Property   System.String CustomAttribute8 {get;set;}
  24. CustomAttribute9                     Property   System.String CustomAttribute9 {get;set;}
  25. Database                             Property   Microsoft.Exchange.Data.Directory.ADObjectId Database {get;}
  26. DeletedItemFlags                     Property   Microsoft.Exchange.Data.Directory.Recipient.DeletedItemRetention Del…
  27. DeliverToMailboxAndForward           Property   System.Boolean DeliverToMailboxAndForward {get;set;}
  28. DisplayName                          Property   System.String DisplayName {get;set;}
  29. DistinguishedName                    Property   System.String DistinguishedName {get;}
  30. DowngradeHighPriorityMessagesEnabled Property   System.Boolean DowngradeHighPriorityMessagesEnabled {get;set;}
  31. EmailAddresses                       Property   Microsoft.Exchange.Data.ProxyAddressCollection EmailAddresses {get;s…
  32. EmailAddressPolicyEnabled            Property   System.Boolean EmailAddressPolicyEnabled {get;set;}
  33. EndDateForRetentionHold              Property   System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Cultu…
  34. ExchangeGuid                         Property   System.Guid ExchangeGuid {get;}
  35. ExchangeSecurityDescriptor           Property   System.Security.AccessControl.RawSecurityDescriptor ExchangeSecurity…
  36. ExchangeUserAccountControl           Property   Microsoft.Exchange.Data.Directory.Recipient.UserAccountControlFlags
  37. ExchangeVersion                      Property   Microsoft.Exchange.Data.ExchangeObjectVersion ExchangeVersion {get;}
  38. Extensions                           Property   Microsoft.Exchange.Data.MultiValuedProperty`1[[System.String, mscorl…
  39. ExternalOofOptions                   Property   Microsoft.Exchange.Data.Directory.Recipient.ExternalOofOptions Exter…
  40. ForwardingAddress                    Property   Microsoft.Exchange.Data.Directory.ADObjectId ForwardingAddress {get;…
  41. GrantSendOnBehalfTo                  Property   Microsoft.Exchange.Data.MultiValuedProperty`1[[Microsoft.Exchange.Da
  42. Guid                                 Property   System.Guid Guid {get;}
  43. HiddenFromAddressListsEnabled        Property   System.Boolean HiddenFromAddressListsEnabled {get;set;}
  44. Identity                             Property   Microsoft.Exchange.Data.ObjectId Identity {get;}
  45. IsLinked                             Property   System.Boolean IsLinked {get;}
  46. IsMailboxEnabled                     Property   System.Boolean IsMailboxEnabled {get;}
  47. IsResource                           Property   System.Boolean IsResource {get;}
  48. IsShared                             Property   System.Boolean IsShared {get;}
  49. IssueWarningQuota                    Property   Microsoft.Exchange.Data.Unlimited`1[[Microsoft.Exchange.Data.ByteQua
  50. IsValid                              Property   System.Boolean IsValid {get;}
  51. Languages                            Property   Microsoft.Exchange.Data.MultiValuedProperty`1[[System.Globalization….
  52. LegacyExchangeDN                     Property   System.String LegacyExchangeDN {get;}
  53. LinkedMasterAccount                  Property   System.String LinkedMasterAccount {get;}
  54. ManagedFolderMailboxPolicy           Property   Microsoft.Exchange.Data.Directory.ADObjectId ManagedFolderMailboxPol…
  55. MaxBlockedSenders                    Property   System.Nullable`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=…
  56. MaxReceiveSize                       Property   Microsoft.Exchange.Data.Unlimited`1[[Microsoft.Exchange.Data.ByteQua
  57. MaxSafeSenders                       Property   System.Nullable`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=…
  58. MaxSendSize                          Property   Microsoft.Exchange.Data.Unlimited`1[[Microsoft.Exchange.Data.ByteQua
  59. Name                                 Property   System.String Name {get;set;}
  60. ObjectCategory                       Property   Microsoft.Exchange.Data.Directory.ADObjectId ObjectCategory {get;}
  61. ObjectClass                          Property   Microsoft.Exchange.Data.MultiValuedProperty`1[[System.String, mscorl…
  62. Office                               Property   System.String Office {get;set;}
  63. OfflineAddressBook                   Property   Microsoft.Exchange.Data.Directory.ADObjectId OfflineAddressBook {get…
  64. OrganizationalUnit                   Property   System.String OrganizationalUnit {get;}
  65. OriginatingServer                    Property   System.String OriginatingServer {get;}
  66. PoliciesExcluded                     Property   Microsoft.Exchange.Data.MultiValuedProperty`1[[System.String, mscorl…
  67. PoliciesIncluded                     Property   Microsoft.Exchange.Data.MultiValuedProperty`1[[System.String, mscorl…
  68. PrimarySmtpAddress                   Property   Microsoft.Exchange.Data.SmtpAddress PrimarySmtpAddress {get;set;}
  69. ProhibitSendQuota                    Property   Microsoft.Exchange.Data.Unlimited`1[[Microsoft.Exchange.Data.ByteQua
  70. ProhibitSendReceiveQuota             Property   Microsoft.Exchange.Data.Unlimited`1[[Microsoft.Exchange.Data.ByteQua
  71. ProtocolSettings                     Property   Microsoft.Exchange.Data.MultiValuedProperty`1[[System.String, mscorl…
  72. RecipientLimits                      Property   Microsoft.Exchange.Data.Unlimited`1[[System.Int32, mscorlib, Version…
  73. RecipientType                        Property   Microsoft.Exchange.Data.Directory.Recipient.RecipientType RecipientT…
  74. RecipientTypeDetails                 Property   Microsoft.Exchange.Data.Directory.Recipient.RecipientTypeDetails Rec…
  75. RejectMessagesFrom                   Property   Microsoft.Exchange.Data.MultiValuedProperty`1[[Microsoft.Exchange.Da
  76. RejectMessagesFromDLMembers          Property   Microsoft.Exchange.Data.MultiValuedProperty`1[[Microsoft.Exchange.Da
  77. RequireSenderAuthenticationEnabled   Property   System.Boolean RequireSenderAuthenticationEnabled {get;set;}
  78. ResourceCapacity                     Property   System.Nullable`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=…
  79. ResourceCustom                       Property   Microsoft.Exchange.Data.MultiValuedProperty`1[[System.String, mscorl…
  80. ResourceType                         Property   System.Nullable`1[[Microsoft.Exchange.Data.Directory.Recipient.Excha
  81. RetainDeletedItemsFor                Property   Microsoft.Exchange.Data.EnhancedTimeSpan RetainDeletedItemsFor {get;…
  82. RetainDeletedItemsUntilBackup        Property   System.Boolean RetainDeletedItemsUntilBackup {get;set;}
  83. RetentionHoldEnabled                 Property   System.Boolean RetentionHoldEnabled {get;set;}
  84. RulesQuota                           Property   Microsoft.Exchange.Data.ByteQuantifiedSize RulesQuota {get;set;}
  85. SamAccountName                       Property   System.String SamAccountName {get;set;}
  86. SCLDeleteEnabled                     Property   System.Nullable`1[[System.Boolean, mscorlib, Version=2.0.0.0, Cultur…
  87. SCLDeleteThreshold                   Property   System.Nullable`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=…
  88. SCLJunkEnabled                       Property   System.Nullable`1[[System.Boolean, mscorlib, Version=2.0.0.0, Cultur…
  89. SCLJunkThreshold                     Property   System.Nullable`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=…
  90. SCLQuarantineEnabled                 Property   System.Nullable`1[[System.Boolean, mscorlib, Version=2.0.0.0, Cultur…
  91. SCLQuarantineThreshold               Property   System.Nullable`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=…
  92. SCLRejectEnabled                     Property   System.Nullable`1[[System.Boolean, mscorlib, Version=2.0.0.0, Cultur…
  93. SCLRejectThreshold                   Property   System.Nullable`1[[System.Int32, mscorlib, Version=2.0.0.0, Culture=…
  94. ServerLegacyDN                       Property   System.String ServerLegacyDN {get;}
  95. ServerName                           Property   System.String ServerName {get;}
  96. SimpleDisplayName                    Property   System.String SimpleDisplayName {get;set;}
  97. StartDateForRetentionHold            Property   System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Cultu…
  98. UMDtmfMap                            Property   Microsoft.Exchange.Data.MultiValuedProperty`1[[System.String, mscorl…
  99. UMEnabled                            Property   System.Boolean UMEnabled {get;}
  100. UseDatabaseQuotaDefaults             Property   System.Nullable`1[[System.Boolean, mscorlib, Version=2.0.0.0, Cultur…
  101. UseDatabaseRetentionDefaults         Property   System.Boolean UseDatabaseRetentionDefaults {get;set;}
  102. UserAccountControl                   Property   Microsoft.Exchange.Data.Directory.Recipient.UserAccountControlFlags
  103. UserPrincipalName                    Property   System.String UserPrincipalName {get;set;}
  104. WhenChanged                          Property   System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Cultu…
  105. WhenCreated                          Property   System.Nullable`1[[System.DateTime, mscorlib, Version=2.0.0.0, Cultu…
  106. WindowsEmailAddress                  Property   Microsoft.Exchange.Data.SmtpAddress WindowsEmailAddress {get;set;}

I dont normally do this, but this is a big one.

Win 2008 and Vista SP1 RTM
http://blogs.technet.com/windowsserver/archive/2008/02/04/windows-server-2008-rtm.aspx

Or at least it appears so… MS hasnt made if official yet.

Converting Secure String

I recently heard a question about ConvertTO-SecureString and ConvertFrom-SecureString.

These CMDLets may be a little confusing so let’s talk a little about them.

Before you read the rest, it is key to understand what a Secure String actually is.

A Secure String is simple text that is encrypted in memory. This lets you store passwords or other secure data in memory without having to concern yourself with someone snooping your session or dumping your memory contents to get your data.

More Info Here
http://msdn2.microsoft.com/en-us/library/system.security.securestring.aspx

ConvertTo-SecureString: http://technet.microsoft.com/en-us/library/bb978707.aspx
I think this where it gets a little confusing for people. ConvertTo is meant to take an encrypted string and store it as a Secure String. Specificially for the output from ConvertFrom-SecureString. It will allow you use -asPlainText w/ -Force if you just want to convert a piece of text to Secure String.

ConvertFrom-SecureString: http://technet.microsoft.com/en-us/library/bb978629.aspx
This is used to convert a Secure String to text. It is import to note…. this is NOT the original text but the string representation of the encryption. This is a great tool for exporting the Secure String to a file in an encrypted form.

One other note before I show the code. By default (unless you provide a key) it uses Windows Data Protection API (DPAPI). This is VERY important. This process it is fairly secure, but can only decrypted by you on that specific machine. On the flip side… using a Key is not near as secure and some would argue security by obscurity.

Now… lets look at what we have… nothing magic here. We have three functions Export-EncryptedText. Import-EncryptedText, and Get-EncryptedText.
Export-EncryptedText: This gets a Secure String and exports to a file
Import-EncryptedText: This imports a Secure String Text from a file and returns a Secure String
Get-EncryptedText: This converts a Secure String into the orginal Text

We use “Read-Host -AsSecureString” to create convert our text to a secure string.

  1. function Export-EncryptedText{
  2.     param($text,$file,$key)
  3.     if($key){ConvertFrom-SecureString -SecureString $text -key $key | out-file $file}
  4.     else{ConvertFrom-SecureString -SecureString $text | out-file $file}
  5. }
  6. function Import-EncryptedText{
  7.     Param($file,$key)
  8.     $textFromFile = Get-Content $file
  9.     if($key){ConvertTO-SecureString $TextFromFile -key $key}
  10.     else{ConvertTO-SecureString $TextFromFile}
  11. }
  12. function Get-EncryptedText($text) {
  13.     $Ptr = [System.Runtime.InteropServices.Marshal ]::SecureStringToCoTaskMemUnicode($text)
  14.     $result = [System.Runtime.InteropServices.Marshal]::PtrToStringUni($Ptr)
  15.     [System.Runtime.InteropServices.Marshal]::ZeroFreeCoTaskMemUnicode($Ptr)
  16.     $result
  17. }
  18.  
  19. # Example Use
  20. $dataToStore = Read-Host -AsSecureString
  21. "My String To Encrypt Here"
  22.  
  23. # Key… needs to be a 16, 24, or 32 byte array
  24. $key = (200..231)
  25.  
  26. # Use this to put the password in a file
  27. Export-EncryptedText -text $dataToStore -file c:\data\testfile.secure -key $key
  28.  
  29. # To get the password back you do this
  30. $myText = Import-EncryptedText c:\data\testfile.secure -key $key
  31.  
  32. # To see the text use Get-SecurePass
  33. Get-EncryptedText $myText

The Power of -f. The Format Operator

This is from a NG post discussing the -f Operator… I thought it was a pretty good description. Compliments to Kiron.

Q: What is the -f operator

A: PowerShell’s Format Operator ‘-f’ is equivalent to .Net’s Composite
Formatting. The syntax is:
{index[,alignment][:formatString]} -f listOfValues

Composite Formatting
http://msdn2.microsoft.com/en-us/library/txafckwd(vs.71).aspx

Quoting from about_operator:
Format Operator “-f”
The format operator provides support for formatting strings via the .NET
string object format method. On the left hand side of the operator is the
format string and on the right hand of the operator is the collection of
objects to be formatted.
The following example shows some of the capabilities of the format operator.
PS> “{0} {1,-10} {2:N}” -f 1,”hello”,[math]::pi
1 hello 3.14

Some samples:

  1. # the ‘|’ is for demonstrating the alignment
  2. "{0:(###) ###-####}" -f 2224445555 # phone number
  3. "{0:hh:mm:ss tt}" -f (get-date) # time, 12 hour format
  4. "{0:HH:mm:ss}" -f (get-date) # time, 24 hour format
  5. "{0:p4}" -f (1/3) # percent with four decimal places
  6. "{0:c2}" -f (1724.87 * 12) # currency with two decimal places
  7. "|{0,22:c2}|" -f (1724.87 * 12) # right aligned currency with two decimal places
  8. "|{0,-22:n2}|" -f (13/57) # left aligned number with two decimal places
  9. "{0:MM dd yy}" -f (get-date) # date, custom short format
  10. "{0:MMMM yyyy}" -f (get-date) # date, ‘month year’ format
  11. 0..15 | % {"{0:0##}" -f $_} # filled number format
  12. 0..15 | % {"|{0,33}|" -f "Number $_"} # right aligned string
  13. 0..15 | % {"|{0,-33}|" -f "Number $_"} # left aligned string
  14. 0..15 | % {"|{0,33}|  |{0,-33}|" -f "Number $_"} # right & left aligned string

Suggested Reading.

Standard Numeric Format Strings
http://msdn2.microsoft.com/en-us/library/dwhawy9k.aspx

Custom Numeric Format Strings
http://msdn2.microsoft.com/en-us/library/0c899ak8.aspx

Standard DateTime Format Strings
http://msdn2.microsoft.com/en-us/library/az4se3k1.aspx

Custom DateTime Format Strings
http://msdn2.microsoft.com/en-us/library/8kb3ddd4.aspx

Enumeration Format Strings
http://msdn2.microsoft.com/en-us/library/c3s1ez6e.aspx

Check out this blog from the PowerShell Team
http://blogs.msdn.com/powershell/archive/2006/06/16/634575.aspx

C# to PowerShell Translation Thought Process

A gentleman on the powershell news group the other day was asking about executing SQL stored procedures and I provided him with example that I had posted earlier in my blog (Click Here) While I’m not sure my answer was exactly what he was looking for he was a little curious as to how I went about translating the original C# code. To be clear I am not a coder nor do I truly know C#, but I know enough to translate. Anyway, I decided this would be a good idea for a post

So… Here we GO!

First… I used this as the C# example
http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson07.aspx

I will show you my thought process by section I will include my comments and after I will post Both code Sections

This was fairly simple. In C# you have the ability to take namespace shortcuts by using ‘using ;’ In PowerShell we dont as of yet have that ability so I had to figure out what class SqlConnection was. A MSDN query returned System.Data.SqlClient.SqlConnection. The resulting PowerShell code is

The C# Code:

  1. // Setup
  2. conn = new SqlConnection("Server=(local);DataBase=Northwind;Integrated Security=SSPI");
  3. conn.Open();

The Powershell Code:

  1. $srv = "srv1"
  2. $db = "Northwind"
  3. $conn = new-Object System.Data.SqlClient.SqlConnection("Server=$srv;DataBase=$db;IntegratedSecurity=SSPI")
  4. $conn.Open() | out-null # The out-null is because the method returns a value and I dont want that output

Again… I had to find out what SqlCommand was referencing so… back to MSDN… System.Data.SqlClient.SqlCommand. BTW… I think I should take time now to tell you it is a REALLY GOOD idea to get use to the idea of constructors (how the object should be created) and how to use MSDN to determine the correct way to create an instance of the class/object. It really helps to know what a class is expecting. In this example its good to know the constructor is wanting a string of the SP and A connection OBJECT to use.

The C# Code:

  1. // 1.  create a command object identifying
  2. //     the stored procedure
  3. SqlCommand cmd  = new SqlCommand("CustOrderHist", conn);

Here is the PowerShell Code:

  1. $cmd = new-Object System.Data.SqlClient.SqlCommand("CustOrderHist", $conn)

Here was the tricky part (at least sorta.) From the C# code its not clear if the CommandType.StoredProcedure is a property and it turns out its not. It is an enumeration. It took me a few clicks to figure it out. The first clue was when looking for CommandType… I got an enum and it turns out the valid options was StoredProcedure, TableDirect, or Text (MSDN LINK) Clearly this was an enum, but I was a little unsure how do to enums in powershell. I found this blog by /\/\0\/\/ that helped a lot (/\/\o\/\/ Link)

The C# Code:

  1. // 2. set the command object so it knows
  2. //    to execute a stored procedure
  3. cmd.CommandType = CommandType.StoredProcedure;

I ended up with this Powershell Line:

  1. $cmd.CommandType = [System.Data.CommandType]‘StoredProcedure’

This was fairly simple as well… Just had to drop the new sqlparameter because strongly typing was not required. Again the out-null was because the method returns data I did not want as well as set the parameters.

The C# Code:

  1. // 3. add parameter to command, which
  2. //    will be passed to the stored procedure
  3. cmd.Parameters.Add(new SqlParameter("@CustomerID", custId));

The PowerShell Code:

  1. $cmd.Parameters.Add("@CustomerID","ANATR") | out-Null

These two parts are really just the excution of the the previous code. I think the only difference is the way PowerShell Writes output

The C# Code:

  1. // execute the command
  2. rdr = cmd.ExecuteReader();
  3.  
  4. // iterate through results, printing each to console
  5. while (rdr.Read())
  6. {
  7.  Console.WriteLine(
  8.  "Product: {0,-35} Total: {1,2}",
  9.  rdr["ProductName"],
  10.  rdr["Total"]);
  11. }

The Powershell Code:

  1. $rdr = $cmd.ExecuteReader()
  2. While($rdr.Read()){
  3.     Write-Host "Product Name: " $rdr[‘ProductName’]
  4.     Write-Host "Total: " $rdr[‘Total’]
  5. }

Here is the Complete PowerShell Code.

  1. $srv = "srv1"
  2. $db = "Northwind"
  3. $conn = new-Object System.Data.SqlClient.SqlConnection("Server=$srv1;DataBase=$db;Integrated Security=SSPI")
  4. $conn.Open() | out-null
  5. $cmd = new-Object System.Data.SqlClient.SqlCommand("CustOrderHist", $conn)
  6. $cmd.CommandType = [System.Data.CommandType]‘StoredProcedure’
  7. $cmd.Parameters.Add("@CustomerID","ANATR") | out-Null
  8. $rdr = $cmd.ExecuteReader()
  9. While($rdr.Read()){
  10.     Write-Host "Product Name: " $rdr[‘ProductName’]
  11.     Write-Host "Total: " $rdr[‘Total’]
  12. }
  13. $conn.Close()
  14. $rdr.Close()