我正在捕获一个函数的名称,以便在每个函数中使用$functionName = $MyInvocation.MyCommand
进行记录,然后允许我的Write-Log函数获取该值。
日志功能:
Function Write-Log {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$False)]
[ValidateSet("INFO","WARN","ERROR","FATAL","DEBUG")]
[String]
$Level = "INFO",
[Parameter(Mandatory=$True)]
[string]
$Message,
[Parameter(Mandatory=$False)]
[string]
$logfile
)
$Stamp = (Get-Date).toString("yyyy/MM/dd HH:mm:ss")
$Line = "$Stamp $Level $Message Function: $functionName User: $tech"
If($logfile) {
Add-Content $logfile -Value $Line
}
Else {
Write-Output $Line
}
}
当前,我只是遍历每个 urgent 函数,并添加$functionName = $MyInvocation.MyCommand
使其保持在适当的范围内,这确实可行,但是对我来说似乎很肮脏。在保持适当范围的同时,还有一种更干燥的方法吗?
将$functionName
放在单个函数中的日志输出示例:
2018/09/03 13:11:36 INFO Store ID object received: https://******/webacs/api/v1/data/Sites/5290873 Function: Management-AfterAll User: admin-dksc104694
2018/09/03 13:11:36 INFO Stores found: 1 Function: Management-AfterAll User: admin-dksc104694
2018/09/03 13:11:36 INFO Get-AllAp started for Store 0925 Function: Get-AllAP User: admin-dksc104694
2018/09/03 13:11:37 INFO Making Get request to https://cpist/webacs/api/v3/data/AccessPointDetails.json?.group=0925 Function: Get-AllAP User: admin-dksc104694
2018/09/03 13:11:37 DEBUG 0925AP7 discovered Function: Get-AllAP User: admin-dksc104694
2018/09/03 13:11:37 DEBUG 0925AP7 discovered Function: Get-AllAP User: admin-dksc104694
2018/09/03 13:11:38 DEBUG 0925AP7 discovered Function: Get-AllAP User: admin-dksc104694
2018/09/03 13:11:38 DEBUG 0925AP7 discovered Function: Get-AllAP User: admin-dksc104694
2018/09/03 13:11:38 DEBUG 0925AP7 discovered Function: Get-AllAP User: admin-dksc104694
2018/09/03 13:11:38 DEBUG 0925AP7 discovered Function: Get-AllAP User: admin-dksc104694
2018/09/03 13:11:39 DEBUG 0925AP7 discovered Function: Get-AllAP User: admin-dksc104694
2018/09/03 13:11:39 DEBUG 0925AP7 discovered Function: Get-AllAP User: admin-dksc104694
2018/09/03 13:11:39 DEBUG 0925AP7 discovered Function: Get-AllAP User: admin-dksc104694
2018/09/03 13:11:40 DEBUG 0925AP7 discovered Function: Get-AllAP User: admin-dksc104694
2018/09/03 13:11:40 DEBUG 0925AP7 discovered Function: Get-AllAP User: admin-dksc104694
答案 0 :(得分:2)
您可以通过查看调用堆栈来推断调用命令的名称:
function Write-Log {
[CmdletBinding()]
Param(
# ...
)
$FunctionName = (Get-PSCallStack |Select-Object -Skip 1 -First 1).Command
# ...
}
调用栈中的第一项将始终是Write-Log
函数本身,因此是-Skip 1