windows - 在函数外使用变量
问题描述
我目前正在用 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
解决方案
这与 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 ...
推荐阅读
- python - 在 RNN 模型上进行网格搜索时训练数据的形状不正确
- python - Pandas groupby + scikit 学习电源变压器
- java - 有没有办法在用 Java 创建文件时将文件发送到 AWS S3 存储桶?
- vue.js - 在 vuejs 中,拖动和调整图像大小时出现问题
- angular - 命名路由器出口在刷新后不呈现相同的组件
- mysql - SQL 按组排序
- php - 我如何通过它们的值在 PHP 中的选择元素中更改页面的位置?
- python - 在 Python 中将用户输入转换为嵌套列表
- r - 如何计算取决于2个条件
- python - 如何使用 Pandas 将变量分配给 Python 中的列