windows - 在函数外使用变量

标签 windows powershell

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

感谢您的帮助:-)

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

最佳答案

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

关于windows - 在函数外使用变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61030113/

相关文章:

c++ - 在没有管理员权限的情况下以 C++ 编程方式将程序添加到启动

windows - 为什么弹出窗口上的图标和按钮有时看起来不一样?

powershell - winspool.drv的openprinter无法正常工作

powershell - 如何使用Microsoft帐户添加-AzureRmAccount?

powershell - Powershell将用户添加到组

c++ - 为什么 Qt 资源在 Linux 而不是 Windows 中加载?

c# 如何使用新的 Version Helper API

powershell - Pester 5.0.2 BeforeAll block 代码未显示在 Describe block 中

arrays - PowerShell - 将扩展参数传递给 Start-Job cmdlet

c++ - 在对象中创建另一个对象时,对象的成员变量被覆盖