Home WindowsExchange Server Обрезать логи базы данных Exchange через скрипт Powershell на Exchange Server

Обрезать логи базы данных Exchange через скрипт Powershell на Exchange Server

by admin
142 views
Exchange logo

Диск журналов Exchange заполняется, как обрезать Exchange логи базы данных без резервного копирования. Однако если вы включите циклическое ведение журнала для очистки журналов транзакций базы данных Exchange, вы должны размонтировать и подключить базу данных, прежде чем изменения вступят в силу. Что, если есть способ удалить журналы базы данных Exchange, не размонтируя и не подключая базу данных? В этой статье вы узнаете, как обрезать журналы базы данных Exchange с помощью PowerShell.

Прежде чем мы начнем, полезно знать, что журналы базы данных Exchange должны усекаться при выполнении резервного копирования. Если он не работает должным образом, вы должны устранить неполадки и посмотреть, что происходит. Иногда у вас нет времени, а диск переполняется, и вам нужно временное исправление для очистки журналов базы данных Exchange.

Есть несколько способов сделать это:

  1. Включить циклическое ведение журнала
  2. Скрипт VSSTester PowerShell

Оба варианта в конце концов сделают то же самое; это усекает журналы базы данных Exchange. Но есть существенная разница в том, как они это делают.

Вариант 1

При первом варианте вам придется демонтировать и монтировать базу данных, что приводит к сбоям в работе пользователей. Если база данных почтовых ящиков большая и в ней терабайты журналов, это займет время. Кроме того, вы должны сделать это в нерабочее время

Вариант 2

Во втором варианте база данных будет смонтирована. Это означает, что база данных не будет отключена, и пользователи не получат никаких сбоев. Он также создаст моментальный снимок базы данных и тома журналов.

На данный момент объем журнала базы данных почтовых ящиков показывает, что свободно только 1,34 ГБ.

[PS] C:\Windows\system32>Get-MailboxDatabase -Server mbx1 | Format-List Name, EdbFilePath, LogFolderPath



Name          : DB04
EdbFilePath   : E:\MBX1_DB_1\MBX1_DB_1.edb
LogFolderPath : F:\MBX1_DB_1

Подготовка к усечению журнала через PowerShell script

Загрузите PowerShell-скрипт VSSTester.ps1 с GitHub либо с моего сайта

 Сохраните его на сервере Exchange. Создайте папку скриптов на диске (C:) и поместите скрипт в C:\scripts .

Запустите PowerShell от имени администратора и запустите сценарий PowerShell VSSTester.ps1 . Сценарий VSSTester работает для Exchange 2010, 2013, 2016 и 2019.

****************************************************************************************
****************************************************************************************
**                                                                                    **
**                 VSSTESTER SCRIPT (for Exchange 2013, 2016, 2019)                   **
**                                                                                    **
****************************************************************************************
****************************************************************************************

         Welcome to the Exchange Management Shell!

Full list of cmdlets: Get-Command
Only Exchange cmdlets: Get-ExCommand
Cmdlets that match a specific string: Help *<string>*
Get general help: Help
Get help for a cmdlet: Help <cmdlet name> or <cmdlet name> -?
Exchange team blog: Get-ExBlog
Show full output for a command: <command> | Format-List

Show quick reference guide: QuickRef
VERBOSE: Connecting to MBX1.pentagon.loc.
VERBOSE: Connected to MBX1.pentagon.loc.



Monday, September 5, 2022 12:08:41 PM


Please select the operation you would like to perform from the following options:


  1. Test backup using built-in Diskshadow
  2. Enable logging to troubleshoot backup issues


Selection:1

После запуска скрипта у нас есть два варианта. Тот, который мы ищем, это вариант 1. Тестовое резервное копирование с использованием встроенной Diskshadow .

Вставьте 1 и нажмите Enter .

