Exportar mailbox para PST


Montei um script de powershell que cria uma tela para facilitar a exportação de caixas de email do exchange 2010 para PST.

export_pst3

Ele é bem simples,,, Antes de carregar essa tela, ele vai tentar localizar seu servidor de Exchange, vai baixar o módulo EMS para sua maquina e ai ele libera o acesso a tela acima… (o processo de baixar o EMS pode demorar um pouco)

Para localizar alguma caixa utilize o campo “Localizar” e não esqueça de colocar um * (asterisco) e depois clique em “Localizar”

Na Grid abaixo ele vai mostrar todos os resultados para sua busca, selecione a caixa que você quer exportar.

No campo salvar você pode:

  • Digitar o local e o nome do arquivo para ele exportar a caixa, não esqueça de colocar o nome do arquivo e o .PST
  • Clicar em “…” e uma tela do “Salvar como” será exibida, escolha o local para salvar o arquivo e nesse caso você não precisa colocar o .PST ele mesmo adiciona.

Clique em “Exportar”.

Detalhe muito importante:

  • O processo de exportação é assíncrono, isso quer dizer que: ele não ocorre durante a execução do comando de exportação, ele vai para uma fila de tratamento secundária do Exchange e depois vai ser executado. por isso ainda não conseguir colocar um status. Se você quiser saber o status da exportação da caixa pode utilizar o powershell e digitar:
[PS] C:\Get-MailboxExportRequest | Get-MailboxExportRequestStatistics
  • O local para salvar PRECISA ser um compartilhamento da rede, pode ser endereço de loop-back, não importa, mas tem que ser endereço de rede… ainda estou trabalhando nisso

Para essa versão é isso,,, o download está no Skydrive.

O código ficou assim:

