Answer the question
In order to leave comments, you need to log in
How to get the result of a function execution and redirect verbose output stream to pipeline at the same time?
Hello,
there is a function that writes text to a log file and displays it in the powershell window:
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
}
}
}
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 = B -message "World" -Verbose 4>&1 | Write-Log -LogFilePath "D:\test.log"
Answer the question
In order to leave comments, you need to log in
So far I've found this one that works as it should:
. { $a = B -message "World" -Verbose } 4>&1 | Write-Log -LogFilePath "D:\test.log"
if you add return $MessageWithDate
to function Write-Log process
then get back everything at all:
$a = (B -message "World" -Verbose 4>&1 | Write-Log -LogFilePath "c:\temp\test.log" ) ; $a
[Function B] - Start
Initial parameters:
- message = 'World'
- Verbose = 'True'
Hello, World
[Function B] - End
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 Hello, World
3/30/2019 12:37:35 PM [Function B] - End
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question