rubypowershell-2.0winrmexchange-management-shell

Run Exchange Powershell commands from Linux using Ruby/WinRM


I am attempting to run the enable-mailbox command for existing users in Active Directory from a ruby script. I'm using this winrm gem. So far I have been able to connect to the exchange server using winrm and kerberos authentication. I can run an exchange management shell from powershell. From there I can execute exchange commands.

However, when I try to run enable-mailbox I get the following error:

Active Directory operation failed on . The supplied credential for 'domain\account' is invalid.

The 'operation failed on .' is verbatim. There is no text in the space where you would think there should be. The domain\account is the same one I'm using to successfully connect with winrm via kerberos.

Here's my simple code:

endpoint = 'http://server:5985/wsman'
krb5_realm = 'myrealm'
winrm = WinRM::WinRMWebService.new(endpoint, :kerberos, :realm => krb5_realm)

#exch_cmd = "Get-Help Enable-Mailbox" NOTE THAT THIS COMMAND WORKS FINE
exch_cmd = "Enable-Mailbox -Identity:'user DN' -Alias:'username' -Database:'mailbox'"
command = "powershell -psconsolefile \"C:\\Program Files\\Microsoft\\Exchange Server\\V15\\bin\\exshell.psc1\" -command \". "+exch_cmd+"\""

winrm.cmd(command) do |stdout, stderr|
  STDOUT.print stdout
  STDERR.print stderr
end

Thanks for any help!


Solution

  • We managed to get it to work. I had to first connect to a 'management' server to initiate the powershell command.

    endpoint = 'http://YOURSERVER:5985/wsman' krb5_realm = 'YOURREALM' winrm = WinRM::WinRMWebService.new(endpoint, :kerberos, :realm => krb5_realm)

    Then I had to modify the exchange command to this:

    exch_cmd = "Enable-Mailbox -Identity:'DOMAIN/OU/#{fullname}' -Alias:'#{username}' -Database:'#{MailboxDB}'"

    command = "powershell -NonInteractive -WindowStyle Hidden -command \" $username = '#{account}'; $password = ConvertTo-SecureString '#{password}' -asplaintext -force; $UserCredential = New-Object -TypeName System.Management.Automation.PSCredential -argumentlist $username,$password; $Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri #{server} -Authentication Kerberos -Credential $UserCredential; Invoke-Command -Session $Session {#{exch_cmd}}\""

    On the Management and Exchange servers, the service account needs to be in the Remote Management Group. You also need to update the SDDL according to this guide: http://www.sevecek.com/Lists/Posts/Post.aspx?ID=280 Depending on your server config this will be different.