#Generated Form Function
function GenerateForm {
########################################################################
# Generated On: 10/05/2012 12:16
# Generated By: Ricardo Leka
# Site: http://leka.com.br
# Twitter: @bigleka
# Versao: 0.5
########################################################################

#region Import the Assemblies
[reflection.assembly]::loadwithpartialname("System.Drawing") | Out-Null
[reflection.assembly]::loadwithpartialname("System.Windows.Forms") | Out-Null
#endregion

    #----------------------------------------------
    # User Generated Script
    #----------------------------------------------
function Get-ExchangeServerInSite {
        $ADSite = [System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]
        $siteDN = $ADSite::GetComputerSite().GetDirectoryEntry().distinguishedName
        $configNC=([ADSI]"LDAP://RootDse").configurationNamingContext
        $search = new-object DirectoryServices.DirectorySearcher([ADSI]"LDAP://$configNC")
        $objectClass = "objectClass=msExchExchangeServer"
        $version = "versionNumber>=1937801568"
        $site = "msExchServerSite=$siteDN"
        $search.Filter = "(&($objectClass)($version)($site))"
        $search.PageSize=1000
        [void] $search.PropertiesToLoad.Add("name")
        [void] $search.PropertiesToLoad.Add("msexchcurrentserverroles")
        [void] $search.PropertiesToLoad.Add("networkaddress")
        $search.FindAll() | %{
            New-Object PSObject -Property @{
                Name = $_.Properties.name[0]
                FQDN = $_.Properties.networkaddress |
                    %{if ($_ -match "ncacn_ip_tcp") {$_.split(":")[1]}}
                Roles = $_.Properties.msexchcurrentserverroles[0]
            }
        }
    }
    
    function Import-EMS {
        $servers = New-Object System.Collections.ArrayList
        Get-ExchangeServerInSite | %{ [void]$servers.Add(($_.fqdn)) }
        
        #select a random server from the current site
        if($servers.count -gt 1) {
            $random = Get-Random -Minimum 0 -Maximum $servers.count
            $fqdn = $servers[$random]
        }
        else {
            $fqdn = $servers[0]
        }
        
        try {
            $session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "http://$fqdn/PowerShell/" -Authentication Kerberos
            Import-PSSession $session        
        }
        catch {
            [System.Windows.Forms.MessageBox]::Show(
                $_.Exception.Message,
                "Error",
                [System.Windows.Forms.MessageBoxButtons]::OK,
                [System.Windows.Forms.MessageBoxIcon]::Error
                )
        }
    }

$FormEvent_Load={
    #TODO: Place custom script here
        if(!(get-command get-mailbox -EA 0)) {
            if(Get-PSSnapin -Registered "Microsoft.Exchange.Management.PowerShell.E2010" -EA 0) {
                Add-PSSnapin "Microsoft.Exchange.Management.PowerShell.E2010"
            }
            else {
                $message = [System.Windows.Forms.MessageBox]::Show(
                    "Vou importar o EMS do Exchange. Espere... isso pode demorar um pouco.",
                    "Conectando ao Exchange",
                    [System.Windows.Forms.MessageBoxButtons]::OK,
                    [System.Windows.Forms.MessageBoxIcon]::Information
                    )            
                Import-EMS
            }
        }
    }

#region Generated Form Objects
$form1 = New-Object System.Windows.Forms.Form
$groupBox2 = New-Object System.Windows.Forms.GroupBox
$statusbar1 = New-Object System.Windows.Forms.StatusBar
$button3 = New-Object System.Windows.Forms.Button
$button2 = New-Object System.Windows.Forms.Button
$textBox2 = New-Object System.Windows.Forms.TextBox
$groupBox1 = New-Object System.Windows.Forms.GroupBox
$textBox1 = New-Object System.Windows.Forms.TextBox
$button1 = New-Object System.Windows.Forms.Button
$dataGridView1 = New-Object System.Windows.Forms.DataGridView
$saveFileDialog1 = New-Object System.Windows.Forms.SaveFileDialog
$InitialFormWindowState = New-Object System.Windows.Forms.FormWindowState
#endregion Generated Form Objects

#----------------------------------------------
#Generated Event Script Blocks
#----------------------------------------------
#Provide Custom Code for events specified in PrimalForms.

$button3_OnClick= 
{
#TODO: Place custom script here

if($textbox2.Text -eq "") {
            [System.Windows.Forms.MessageBox]::Show(
                "Voce precisa selecionar onde salvar...",
                "Error",
                [System.Windows.Forms.MessageBoxButtons]::OK,
                [System.Windows.Forms.MessageBoxIcon]::Error
                )
        }
        else {
            try {
                New-MailboxExportRequest -Mailbox $dataGridView1.SelectedCells[0].Value.ToString() -FilePath $textbox2.Text -ErrorAction Stop
                
                [System.Windows.Forms.MessageBox]::Show(
                    "A exportacao foi colocada em fila com sucesso.",
                    "exportacao",
                    [System.Windows.Forms.MessageBoxButtons]::OK,
                    [System.Windows.Forms.MessageBoxIcon]::Information
                    )
                $textbox2.Text = ""
            }
            catch {
            [System.Windows.Forms.MessageBox]::Show(
                $_.Exception.Message,
                "Error",
                [System.Windows.Forms.MessageBoxButtons]::OK,
                [System.Windows.Forms.MessageBoxIcon]::Error
                )
            }    
        }

}

$button2_OnClick= 
{
#TODO: Place custom script here

try {
            if($saveFileDialog1.ShowDialog() -eq [System.Windows.Forms.DialogResult]::OK) {
                $textbox2.Text = $saveFileDialog1.FileName.ToString()
                                
            }    
        }
        catch {
            [System.Windows.Forms.MessageBox]::Show(
                $_.Exception.Message,
                "Error",
                [System.Windows.Forms.MessageBoxButtons]::OK,
                [System.Windows.Forms.MessageBoxIcon]::Error
                )            
        }

}

$handler_saveFileDialog1_FileOk= 
{
#TODO: Place custom script here

}

$handler_button1_Click= 
{
#TODO: Place custom script here
$textbox2.Text = ""
$statusbar1.Text = "Status: Procurando..."
try {
            $mailboxes = New-Object System.Collections.ArrayList
            if(!($textbox1.Text)) {
                $mailboxInfo = Get-Mailbox -resultsize unlimited -ErrorAction Stop | select Name,Alias,PrimarySMTPAddress,DistinguishedName
            }
            else {
                $mailboxInfo = Get-Mailbox $textbox1.Text -resultsize unlimited -ErrorAction Stop | select Name,Alias,PrimarySMTPAddress,DistinguishedName
            }
            if($mailboxInfo.count) {
                $mailboxes.AddRange($mailboxInfo)
            }
            else {
                $mailboxes.Add($mailboxInfo)
            }
            
            $datagridview1.DataSource = $mailboxes
            $form1.refresh()
            $statusbar1.Text = ""
            }
        catch {
            [System.Windows.Forms.MessageBox]::Show(
                $_.Exception.Message,
                "Erro",
                [System.Windows.Forms.MessageBoxButtons]::OK,
                [System.Windows.Forms.MessageBoxIcon]::Error
                )
        $statusbar1.Text = ""
        }
    
}

$OnLoadForm_StateCorrection=
{#Correct the initial state of the form to prevent the .Net maximized form issue
    $form1.WindowState = $InitialFormWindowState
}

#----------------------------------------------
#region Generated Form Code
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 325
$System_Drawing_Size.Width = 631
$form1.ClientSize = $System_Drawing_Size
$form1.DataBindings.DefaultDataSourceUpdateMode = 0
$form1.FormBorderStyle = 1
$form1.Name = "form1"
$form1.Text = "Exportar para PST"

# statusbar1
    
    $statusbar1.Size = New-Object System.Drawing.Size(551,22)
    $statusbar1.TabIndex = 3
    $statusbar1.Location = New-Object System.Drawing.Point(0,364)
    $statusbar1.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation 
    $statusbar1.Name = "statusbar1"
    

$groupBox2.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 24
$System_Drawing_Point.Y = 237
$groupBox2.Location = $System_Drawing_Point
$groupBox2.Name = "groupBox2"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 49
$System_Drawing_Size.Width = 577
$groupBox2.Size = $System_Drawing_Size
$groupBox2.TabIndex = 4
$groupBox2.TabStop = $False
$groupBox2.Text = "Salvar"

$form1.Controls.Add($statusbar1)
$form1.Controls.Add($groupBox2)

$button3.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 496
$System_Drawing_Point.Y = 20
$button3.Location = $System_Drawing_Point
$button3.Name = "button3"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 75
$button3.Size = $System_Drawing_Size
$button3.TabIndex = 2
$button3.Text = "Exportar"
$button3.UseVisualStyleBackColor = $True
$button3.add_Click($button3_OnClick)

$groupBox2.Controls.Add($button3)


$button2.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 319
$System_Drawing_Point.Y = 19
$button2.Location = $System_Drawing_Point
$button2.Name = "button2"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 33
$button2.Size = $System_Drawing_Size
$button2.TabIndex = 1
$button2.Text = "..."
$button2.UseVisualStyleBackColor = $True
$button2.add_Click($button2_OnClick)

$groupBox2.Controls.Add($button2)

$textBox2.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 7
$System_Drawing_Point.Y = 20
$textBox2.Location = $System_Drawing_Point
$textBox2.Name = "textBox2"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 306
$textBox2.Size = $System_Drawing_Size
$textBox2.TabIndex = 0

$groupBox2.Controls.Add($textBox2)



$groupBox1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 24
$System_Drawing_Point.Y = 13
$groupBox1.Location = $System_Drawing_Point
$groupBox1.Name = "groupBox2"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 218
$System_Drawing_Size.Width = 577
$groupBox1.Size = $System_Drawing_Size
$groupBox1.TabIndex = 3
$groupBox1.TabStop = $False
$groupBox1.Text = "Localizar"

$form1.Controls.Add($groupBox1)
$textBox1.DataBindings.DefaultDataSourceUpdateMode = 0
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 7
$System_Drawing_Point.Y = 20
$textBox1.Location = $System_Drawing_Point
$textBox1.Name = "textBox1"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 20
$System_Drawing_Size.Width = 306
$textBox1.Size = $System_Drawing_Size
$textBox1.TabIndex = 2

$groupBox1.Controls.Add($textBox1)


$button1.DataBindings.DefaultDataSourceUpdateMode = 0

$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 463
$System_Drawing_Point.Y = 20
$button1.Location = $System_Drawing_Point
$button1.Name = "button1"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 75
$button1.Size = $System_Drawing_Size
$button1.TabIndex = 1
$button1.Text = "Localizar"
$button1.UseVisualStyleBackColor = $True
$button1.add_Click($handler_button1_Click)

$groupBox1.Controls.Add($button1)

$dataGridView1.DataBindings.DefaultDataSourceUpdateMode = 0
$datagridview1.ShowEditingIcon = $False
$datagridview1.AllowUserToAddRows = $False
$datagridview1.AutoSizeColumnsMode = [System.Windows.Forms.DataGridViewAutoSizeColumnsMode]::Fill
$datagridview1.ColumnHeadersDefaultCellStyle = $System_Windows_Forms_DataGridViewCellStyle_22
$datagridview1.Anchor = [System.Windows.Forms.AnchorStyles]::Top -bor [System.Windows.Forms.AnchorStyles]::Bottom -bor [System.Windows.Forms.AnchorStyles]::Left -bor [System.Windows.Forms.AnchorStyles]::Right 
$datagridview1.SelectionMode = [System.Windows.Forms.DataGridViewSelectionMode]::FullRowSelect 
$datagridview1.BackgroundColor = [System.Drawing.Color]::FromArgb(255,255,255,255)
$datagridview1.DataBindings.DefaultDataSourceUpdateMode = [System.Windows.Forms.DataSourceUpdateMode]::OnValidation
$System_Windows_Forms_DataGridViewCellStyle_23 = New-Object System.Windows.Forms.DataGridViewCellStyle
    $System_Windows_Forms_DataGridViewCellStyle_23.Alignment = [System.Windows.Forms.DataGridViewContentAlignment]::MiddleLeft 
    $System_Windows_Forms_DataGridViewCellStyle_23.BackColor = [System.Drawing.Color]::FromArgb(255,212,208,200)
    $System_Windows_Forms_DataGridViewCellStyle_23.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",8.25,0,3,1)
    $System_Windows_Forms_DataGridViewCellStyle_23.ForeColor = [System.Drawing.Color]::FromArgb(255,0,0,0)
    $System_Windows_Forms_DataGridViewCellStyle_23.SelectionBackColor = [System.Drawing.Color]::FromArgb(255,10,36,106)
    $System_Windows_Forms_DataGridViewCellStyle_23.SelectionForeColor = [System.Drawing.Color]::FromArgb(255,255,255,255)
    $System_Windows_Forms_DataGridViewCellStyle_23.WrapMode = [System.Windows.Forms.DataGridViewTriState]::True 
    $datagridview1.RowHeadersDefaultCellStyle = $System_Windows_Forms_DataGridViewCellStyle_23
    $System_Windows_Forms_DataGridViewCellStyle_24 = New-Object System.Windows.Forms.DataGridViewCellStyle
    $System_Windows_Forms_DataGridViewCellStyle_24.Alignment = [System.Windows.Forms.DataGridViewContentAlignment]::MiddleLeft 
    $System_Windows_Forms_DataGridViewCellStyle_24.BackColor = [System.Drawing.Color]::FromArgb(255,255,255,255)
    $System_Windows_Forms_DataGridViewCellStyle_24.Font = New-Object System.Drawing.Font("Microsoft Sans Serif",8.25,0,3,1)
    $System_Windows_Forms_DataGridViewCellStyle_24.ForeColor = [System.Drawing.Color]::FromArgb(255,0,0,0)
    $System_Windows_Forms_DataGridViewCellStyle_24.SelectionBackColor = [System.Drawing.Color]::FromArgb(255,10,36,106)
    $System_Windows_Forms_DataGridViewCellStyle_24.SelectionForeColor = [System.Drawing.Color]::FromArgb(255,255,255,255)
    $System_Windows_Forms_DataGridViewCellStyle_24.WrapMode = [System.Windows.Forms.DataGridViewTriState]::False

$datagridview1.DefaultCellStyle = $System_Windows_Forms_DataGridViewCellStyle_24
    $datagridview1.Location = New-Object System.Drawing.Point(16,69)
    $datagridview1.AllowUserToResizeRows = $False
    $datagridview1.RowHeadersVisible = $False
#    $datagridview1.TabIndex = 2
    $datagridview1.ReadOnly = $True
    $datagridview1.AllowUserToDeleteRows = $False
    $datagridview1.MultiSelect = $False
    $datagridview1.ColumnHeadersHeightSizeMode = [System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode]::AutoSize
    
$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 6
$System_Drawing_Point.Y = 49
$dataGridView1.Location = $System_Drawing_Point
$dataGridView1.Name = "dataGridView1"
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 163
$System_Drawing_Size.Width = 565
$dataGridView1.Size = $System_Drawing_Size
$dataGridView1.TabIndex = 0

$groupBox1.Controls.Add($dataGridView1)


$System_Drawing_Point = New-Object System.Drawing.Point
$System_Drawing_Point.X = 24
$System_Drawing_Point.Y = 292
$System_Drawing_Size = New-Object System.Drawing.Size
$System_Drawing_Size.Height = 23
$System_Drawing_Size.Width = 577

$savefiledialog1.Filter = "Arquivo PST (*.pst)|*.pst"
$saveFileDialog1.DefaultExt = "PST"
$saveFileDialog1.InitialDirectory = "c:\"
$saveFileDialog1.ShowHelp = $True
$saveFileDialog1.add_FileOk($handler_saveFileDialog1_FileOk)

#endregion Generated Form Code

#Save the initial state of the form
$form1.add_Load($FormEvent_Load)
$InitialFormWindowState = $form1.WindowState
#Init the OnLoad event to correct the initial state of the form
$form1.add_Load($OnLoadForm_StateCorrection)
#Show the Form
$form1.ShowDialog()| Out-Null

} #End Function