Please select the operation you would like to perform from the following options:


  1. Test backup using built-in Diskshadow
  2. Enable logging to troubleshoot backup issues


Selection: 1

Укажите путь к каталогу, например, C:\temp (Если его нет , создайте каталог) и нажмите Enter .

Please specify a directory other than root of a volume to save the configuration and output files.
Directory path (e.g. C:\temp): C:\temp

Он проверит версию Exchange Server и статус модуля записи VSS. После этого он проверит, какие базы данных почтовых ящиков доступны, и спросит нас, какую из них нужно сделать резервной копией.

В нашем примере нам нравится очищать журналы базы данных почтовых ящиков DB04 , которая имеет номер 1. Введите 1 и нажмите Enter .


Monday, September 5, 2022 12:11:43 PM
Starting transcript...

--------------------------------------------------------------------------------------------------------------
Transcript started, output file is c:\temp\vssTranscript.log


Monday, September 5, 2022 12:11:43 PM
Verifying Exchange version...

--------------------------------------------------------------------------------------------------------------

MBX1 is an Exchange 2016 server.


Monday, September 5, 2022 12:11:44 PM
Checking VSS Writer Status: (All Writers must be in a Stable state before running this script)

--------------------------------------------------------------------------------------------------------------

Writer name: 'Task Scheduler Writer'
   State: [1] Stable

Writer name: 'VSS Metadata Store Writer'
   State: [1] Stable

Writer name: 'Performance Counters Writer'
   State: [1] Stable

Writer name: 'System Writer'
   State: [1] Stable

Writer name: 'Shadow Copy Optimization Writer'
   State: [1] Stable

Writer name: 'Microsoft Exchange Writer'
   State: [1] Stable

Writer name: 'ASR Writer'
   State: [1] Stable

Writer name: 'IIS Config Writer'
   State: [1] Stable

Writer name: 'IIS Metabase Writer'
   State: [1] Stable

Writer name: 'WMI Writer'
   State: [1] Stable

Writer name: 'Registry Writer'
   State: [1] Stable

Writer name: 'COM+ REGDB Writer'
   State: [1] Stable

Writer name: 'MSMQ Writer (MSMQ)'
   State: [1] Stable

Writer name: 'Cluster Shared Volume VSS Writer'
   State: [1] Stable

Writer name: 'Cluster Database'
   State: [1] Stable



Monday, September 5, 2022 12:11:49 PM
Getting databases on server: MBX1

--------------------------------------------------------------------------------------------------------------


Number Name Mounted Server
------ ---- ------- ------
     0 DB01    True MBX1
     1 DB04    True MBX1
     2 DB03    True MBX1





Select the number of the database to backup :1

Проверьте, какой диск не используется.

 В нашем примере диск X: не используется, и его мы будем использовать. Введите X: и нажмите Enter . Этот диск будет временно под базу

The database guid for 'DB04' is: 88f3ab16-f0b2-4567-a1cc-5528524a15a1

The database is mounted on server: MBX1

Monday, September 5, 2022 12:15:26 PM
Status of 'DB04' and its replicas (if any)

--------------------------------------------------------------------------------------------------------------

DB04\MBX1 is Mounted
DB04\MBX2 is Healthy



Monday, September 5, 2022 12:15:27 PM
Creating diskshadow config file...

--------------------------------------------------------------------------------------------------------------


The selected database path is 'E:\MBX1_DB_1\MBX1_DB_1.edb' so adding volume E: to backup scope


The selected database log folder path is 'F:\MBX1_DB_1' so adding volume F: to backup scope



Adding the volume for DSH file
add volume E: alias vss_test_E
Adding the volume for DSH file
add volume F: alias vss_test_F


Monday, September 5, 2022 12:15:29 PM
Getting drive letters for exposing backup snapshot
--------------------------------------------------------------------------------------------------------------


Since different volumes are used for this database's EDB and logs, we need two drive
letters to expose the backup snapshot.


