How to get the result of the function and redirect the output to verbose in the pipeline at the same time?

Hello,
there is a function that writes text to the log file and displays it in a 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 a log note to file $($LogFilePath): $($_ | Select-Object-Property *)" -foregroundcolor red
}
}
}


There is a function that returns a value:
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"
}
}


The real question is this: I need to get the verbose stream to the function Write-Log through the pipeline and get the result of the function into a variable at the same time. This code writes to a log file even output flow, and the variable turns out empty
$a = B -message the "World" -Verbose 4>&1 | Write-Log-LogFilePath "D:\test.log"


Tell me, please, how to organize this process?
March 19th 20 at 09:18
2 answers
March 19th 20 at 09:20
Solution
Until I found a solution that works as it should:
. { $a = B -message the "World" -Verbose } 4>&1 | Write-Log-LogFilePath "D:\test.log"
March 19th 20 at 09:22
if you add return $MessageWithDate in function Write-Log process
you will get back all:
$a = (B -message the "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
I need to use $a to "Hello, World", and in the log something like
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
- gregorio.Brakus commented on March 19th 20 at 09:25

Find more questions by tags PowerShell