gpt4 book ai didi

powershell - 从内部方法访问$ args/params

转载 作者:行者123 更新时间:2023-12-03 01:13:06 25 4
gpt4 key购买 nike

我正在为我的PowerShell脚本开发一种错误处理方法。我通过catch上的try / catch将错误传递给它,但是我想从调用它的命令行中遍历原始参数,以便创建错误日志和错误电子邮件。

这是我到目前为止的内容:

# --params--
param(
[string]$Directory,
[string]$ArchiveDirectory,
[string]$ErrorDirectory,
[string]$ErrorEmailFrom,
[string]$ErrorEmailTo,
[string]$ErrorEmailSubject,
[string]$ErrorSMTP,
[string]$FTPSite,
[string]$FTPUser,
[string]$FTPPass,
[string]$FTPRemoteDir
)

# list of arguments for debug
$paramList = $args

# --functions--

function Handle-MyError
{
Write-Host "handle-error"
Write-Host $args[0]; # this is the exception passed in

# -Email alert-
$subject = $ErrorEmailSubject + $FTPSite
# build message
$message = Get-Date -Format "yyyy-mm-dd hh:mm:ss"
$message += "`r`nError: " + $FTPSite + " : " + $args[0]
$message += "`r`nParameters:`r`n"

# Grab each parameter value, using Get-Variable
for ($i=0;$i -lt $paramList.Length; $i++)
{
$message += $paramList[$i]
}

# send email
$smtp = New-Object Net.Mail.SmtpClient($ErrorSMTP)
$smtp.Send($ErrorEmailFrom, $ErrorEmailTo, $subject, $message)

# drop error file
$theDate = Get-Date -Format "yyyymmdd"
$errorFile = $ErrorDirectory + "\" + $theDate + "_ERROR.txt"
Write-Host $errorFile
$message | Out-File $errorFile -Append
}

并在我的 try / catch中:
catch [Exception]
{
Write-Host "SPOT 1"
Handle-MyError $_.
}

在顶部,我尝试将原始 $args保存为 $paramList,以供以后循环使用,但它不起作用。在 Handle-MyError方法内部, $args成为传递的错误,因此我想如果我将原始 $args保存为 $paramList,则以后可以访问它,但是它很奇怪...想法?

最佳答案

有几种方法,从最坏到最好的顺序:

Get-VariableScope参数一起使用。作用域编号可以不同,但​​至少应为2(Script->Catch->Handle-MyError)

function Handle-MyError
{
Write-Host (Get-Variable -Name ErrorEmailFrom -ValueOnly -Scope 2)
}

使用 $Script:前缀
function Handle-MyError
{
Write-Host $Script:ErrorEmailFrom
}

使用 $PSBoundParameters
# list of arguments for debug
$paramList = $PsBoundParameters

function Handle-MyError
{
Param
(
$Exception,
$Cfg
)

Write-Host $Cfg.ErrorEmailFrom
}

catch [Exception]
{
Write-host "SPOT 1"
Handle-MyError -Exception $_ -Cfg $paramList
}

使用喷溅:
$paramList = $PsBoundParameters

function Handle-MyError
{
Param
(
$Exception,
$ErrorDirectory,
$ErrorEmailFrom,
$ErrorEmailTo,
$ErrorEmailSubject,
$ErrorSMTP
)

Write-Host $ErrorEmailFrom
}

catch [Exception]
{
Write-host "SPOT 1"
Handle-MyError @paramList -Exception $_
}

关于powershell - 从内部方法访问$ args/params,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35272610/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com