我有两个功能:写入日志和 B 。函数 B 可以将消息输出到Verbose Stream,并返回一些值。我需要从函数 B 获得返回值到某个变量,并通过点线同时将详细流传递给函数 Write-Log 。
我试图按行进行:
$a = B -message "World" -Verbose 4>&1 | Write-Log -LogFilePath "D:\test.log"
但是它将所有消息输出到日志文件,包括返回值和变量 $ a 为空
功能代码写入日志:
function Write-Log {
[cmdletbinding()]
param(
[Parameter (ValueFromPipeline=$True)]
[string]$Text,
[string]$LogFilePath,
[switch]$Silent,
[ConsoleColor]$ForegroundColor
)
process {
[string]$MessageWithDate = "$((Get-Date).ToString()) $Text"
if (-not($Silent)) {
if($ForegroundColor -eq $null) {
Write-Host $Text
} else {
Write-Host $Text -ForegroundColor $ForegroundColor
}
}
try {
if(-not (Test-Path($($LogFilePath)))) {
New-Item -Path $($LogFilePath) -ItemType "file" | Out-Null
}
$MessageWithDate | Out-File -filepath $($LogFilePath) -Append -NoClobber
} catch {
Write-Host "Error has occurred while writing log note to file $($LogFilePath): $($_ | Select-Object -Property *)" -foregroundcolor red
}
}
}
功能代码 B :
function B{
[cmdletbinding()]
param(
$message
)
begin {
Write-Verbose "[Function B] - Start"
Write-Verbose "Initial parameters:"
($PSBoundParameters.GetEnumerator() | ForEach-Object { Write-Verbose "- $($_.Key) = '$($_.Value)'" })
}
process {
return ("Hello, " + $message)
}
end {
Write-Verbose "[Function B] - End"
}
}
我需要在变量$ a中包含“ Hello,World”,并在日志文件中包含以下内容:
3/30/2019 12:37:35 PM [Function B] - Start
3/30/2019 12:37:35 PM Initial parameters:
3/30/2019 12:37:35 PM - message = 'World'
3/30/2019 12:37:35 PM - Verbose = 'True'
3/30/2019 12:37:35 PM [Function B] - End
您能帮我解决这个问题吗?