Enter an unused drive letter with colon (e.g. X:) to expose the DATABASE volume : X:

На этот раз он запрашивает неиспользуемую букву диска для тома журнала. Мы будем использовать букву диска Y:, потому что она не используется, и нажмите Enter .

Enter an unused drive letter with colon (e.g. Y:) to expose the LOG volume : Y:



Monday, September 5, 2022 12:16:54 PM
Enabling Diagnostics Logging...

--------------------------------------------------------------------------------------------------------------

MSExchange Repl\Service - Expert

MSExchange Repl\Exchange VSS Writer  - Expert


Monday, September 5, 2022 12:16:55 PM
Enabling VSS Tracing...

--------------------------------------------------------------------------------------------------------------

The command completed successfully.

Monday, September 5, 2022 12:16:55 PM
Enabling ExTRA Tracing...

--------------------------------------------------------------------------------------------------------------


LastWriteTime : 9/5/2022 12:16:55 PM
Length        : 0
Name          : EnabledTraces.Config



Creating Exchange Trace data collector set...
The command completed successfully.
Starting Exchange Trace data collector...
The command completed successfully.



Monday, September 5, 2022 12:16:56 PM
Starting DiskShadow copy of Exchange database: DB04

--------------------------------------------------------------------------------------------------------------

Running the following command:

"C:\Windows\System32\diskshadow.exe /s c:\temp\diskshadow.dsh /l c:\temp\diskshadow.log"


Microsoft DiskShadow version 1.0
Copyright (C) 2013 Microsoft Corporation
On computer:  MBX1,  9/5/2022 12:16:57 PM

-> set verbose on
-> set context persistent
->
-> writer exclude {e8132975-6f93-4464-a53e-1050253ae220}
-> writer exclude {2a40fd15-dfca-4aa8-a654-1f8c654603f6}
-> writer exclude {35E81631-13E1-48DB-97FC-D5BC721BB18A}
-> writer exclude {be000cbe-11fe-4426-9c58-531aa6355fc4}
-> writer exclude {4969d978-be47-48b0-b100-f328f07ac1e0}
-> writer exclude {a6ad56c2-b509-4e6c-bb19-49d8f43532f0}
-> writer exclude {afbab4a2-367d-4d15-a586-71dbb18f8485}
-> writer exclude {59b1f0cf-90ef-465f-9609-6ca8b2938366}
-> writer exclude {542da469-d3e1-473c-9f4f-7847f01fc64f}
-> writer exclude {4dc3bdd4-ab48-4d07-adb0-3bee2926fd7f}
-> writer exclude {41e12264-35d8-479b-8e5c-9b23d1dad37e}
-> writer exclude {12ce4370-5bb7-4C58-a76a-e5d5097e3674}
-> writer exclude {cd3f2362-8bef-46c7-9181-d62844cdc062}
-> writer exclude {dd846aaa-A1B6-42A8-AAF8-03DCB6114BFD}
-> writer exclude {B2014C9E-8711-4C5C-A5A9-3CF384484757}
-> writer exclude {BE9AC81E-3619-421F-920F-4C6FEA9E93AD}
-> writer exclude {F08C1483-8407-4A26-8C26-6C267A629741}
-> writer exclude {6F5B15B5-DA24-4D88-B737-63063E3A1F86}
-> writer exclude {368753EC-572E-4FC7-B4B9-CCD9BDC624CB}
-> writer exclude {5382579C-98DF-47A7-AC6C-98A6D7106E09}
-> writer exclude {d61d61c8-d73a-4eee-8cdd-f6f9786b7124}
-> writer exclude {75dfb225-e2e4-4d39-9ac9-ffaff65ddf06}
-> writer exclude {0bada1de-01a9-4625-8278-69e735f39dd2}
-> writer exclude {a65faa63-5ea8-4ebc-9dbd-a0c4db26912a}
->
-> writer exclude "Microsoft Exchange Writer:\Microsoft Exchange Server\Microsoft Information Store\MBX1\4f55a302-0881-415d-9008-77af245f3a96"
-> writer exclude "Microsoft Exchange Writer:\Microsoft Exchange Server\Microsoft Information Store\MBX1\1f4f91fa-5fde-4133-a9ed-0a0055df5588"
->
-> Begin backup
-> add volume E: alias vss_test_E
-> add volume F: alias vss_test_F
-> create

