UWF_Volume

Этот класс управляет томом, защищенным с помощью единого фильтра записи (UWF).

Синтаксис

class UWF_Volume {
    [key, Read] boolean CurrentSession;
    [key, Read] string DriveLetter;
    [key, Read] string VolumeName;
    [Read, Write] boolean BindByDriveLetter;
    [Read] boolean CommitPending;
    [Read, Write] boolean Protected;

    UInt32 CommitFile([in] string FileFullPath);
    UInt32 CommitFileDeletion(string FileName);
    UInt32 Protect();
    UInt32 Unprotect();
    UInt32 SetBindByDriveLetter(boolean bBindByVolumeName);
    UInt32 AddExclusion(string FileName);
    UInt32 RemoveExclusion(string FileName);
    UInt32 RemoveAllExclusions();
    UInt32 FindExclusion([in] string FileName, [out] bFound);
    UInt32 GetExclusions([out, EmbeddedInstance("UWF_ExcludedFile")] string ExcludedFiles[]);

};

Члены

В следующих таблицах перечислены методы и свойства, принадлежащие этому классу.

Методы

Метод Описание
UWF_Volume.AddExclusion Добавляет файл или папку в список исключений файлов для тома, защищенного с помощьюUWF.
UWF_Volume.CommitFile Фиксирует изменения с наложения на физический том для указанного файла на томе, защищенном единым фильтром записи (UWF).
UWF_Volume.CommitFileDeletion Удаляет защищенный файл из тома и фиксирует удаление в физическом томе.
UWF_Volume.FindExclusion Определяет, находится ли определенный файл или папка в списке исключений для тома, защищенного с помощьюUWF.
UWF_Volume.GetExclusions Извлекает список всех исключений файлов для тома, защищенного с помощьюUWF.
UWF_Volume.Protect Защищает том после следующего перезапуска системы, если после перезапуска включенА UWF.
UWF_Volume.RemoveAllExclusions Удаляет все файлы и папки из списка исключений для тома, защищенного UWF.
UWF_Volume.RemoveExclusion Удаляет определенный файл или папку из списка исключений файлов для тома, защищенного с помощьюUWF.
UWF_Volume.SetBindByDriveLetter Задает свойство BindByDriveLetter , указывающее, привязан ли том UWF к физическому тому буквой диска или именем тома.
UWF_Volume.Unprotect Отключает защиту UWF тома после следующего перезапуска системы.

Свойства

Свойство Тип данных Квалификаторы Описание
BindByDriveLetter Логическое [чтение, запись] Указывает тип привязки, используемой томом.
- Значение True для привязки тома с помощью DriveLetter(свободная привязка)
- False для привязки тома с помощью VolumeName (жесткой привязки).
CommitPending Логическое [чтение] Зарезервировано для использования корпорацией Майкрософт.
CurrentSession Логическое [ключ, чтение] Указывает, для какого сеанса объект содержит параметры.
- True , если параметры для текущего сеанса
- — False , если параметры предназначены для следующего сеанса, следующего за перезапуском.
DriveLetter строка [ключ, чтение] Буква диска тома. Если в томе нет буквы диска, это значение равно NULL.
Защищены Логическое [чтение, запись] Если значение CurrentSession имеет значение true, указывает, защищен ли в данный момент том UWF.
Если значение CurrentSession равно false, указывает, защищен ли том в следующем сеансе после перезапуска устройства.
Имя_тома строка [ключ, чтение] Уникальный идентификатор тома в текущей системе. Значение VolumeName совпадает со свойством DeviceID класса Win32_Volume для тома.

Комментарии

Для изменения свойств или вызова методов, изменяющих параметры конфигурации, необходимо использовать учетную запись администратора.

Включение и отключение защиты UWF

В следующем примере показано, как защитить или снять защиту тома с помощью UWF с помощью поставщика инструментария управления Windows (WMI) в скрипте PowerShell.

PowerShellscript создает функцию Set-ProtectVolume, которая включает или отключает защиту UWF для тома. Затем скрипт демонстрирует, как использовать функцию .

$COMPUTER = "localhost"
$NAMESPACE = "root\standardcimv2\embedded"

# Define common parameters

$CommonParams = @{"namespace"=$NAMESPACE; "computer"=$COMPUTER}

# Create a function to protect or unprotect a volume based on the drive letter of the volume

function Set-ProtectVolume($driveLetter, [bool] $enabled) {

# Each volume has two entries in UWF_Volume, one for the current session and one for the next session after a restart
# You can only change the protection status of a drive for the next session

    $nextConfig = Get-WMIObject -class UWF_Volume @CommonParams |
        where {
            $_.DriveLetter -eq "$driveLetter" -and $_.CurrentSession -eq $false
        };

# If a volume entry is found for the drive letter, enable or disable protection based on the $enabled parameter

    if ($nextConfig) {

        Write-Host "Setting drive protection on $driveLetter to $enabled"

        if ($Enabled -eq $true) {
            $nextConfig.Protect() | Out-Null;
        } else {
            $nextConfig.Unprotect() | Out-Null;
        }
    }

# If the drive letter does not match a volume, create a new UWF_volume instance

    else {
    Write-Host "Error: Could not find $driveLetter. Protection is not enabled."
    }
}

# The following sample commands demonstrate how to use the Set-ProtectVolume function
# to protect and unprotect volumes

Set-ProtectVolume "C:" $true
Set-ProtectVolume "D:" $true

Set-ProtectVolume "C:" $false

Управление исключениями файлов и папок UWF

В следующем примере показано, как управлять исключениями файлов и папок UWF с помощью поставщика WMI в скрипте PowerShell. Скрипт PowerShell создает четыре функции, а затем демонстрирует их использование.

