首页 > 解决方案 > 在函数外使用变量

问题描述

我目前正在用 Powershell 编写我的第一个脚本,我已经面临第一个问题。我想从函数中的变量中读取值,以便稍后在另一个 cmd-let 中使用该变量。现在的问题是该变量仅在功能块内部而不是外部被识别。我怎样才能让它工作?

谢谢您的帮助 :-)

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

Send-MailMessage -To "<xxx@xxx.de>" -Subject "$text" -Body "The GPO backup creation was completed with the following status: `n $text" -SmtpServer "xxx@xxx.de" -From "xxx@xxx.de"

我想提交 $text

标签: windowspowershell

解决方案


这与 PowerShell 中的变量作用域行为有关。

默认情况下,调用者范围内的所有变量在函数内都是可见的。所以我们可以这样做:

function Print-X
{
  Write-Host $X
}

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

到现在为止还挺好。但是当我们开始写入函数本身之外的变量时,PowerShell 会透明地在函数自己的范围内创建一个新变量

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

那么该怎么办?您可以使用作用域修饰符写入函数外部的变量,但这里真正的解决方案是从函数返回值:

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 ...

推荐阅读