COM call "lvssObject4->GetRootAndLogicalPrefixPaths" failed.
Component "\Microsoft Exchange Server\Microsoft Information Store\MBX1\4f55a302-0881-415d-9008-77af245f3a96" from writer "Microsoft Exchange Writer" is explicitly excluded.
Component "\Microsoft Exchange Server\Microsoft Information Store\MBX1\1f4f91fa-5fde-4133-a9ed-0a0055df5588" from writer "Microsoft Exchange Writer" is explicitly excluded.
Excluding writer "Cluster Shared Volume VSS Writer", because all of its components have been excluded.
Component "\config\sysq" from writer "MSMQ Writer (MSMQ)" is excluded from backup,
because it requires volume C:\ which is not in the shadow copy set.
Component "\config\registry" from writer "MSMQ Writer (MSMQ)" is excluded from backup,
because it requires volume C:\ which is not in the shadow copy set.
Component "\config\mapping" from writer "MSMQ Writer (MSMQ)" is excluded from backup,
because it requires volume C:\ which is not in the shadow copy set.
Component "\storage\queue" from writer "MSMQ Writer (MSMQ)" is excluded from backup,
because it requires volume C:\ which is not in the shadow copy set.
Component "\config" from writer "MSMQ Writer (MSMQ)" is excluded from backup,
because it has an excluded descendent: "sysq".
Component "\storage" from writer "MSMQ Writer (MSMQ)" is excluded from backup,
because it has an excluded descendent: "queue".
The writer "MSMQ Writer (MSMQ)" is now entirely excluded from the backup,
because it does not contain any components that can be included.

* Including writer "Microsoft Exchange Writer":
        + Adding component: \Microsoft Exchange Server\Microsoft Information Store\MBX1\88f3ab16-f0b2-4567-a1cc-5528524a15a1

Alias vss_test_E for shadow ID {b8f85ee3-93fd-46d5-ab79-af6bc0ae32b7} set as environment variable.
Alias vss_test_F for shadow ID {04ebc950-03e9-4305-aee2-9a33e7bcf79e} set as environment variable.
Alias VSS_SHADOW_SET for shadow set ID {69176ea9-6438-42b5-9d9e-12635793ea61} set as environment variable.
Inserted file Manifest.xml into .cab file 2022-09-05_24-18-21_MBX1.cab
Inserted file BCDocument.xml into .cab file 2022-09-05_24-18-21_MBX1.cab
Inserted file WM0.xml into .cab file 2022-09-05_24-18-21_MBX1.cab
Inserted file WM1.xml into .cab file 2022-09-05_24-18-21_MBX1.cab
Inserted file WM2.xml into .cab file 2022-09-05_24-18-21_MBX1.cab
Inserted file WM3.xml into .cab file 2022-09-05_24-18-21_MBX1.cab
Inserted file WM4.xml into .cab file 2022-09-05_24-18-21_MBX1.cab
Inserted file WM5.xml into .cab file 2022-09-05_24-18-21_MBX1.cab
Inserted file WM6.xml into .cab file 2022-09-05_24-18-21_MBX1.cab
Inserted file WM7.xml into .cab file 2022-09-05_24-18-21_MBX1.cab
Inserted file WM8.xml into .cab file 2022-09-05_24-18-21_MBX1.cab
Inserted file WM9.xml into .cab file 2022-09-05_24-18-21_MBX1.cab
Inserted file WM10.xml into .cab file 2022-09-05_24-18-21_MBX1.cab
Inserted file WM11.xml into .cab file 2022-09-05_24-18-21_MBX1.cab
Inserted file WM12.xml into .cab file 2022-09-05_24-18-21_MBX1.cab
Inserted file WM13.xml into .cab file 2022-09-05_24-18-21_MBX1.cab
Inserted file WM14.xml into .cab file 2022-09-05_24-18-21_MBX1.cab
Inserted file WM15.xml into .cab file 2022-09-05_24-18-21_MBX1.cab
Inserted file diskshadow.log into .cab file 2022-09-05_24-18-21_MBX1.cab

