【发布时间】:2018-12-28 01:35:47
【问题描述】:
我认为由 Powershell 脚本调用的函数应该是有意义的
- 将相同的输出记录到日志文件和控制台中,然后
- 应返回指示成功/失败的状态。
我找到了一种方法来做到这一点,但它看起来非常繁琐和倒退(如下图所示)。我认为这是任何脚本语言的基本和必不可少的能力,我必须真的迷失和困惑以这种倒退的方式做某事。我对 PowerShell 很陌生,但来自 C# 背景。
我最终将-PassThru 添加到函数中的每个Add-Content 语句中,因此日志条目将作为Object[] 集合的项目返回到管道中。然后,我将返回 Object[] 集合中的最后一个布尔项,它是函数的状态。
# Main script c:\temp\test1.ps1
Function Write-FunctionOutputToConsole {
Param ([Object[]] $FunctionResults)
foreach ($item in $FunctionResults) {
if ($item -is [System.Array]) {
Write-Host $($item)
}
}
}
Function Get-FunctionReturnCode {
Param ([Object[]] $FunctionResults)
if ($FunctionResults[-1] -is [System.Boolean]) {
Return $FunctionResults[-1]
}
}
. c:\temp\test2.ps1 #pull in external function
$LogFile = "c:\temp\test.log"
$results = FunctionThatDoesStuff -LogFile $LogFile -DesiredReturnValue $true
Write-FunctionOutputToConsole -FunctionResults $results
$FunctionReturnCode = Get-FunctionReturnCode -FunctionResults $results
Add-Content -Path $LogFile -Value "$(Get-Date -Format G) Logging in Main: returnValue=$FunctionReturnCode" -PassThru
# Do some logic based on $FunctionReturnCode
外部函数
# c:\temp\test2.ps1
function FunctionThatDoesStuff {
Param(
[string] $LogFile,
[bool] $DesiredReturnValue
)
Add-Content -Path $LogFile -Value "-----------------------------------------" -PassThru
Add-Content -Path $LogFile -Value "$(Get-Date -Format G) returnValue=$DesiredReturnValue" -PassThru
Add-Content -Path $LogFile -Value "$(Get-Date -Format G) line 1 being logged" -PassThru
Add-Content -Path $LogFile -Value "$(Get-Date -Format G) line 2 being logged" -PassThru
return $DesiredReturnValue
}
控制台输出:
PS C:\Temp> c:\temp\test1.ps1 ----------------------------------------- 2018 年 7 月 19 日下午 3:26:28 returnValue=True 2018 年 7 月 19 日下午 3:26:28 正在记录第 1 行 2018 年 7 月 19 日下午 3:26:28 正在记录第 2 行 2018 年 7 月 19 日下午 3:26:28 登录 Main:returnValue=True日志文件
PS C:\Temp> 获取内容 c:\temp\test.log ----------------------------------------- 2018 年 7 月 19 日下午 3:29:59 returnValue=True 2018 年 7 月 19 日下午 3:29:59 正在记录第 1 行 2018 年 7 月 19 日下午 3:29:59 正在记录第 2 行 2018 年 7 月 19 日下午 3:29:59 登录 Main:returnValue=True如您所见,这会导致控制台和日志文件中的信息相同。
【问题讨论】:
标签: function powershell logging return-value