共用方式為


展開包含 SHA-256 檔案驗證和允許檔案覆寫的封存

描述

此範例示範如何使用 Archive 資源來確保 .zip 檔案已擴充至特定目錄,而展開的內容符合檔案中 .zip 的內容。

將 [確定] 設定為 Present 、[路徑] 設定 C:\ExampleArchivePath\Archive.zip 為 ,而 [目的地] 設定 C:\ExampleDestinationPath\Destination 為 ,則資源會在尚未存在時,將 的內容 Archive.zip 展開至 Destination 資料夾。

Validate 設定為 $true 並將 Checksum 設定為 SHA-256 時,資源會比較每個展開檔案的 SHA256 總和檢查碼與 中的 Archive.zip 相關檔案。 如果任何展開檔案的總和檢查碼不符合 中 Archive.zip 該檔案總和檢查碼,則資源已不符合所需的狀態。

Force 設定為 $true 時,資源會以不正確的總和檢查碼覆寫任何展開的檔案。 如果 Force 設定為 $false ,則資源會擲回例外狀況,而不是覆寫檔案。

使用 Invoke-DscResource

此腳本示範如何搭配 Cmdlet 使用 Archive 資源,以確保 Archive.zip 已展開至 Destination 具有 SHA256 總和檢查碼驗證的資料夾。 Invoke-DscResource

[CmdletBinding()]
param()

begin {
    $SharedParameters = @{
        Name       = 'Archive'
        ModuleName = 'PSDscResource'
        Properties = @{
            Path        = 'C:\ExampleArchivePath\Archive.zip'
            Destination = 'C:\ExampleDestinationPath\Destination'
            Validate    = $true
            Force       = $true
            Ensure      = 'Present'
        }
    }

    $NonGetProperties = @(
        'Validate'
        'Force'
        'Ensure'
    )
}

process {
    $TestResult = Invoke-DscResource -Method Test @SharedParameters

    if ($TestResult.InDesiredState) {
        $QueryParameters = $SharedParameters.Clone()

        foreach ($Property in $NonGetProperties) {
            $QueryParameters.Properties.Remove($Property)
        }

        Invoke-DscResource -Method Get @QueryParameters
    } else {
        Invoke-DscResource -Method Set @SharedParameters
    }
}

使用組態

此程式碼片段示範如何使用資源區塊來定義 , ConfigurationArchive 以確保 Archive.zip 已擴充至 Destination 具有 SHA256 總和檢查碼驗證的資料夾。

Configuration ExpandArchiveDefaultValidationAndForce {
    Import-DscResource -ModuleName 'PSDscResources'

    Node localhost {
        Archive ExampleArchive {
            Path        = 'C:\ExampleArchivePath\Archive.zip'
            Destination = 'C:\ExampleDestinationPath\Destination'
            Validate    = $true
            Force       = $true
            Ensure      = 'Present'
        }
    }
}