Querying all shadow copies with the shadow copy set ID {69176ea9-6438-42b5-9d9e-12635793ea61}

        * Shadow copy ID = {b8f85ee3-93fd-46d5-ab79-af6bc0ae32b7}               %vss_test_E%
                - Shadow copy set: {69176ea9-6438-42b5-9d9e-12635793ea61}       %VSS_SHADOW_SET%
                - Original count of shadow copies = 2
                - Original volume name: \\?\Volume{22fc663d-e961-4a98-83a2-276aebeddca5}\ [E:\]
                - Creation time: 9/5/2022 12:18:21 PM
                - Shadow copy device name: \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy1
                - Originating machine: MBX1.pentagon.loc
                - Service machine: MBX1.pentagon.loc
                - Not exposed
                - Provider ID: {b5946137-7b9f-4925-af80-51abd60b20d5}
                - Attributes:  No_Auto_Release Persistent Differential

        * Shadow copy ID = {04ebc950-03e9-4305-aee2-9a33e7bcf79e}               %vss_test_F%
                - Shadow copy set: {69176ea9-6438-42b5-9d9e-12635793ea61}       %VSS_SHADOW_SET%
                - Original count of shadow copies = 2
                - Original volume name: \\?\Volume{8407116c-2289-48df-bd8a-813f69f818cd}\ [F:\]
                - Creation time: 9/5/2022 12:18:21 PM
                - Shadow copy device name: \\?\GLOBALROOT\Device\HarddiskVolumeShadowCopy2
                - Originating machine: MBX1.pentagon.loc
                - Service machine: MBX1.pentagon.loc
                - Not exposed
                - Provider ID: {b5946137-7b9f-4925-af80-51abd60b20d5}
                - Attributes:  No_Auto_Release Persistent Differential

Number of shadow copies listed: 2
->
-> expose %vss_test_E% X:
-> %vss_test_E% = {b8f85ee3-93fd-46d5-ab79-af6bc0ae32b7}
The shadow copy was successfully exposed as X:\.
-> expose %vss_test_F% Y:
-> %vss_test_F% = {04ebc950-03e9-4305-aee2-9a33e7bcf79e}
The shadow copy was successfully exposed as Y:\.
-> end backup
->

Monday, September 5, 2022 12:18:26 PM
Checking VSS Writer Status: (after backup)

--------------------------------------------------------------------------------------------------------------


Writer name: 'Task Scheduler Writer'
   State: [1] Stable

Writer name: 'VSS Metadata Store Writer'
   State: [1] Stable

Writer name: 'Performance Counters Writer'
   State: [1] Stable

Writer name: 'System Writer'
   State: [1] Stable

Writer name: 'Shadow Copy Optimization Writer'
   State: [1] Stable

Writer name: 'Microsoft Exchange Writer'
   State: [1] Stable

Writer name: 'ASR Writer'
   State: [1] Stable

Writer name: 'IIS Config Writer'
   State: [1] Stable

Writer name: 'WMI Writer'
   State: [1] Stable

Writer name: 'IIS Metabase Writer'
   State: [1] Stable

Writer name: 'COM+ REGDB Writer'
   State: [1] Stable

Writer name: 'Cluster Shared Volume VSS Writer'
   State: [1] Stable