#Call the Function
GenerateForm

Para a próxima versão:

  • estou tentando alterar a grid para exibir o tamanho da caixa e a quantidade de itens
  • habilitar a opção de múltipla seleção da grid para exportar mais de uma caixa
  • colocar em algum lugar um status da exportação

Lync – Aparecer Offline


Quem usa software de mensagem instantânea sabe que tem a opção de aparecer invisível,,, e isso em muitos casos é bem útil…

Por padrão o Microsoft Lync não mostra essa opção, mas ela pode ser habilitada pelo administrador do Lync usando o comando de powershell:

Get-CSClientPolicy | Set-CSClientPolicy -EnableAppearOffline:$true

Isso tudo é uma linha só,,,

O usuário vai ter que desconectar e reconectar, ai a opção vai aparecer assim:

offline

Ai entra uma outra questão, por que, no ambiente corporativo, você não quer aparecer online ou com outro status para as pessoas?

Não instale o VS2010 SP1 se você usa o Intellisense no SSMS


Se você gosta e usa o Intellisense (aquele opção que ajuda a preencher alguns itens quando você está digitando alguma query) no SSMS NÃO instale o Visual Studio 2010 SP1…

Isso acontece com o SSMS do 2008 R2, de acordo com o time da Microsoft a solução vai estar disponível no CU7 do SQL Server 2008R2 e no SP1 do SQL 2008 R2,,,

