Uso de variables fuera de una función

Julian05:

Actualmente estoy escribiendo mi primer guión en Powershell y yo ya estoy frente al primer problema. Me gustaría leer el valor de una variable en una función para que pueda usar esta variable en otro cmd-dejo más tarde. El problema ahora es que la variable sólo se reconoce en el interior del bloque de función y no fuera. ¿Cómo puedo conseguir que esto funcione?

Gracias por la ayuda :-)

function Write-Log([string]$logtext, [int]$level=0)
{
  if($level -eq 0)
{
    $logtext = "[INFO] " + $logtext
    $text = "["+$logdate+"] - " + $logtext
    Write-Host $text
}
}

Send-MailMessage -To "<[email protected]>" -Subject "$text" -Body "The GPO backup creation was completed with the following status: `n $text" -SmtpServer "[email protected]" -From "[email protected]"

Me gustaría presentar $ texto

Mathias R. Jessen:

Esto tiene que ver con el comportamiento de alcance variable en PowerShell.

Por defecto, todas las variables en el alcance de la persona que llama es visible dentro de la función. Por lo que podemos hacer:

function Print-X
{
  Write-Host $X
}

$X = 123
Print-X # prints 123
$X = 456 
Print-X # prints 456

Hasta aquí todo bien. Pero cuando comenzamos a escribir a variables fuera de la función en sí, PowerShell transparente crea una nueva variable en el interior propio ámbito de la función:

function Print-X2
{
  Write-Host $X   # will resolve the value of `$X` from outside the function
  $X = 999        # This creates a new `$X`, different from the one outside
  Write-Host $X   # will resolve the value of the new `$X` that new exists inside the function
}

$X = 123
Print-X2       # Prints 123, and 999
Write-Host $X  # But the value of `$X` outside is still 123, unchanged

¿Entonces lo que hay que hacer? Usted podría utilizar un modificador de ámbito escribir en la variable fuera de la función, pero la solución real aquí es para devolver el valor de la función en su lugar:

function Write-Log([string]$logtext, [int]$level=0, [switch]$PassThru = $true)
{
    if($level -eq 0)
    {
        $logtext = "[INFO] " + $logtext
        $text = "["+$logdate+"] - " + $logtext
        Write-Host $text
        if($PassThru){
            return $text
        }
    }
}

$logLine = Write-Log "Some log message" -PassThru

Send-MailMessage -Subject $logLine ...

Supongo que te gusta

Origin http://10.200.1.11:23101/article/api/json?id=406249&siteId=1
Recomendado
Clasificación