Creación de un archivo con contenido

Descripción

En este ejemplo se muestra cómo puede usar el Script recurso para crear un archivo.

Para usar el Script recurso, debe especificar tres bloques de código. GetScript, TestScript y SetScript.

En este ejemplo se usan dos parámetros de entrada de usuario. FilePath establece la ruta de acceso en la que debe existir el archivo y FileContent establece el contenido del archivo. Estos valores se hacen referencia en los bloques de scripts con la using directiva .

GetScript

$fileContent = $null

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

return @{
    Result = $fileContent
}

En el bloque de scripts GetScript , el código comprueba si el archivo especificado por FilePath existe. Si es así, el bloque de scripts devuelve el contenido actual del archivo para el resultado. Si no es así, el scriptblock devuelve $null para el resultado.

TestScript

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

En el bloque de scripts TestScript , el código comprueba si el archivo especificado por FilePath existe. Si no es así, el scriptblock devuelve $false. Si existe, el código compara el contenido actual del archivo con el contenido especificado por FileContent. Si el contenido coincide, el scriptblock devuelve $true. Si no lo hacen, el scriptblock devuelve $false.

SetScript

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

En el bloque de scripts SetScript , el código crea un objeto System.IO.StreamWriter para escribir en el archivo especificado por FilePath. Escribe el contenido especificado por FileContent y, a continuación, cierra el objeto StreamWriter .

Con Invoke-DscResource

Este script muestra cómo puede usar el Script recurso con el Invoke-DscResource cmdlet para asegurarse de que existe un archivo con contenido 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
    }
}

Con una configuración

Este fragmento de código muestra cómo puede definir un Configuration elemento con un Script bloque de recursos para asegurarse de que existe un archivo con contenido 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
                }
            }
        }
    }
}