https://connect.microsoft.com/SQLServer/feedback/details/650569/ssms-2008-r2-is-losing-intellisense-after-installing-visual-studio-2010-sp1

Erro no Exchange 2010 EMC após despromover um DC


Já faz um tempo que despromovemos uma maquina Windows 2003 que estava com o nosso antigo Exchange Server 2003 e era o DC primário. Fizemos isso depois que migramos todo mundo para o Exchange 2010.

O interessante é que depois da despromoção do DC começamos a receber 2 erros ao abrir o EMC (Exchange Management Console):

  • An error caused a change in the current set of domain controllers. It was running the command ‘Get-OrganizationConfig’.
  • An error caused a change in the current set of domain controllers. It was running the command ‘Get-Recipient -PropertySet ConsoleLargeSet  -ResultSize ’1000′ -SortBy DisplayName -RecipientType ‘UserMailbox”.

Para corrigir esse problema é simples, feche o EMC e abra o Windows Explorer, vá até o diretório C:\Users\<usuário>\AppData\Roaming\Microsoft\MMC e apague o arquivo “Exchange Management Console”. Abra o EMC e o erro foi corrigido.

Removendo caixas desconectadas no Exchange Server 2010


Como provavelmente você já deve saber, no Exchange server 2010 a opção de expurgar caixa não existe mais e agora não tem uma forma fácil de remover as caixas desconectadas.

Para executar uma limpesa no MailBox Database:
clean-mailboxdatabase “Mailbox Database XXXXXXXXX” Continuar lendo