Writer name: 'Registry Writer'
   State: [1] Stable

Writer name: 'MSMQ Writer (MSMQ)'
   State: [1] Stable

Writer name: 'Cluster Database'
   State: [1] Stable


Monday, September 5, 2022 12:18:32 PM
Diskshadow Snapshots

--------------------------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------------------------


If the snapshot was successful, the snapshot should be exposed as drive(s) X: and Y:.
You should be able to see and navigate the snapshot with File Explorer. How would you like to proceed?

NOTE: It is recommended to wait a few minutes to allow truncation to possibly occur before moving past this point.
      This allows time for the logs that are automatically collected to include the window for the truncation to occur.

When ready, choose from the options below:

  1. Remove exposed snapshot now
  2. Keep snapshot exposed

WARNING: Selecting option 1 will permanently delete the snapshot created, i.e. your backup will be
 deleted.

Запустите проводник и посмотрите на диски X: и Y:.

Выберите вариант 1 и нажмите Enter , чтобы удалить снимок.

Selection :1


LastWriteTime : 9/5/2022 12:21:44 PM
Length        : 0
Name          : removeSnapshot.dsh

Microsoft DiskShadow version 1.0
Copyright (C) 2013 Microsoft Corporation
On computer:  MBX1,  9/5/2022 12:21:44 PM

-> delete shadows exposed X:
Deleting shadow copy {b8f85ee3-93fd-46d5-ab79-af6bc0ae32b7} on volume \\?\Volume{22fc663d-e961-4a98-83a2-276aebeddca5}\ from provider {b5946137-7b9f-4925-af80-51abd60b20d5} [Attributes: 0x00120009]...

1 shadow copy deleted.
-> delete shadows exposed Y:
Deleting shadow copy {04ebc950-03e9-4305-aee2-9a33e7bcf79e} on volume \\?\Volume{8407116c-2289-48df-bd8a-813f69f818cd}\ from provider {b5946137-7b9f-4925-af80-51abd60b20d5} [Attributes: 0x00120009]...

1 shadow copy deleted.
-> exit

Monday, September 5, 2022 12:21:44 PM
Disabling ExTRA Tracing...

--------------------------------------------------------------------------------------------------------------


Stopping Exchange Trace data collector on MBX1...
The command completed successfully.
Deleting Exchange Trace data collector on MBX1...
The command completed successfully.



Monday, September 5, 2022 12:21:45 PM
Disabling Diagnostics Logging...

--------------------------------------------------------------------------------------------------------------

MSExchange Repl\Service - Lowest

MSExchange Repl\Exchange VSS Writer - Lowest


Monday, September 5, 2022 12:21:45 PM
Disabling VSS Tracing...

--------------------------------------------------------------------------------------------------------------

The command completed successfully.


Monday, September 5, 2022 12:21:45 PM
Getting events from the application and system logs since the script's start time of (09/05/2022 12:10:05)

--------------------------------------------------------------------------------------------------------------

Getting application log events...
Getting system log events...
Getting events complete!


Monday, September 5, 2022 12:21:57 PM
Stopping transcript log...

--------------------------------------------------------------------------------------------------------------

Transcript stopped, output file is C:\temp\vssTranscript.log



Please use the <Enter> key to exit...:

Диски удалились ,

Убедитесь, что сценарий удалил моментальные снимки и очистил журналы.

Проверка журналов базы данных Exchange

Откройте том журнала базы данных и убедитесь, что усечение базы данных Exchange выполнено успешно.

Проверим базу данных

[PS] C:\Windows\system32>Get-MailboxDatabase -IncludePreExchange -Status | Sort Name | Format-Table Name, Server, Mounte
d

Name Server Mounted
---- ------ -------
DB01 MBX1      True
DB03 MBX1      True
DB04 MBX1      True

Вот и все, всем хорошего дня

Статьи из этой категории

Leave a Comment