Partilhar via


Criar um ficheiro com conteúdo

Description

Este exemplo mostra como pode utilizar o Script recurso para criar um ficheiro.

Para utilizar o Script recurso, é necessário especificar três blocos de código. O GetScript, TestScript e SetScript.

Este exemplo utiliza dois parâmetros de entrada do utilizador. O FilePath define o caminho em que o ficheiro deve existir e o FileContent define o conteúdo do ficheiro. Estes valores são referenciados nos blocos de guiões com a using diretiva.

GetScript

$fileContent = $null

if (Test-Path -Path $using:FilePath) {
    $fileContent = Get-Content -Path $using:filePath -Raw
}

return @{
    Result = $fileContent
}

No bloco de scripts GetScript , o código verifica se o ficheiro especificado pelo FilePath existe. Se o fizer, o bloco de scripts devolve o conteúdo atual desse ficheiro para o resultado. Se não, o bloco de guiões regressa $null para o resultado.

TestScript

if (Test-Path -Path $using:FilePath) {
    $fileContent = Get-Content -Path $using:filePath -Raw
    return ($fileContent -eq $using:FileContent)
} else {
    return $false
}

No bloco de scripts TestScript , o código verifica se o ficheiro especificado pelo FilePath existe. Se não, o bloco de scripts regressa $false. Se existir, o código compara o conteúdo atual do ficheiro com o conteúdo especificado pelo FileContent. Se o conteúdo coincidir, o bloco de scripts volta a ser $true. Se não o fizerem, o bloco de guiões regressa $false.

SetScript

$streamWriter = New-Object -TypeName 'System.IO.StreamWriter' -ArgumentList @(
    $using:FilePath
)
$streamWriter.WriteLine($using:FileContent)
$streamWriter.Close()

No bloco de scripts SetScript , o código cria um objeto System.IO.StreamWriter para escrever no ficheiro especificado por FilePath. Escreve o conteúdo especificado pelo FileContent e, em seguida, fecha o objeto StreamWriter .

Com Invoke-DscResource

Este script mostra como pode utilizar o Script recurso com o Invoke-DscResource cmdlet para garantir que um ficheiro existe com conteúdo específico.

[CmdletBinding()]
param(
    [Parameter(Mandatory = $true)]
    [ValidateNotNullOrEmpty()]
    [String]
    $FilePath,

    [Parameter(Mandatory = $true)]
    [ValidateNotNullOrEmpty()]
    [String]
    $FileContent
)

begin {
    $SharedParameters = @{
        Name       = 'Script'
        ModuleName = 'PSDscResource'
        Properties = @{
            SetScript = {
                $streamWriter = New-Object -TypeName 'System.IO.StreamWriter' -ArgumentList @(
                    $using:FilePath
                )
                $streamWriter.WriteLine($using:FileContent)
                $streamWriter.Close()
            }
            TestScript = {
                if (Test-Path -Path $using:FilePath) {
                    $fileContent = Get-Content -Path $using:filePath -Raw
                    return ($fileContent -eq $using:FileContent)
                } else {
                    return $false
                }
            }
            GetScript = {
                $fileContent = $null

                if (Test-Path -Path $using:FilePath) {
                    $fileContent = Get-Content -Path $using:filePath -Raw
                }

                return @{
                    Result = $fileContent
                }
            }
        }
    }
}

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

    if ($TestResult.InDesiredState) {
        Invoke-DscResource -Method Get @SharedParameters
    } else {
        Invoke-DscResource -Method Set @SharedParameters
    }
}

Com uma configuração

Este snippet mostra como pode definir um Configuration com um Script bloco de recursos para garantir que um ficheiro existe com conteúdo específico.

Configuration ScriptExample {
    [CmdletBinding()]
    param(
        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $FilePath,

        [Parameter(Mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String]
        $FileContent
    )

    Import-DscResource -ModuleName 'PSDscResources'

    Node localhost {
        Script ScriptExample {
            SetScript = {
                $streamWriter = New-Object -TypeName 'System.IO.StreamWriter' -ArgumentList @(
                    $using:FilePath
                )
                $streamWriter.WriteLine($using:FileContent)
                $streamWriter.Close()
            }
            TestScript = {
                if (Test-Path -Path $using:FilePath) {
                    $fileContent = Get-Content -Path $using:filePath -Raw
                    return ($fileContent -eq $using:FileContent)
                } else {
                    return $false
                }
            }
            GetScript = {
                $fileContent = $null

                if (Test-Path -Path $using:FilePath) {
                    $fileContent = Get-Content -Path $using:filePath -Raw
                }

                return @{
                    Result = $fileContent
                }
            }
        }
    }
}