Exchange 개발 관련 파워쉘 명령어 모음



/// <summary>
/// 메일박스에서 사용자 정보 가져오기
/// </summary>
/// <param name="dbhId">DB의 UniqueId</param>
/// <returns></returns>
private IList<string> GetUserIdFromMailBox(string dbhId)
{
    IList<string> list = new List<string>();
 
    using (var ems = new ExchangePowerShellWrapper(new AppConfigExchangePowerShellConfig()))
    {
        var results = ems.PipelineScriptInvoke("Get-MailboxDatabase \"" + dbhId + "\" | Get-Mailbox");
        foreach (PSObject item in results)
        {
            list.Add(item.Members["WindowsEmailAddress"].Value.ToString());
        }
    }
 
    return list;
}

[코드1] 특정 EDB안에 있는 사용자 추출 코드




//// MBX Worker process가 시작할 때 이벤트 처리
ManagementEventWatcher startWatcherProcess;
startWatcherProcess = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_ProcessStartTrace WHERE ProcessName = '" + monitoringProcessName + "'"));   // WHERE ProcessName = 'microsoft.exchange.store.worker.exe'
startWatcherProcess.EventArrived += startWatcher_EventArrived;
startWatcherProcess.Start();
 
//// MBX Worker process가 종료될 때 이벤트 처리
ManagementEventWatcher stopWatcherProcess;
stopWatcherProcess = new ManagementEventWatcher(new WqlEventQuery("SELECT * FROM Win32_ProcessStopTrace WHERE ProcessName = '" + monitoringProcessName + "'")); // WHERE ProcessName = 'microsoft.exchange.store.worker.exe'
stopWatcherProcess.EventArrived += stopWatcher_EventArrived;
stopWatcherProcess.Start();

[코드2] ManagementEventWatcher로 프로세스의 시작과 종료 이벤트를 처리



/// <summary>
/// 현재 서버의 데이터 베이스를 가져온다.
/// </summary>
/// <returns></returns>
private List<string> GetMailboxActiveDatabaseNames()
{
    var list = new List<string>();
 
    using (var ems = new ExchangePowerShellWrapper(new AppConfigExchangePowerShellConfig()))
    {
        var psScript = "Get-MailboxDatabaseCopyStatus -Active -Local | select-object DatabaseName";
        var results = ems.PipelineScriptInvoke(psScript);
        foreach (PSObject item in results)
        {
            list.Add(item.Members["DatabaseName"].Value.ToString());
        }
    }
 
    return list;
}

[코드3] 현재 서버의 Active EDB를 가져온다.




/// <summary>
/// 동적으로 사용자 추가
/// </summary>
/// <param name="emaillist"></param>
/// <returns></returns>
private Dictionary<stringstring> DynamicUserListAdd(Dictionary<stringstring> requestList)
{
    dynamicAddedDate = previousDynamicAddedDate;
    previousDynamicAddedDate = DateTime.Now.AddSeconds(-1); // 현재 시간을 포함하기 위해 1초를 뺀다.
            
    // 파워쉘 명렁으로 알아 내기
    using (var powershellInvoker = new ExchangePowerShellWrapper(new AppConfigExchangePowerShellConfig()))
    {
        foreach (var databaseName in GetMailboxActiveDatabaseNames())
        {
            // 파워쉘 실행
            //var psScript = "Get-Mailbox -Database \"" + databaseName + "\" -Filter {(WhenChanged -gt \"" + dynamicAddedDate.ToString("yyyy-MM-dd HH:mm:ss") + "\")} -ResultSize unlimited | select-object WindowsEmailAddress";
 
            // 파워쉘의 WhenChanged 필터를 통해 수정된 일자를 바탕으로 이메일 사용자 계정을 검색한다.
            log.Info(string.Format("{0} database에서 사용자를 추출하는 중입니다..."databaseName));
            Collection<Command> listCommand = new Collection<Command>();
 
            var command = new Command("Get-Mailbox");
            command.Parameters.Add("Database"databaseName);
            command.Parameters.Add("Filter""WhenChanged -gt \"" + dynamicAddedDate.ToString("yyyy-MM-dd HH:mm:ss"+ "\"");
            //command.Parameters.Add("Filter", "WhenChanged -gt \"2013-06-10 17:00:00\"");
            command.Parameters.Add("ResultSize""unlimited");
            listCommand.Add(command);
 
            var props = new string[] { "WindowsEmailAddress" };
            Command CommandSelect = new Command("Select-Object");
            CommandSelect.Parameters.Add("Property"props);
            listCommand.Add(CommandSelect);
 
            var results = powershellInvoker.PipelineInvoke(listCommand);
            log.Info(string.Format("{0} database에서 사용자 계정 {1}개 추출 하였습니다."databaseNameresults.Count));
            foreach (var user in results)
            {
                // 사용자의 이메일 주소
                var windowsEmailAddress = user.Members["WindowsEmailAddress"].Value.ToString();
 
                // 새로운 사용자만 추가
                if (!requestList.ContainsKey(windowsEmailAddress))
                {
                    requestList.Add(windowsEmailAddressdatabaseName);
                }
            }
        }
    }
 
    return requestList;
}

[코드4] 최근에 변경된 사용자만 알아내어 기존 리스트에 추가하는 코드



/// <summary>
/// 데이터베이스 명으로 사용자 리스트 가져오기
/// </summary>
/// <param name="databaseName"></param>
/// <returns></returns>
public Dictionary<stringstring> GetMailboxbyDatabaseNames(string databaseName)
{
    // 요청자 사용자 리스트
    var requestList = new Dictionary<stringstring>();
 
    // 파워쉘 명렁으로 알아 내기
    using (var powershellInvoker = new ExchangePowerShellWrapper(new AppConfigExchangePowerShellConfig()))
    {
        int mailUserCount = 0;
        var psScript = "Get-Mailbox -Database \"" + databaseName + "\" -ResultSize unlimited | select-object WindowsEmailAddress";
        foreach (var user in powershellInvoker.PipelineScriptInvoke(psScript))
        {
            // 사용자의 이메일 주소
            var windowsEmailAddress = user.Members["WindowsEmailAddress"].Value.ToString();
            var databaseNameTemp = databaseName;
 
            requestList.Add(windowsEmailAddressdatabaseName);
            mailUserCount++;
        }
 
        log.Info(string.Format("{0} database에서 {1}개의 사용자 계정이 추가 되었습니다."databaseNamemailUserCount));
    }
 
    return requestList;
}

[코드5] 데이터베이스 명으로 사용자 리스트 가져오기






+ Recent posts