Первая функция Get-FileExclusions отображает список исключений файлов UWF, которые существуют на томе. Отображаются исключения как для текущего, так и для следующего сеанса, следующего после перезапуска.

Вторая функция Add-FileExclusion добавляет файл или папку в список исключений UWF для заданного тома. Исключение добавляется для следующего сеанса, следующего за перезапуском.

Третья функция Remove-FileExclusion удаляет файл или папку из списка исключений UWF для заданного тома. Исключение удаляется для следующего сеанса, следующего за перезапуском.

Четвертая функция Clear-FileExclusions удаляет все исключения файлов UWF и папок из заданного тома. Исключения удаляются для следующего сеанса, следующего за перезапуском.

$COMPUTER = "localhost"
$NAMESPACE = "root\standardcimv2\embedded"

# Define common parameters

$CommonParams = @{"namespace"=$NAMESPACE; "computer"=$COMPUTER}

function Get-FileExclusions($driveLetter) {

# This function lists the UWF file exclusions for a volume, both
# for the current session as well as the next session after a restart 

# $driveLetter is the drive letter of the volume

# Get the UWF_Volume configuration for the current session

    $currentConfig = Get-WMIObject -class UWF_Volume @CommonParams |
        where {
            $_.DriveLetter -eq "$driveLetter" -and $_.CurrentSession -eq $true
        };

# Get the UWF_Volume configuration for the next session after a restart

    $nextConfig = Get-WMIObject -class UWF_Volume @CommonParams |
        where {
            $_.DriveLetter -eq "$driveLetter" -and $_.CurrentSession -eq $false
        };

# Display file exclusions for the current session

    if ($currentConfig) {

        Write-Host "The following files and folders are currently excluded from UWF filtering for $driveLetter";

        $currentExcludedList = $currentConfig.GetExclusions()

        if ($currentExcludedList) {
            foreach ($fileExclusion in $currentExcludedList.ExcludedFiles)  {
                Write-Host "  " $fileExclusion.FileName
            }
        } else {
            Write-Host "  None"
        }
    } else {
        Write-Error "Could not find drive $driveLetter";
}

# Display file exclusions for the next session after a restart

    if ($nextConfig) {

        Write-Host ""
        Write-Host "The following files and folders will be excluded from UWF filtering for $driveLetter after the next restart:";

        $nextExcludedList = $nextConfig.GetExclusions()

        if ($nextExcludedList) {
            foreach ($fileExclusion in $nextExcludedList.ExcludedFiles)  {
                Write-Host "  " $fileExclusion.FileName
            }
        } else {
            Write-Host "  None"
        }

        Write-Host ""
    }
}

function Add-FileExclusion($driveLetter, $exclusion) {

# This function adds a new UWF file exclusion to a volume
# The new file exclusion takes effect the next time the device is restarted and UWF is enabled

# $driveLetter is the drive letter of the volume
# $exclusion is the path and filename of the file or folder exclusion

# Get the configuration for the next session for the volume

    $nextConfig = Get-WMIObject -class UWF_Volume @CommonParams |
        where {
            $_.DriveLetter -eq "$driveLetter" -and $_.CurrentSession -eq $false
        };

# Add the exclusion

    if ($nextConfig) {
        $nextConfig.AddExclusion($exclusion) | Out-Null;
        Write-Host "Added exclusion $exclusion for $driveLetter";
    } else {
        Write-Error "Could not find drive $driveLetter";
    }
}

function Remove-FileExclusion($driveLetter, $exclusion) {

# This function removes a UWF file exclusion from a volume
# The file exclusion is removed the next time the device is restarted

# $driveLetter is the drive letter of the volume
# $exclusion is the path and filename of the file or folder exclusion

# Get the configuration for the next session for the volume

    $nextConfig = Get-WMIObject -class UWF_Volume @CommonParams |
        where {
            $_.DriveLetter -eq "$driveLetter" -and $_.CurrentSession -eq $false
        };

# Try to remove the exclusion

    if ($nextConfig) {
        try {
            $nextConfig.RemoveExclusion($exclusion) | Out-Null;
            Write-Host "Removed exclusion $exclusion for $driveLetter";
        } catch {
            Write-Host "Could not remove exclusion $exclusion on drive $driveLetter"
        }
    } else {
        Write-Error "Could not find drive $driveLetter";
    }
}

function Clear-FileExclusions($driveLetter) {

# This function removes all UWF file exclusions on a volume
# The file exclusions are removed the next time the device is restarted

# $driveLetter is the drive letter of the volume

# Get the configuration for the next session for the volume

    $nextConfig = Get-WMIObject -class UWF_Volume @CommonParams |
        where {
            $_.DriveLetter -eq "$driveLetter" -and $_.CurrentSession -eq $false
        };

# Remove all file and folder exclusions

    if ($nextConfig) {
        $nextConfig.RemoveAllExclusions() | Out-Null;
        Write-Host "Cleared all exclusions for $driveLetter";
    } else {
        Write-Error "Could not clear exclusions for drive $driveLetter";
    }
}

# Some examples of using the functions

Clear-FileExclusions "C:"

Add-FileExclusion "C:" "\Users\Public\Public Documents"
Add-FileExclusion "C:" "\myfolder\myfile.txt"

Get-FileExclusions "C:"

Remove-FileExclusion "C:" "\myfolder\myfile.txt"

Get-FileExclusions "C:"

Требования

Выпуск для Windows Поддерживается
Домашняя страница Windows Нет
Windows Pro Нет
Windows Корпоративная Да
Windows для образовательных учреждений Да
Windows IoT Корпоративная Да