Search code examples
powershellpowershell-module

In a PowerShell module, using Start-Transcript in an exported function, changes the return value?


I hope someone can assist with this issue. I've created a logger for some work purpose, which I've made as a PS Module. The logger works fine, however just learned about the Start-Transcript and thought I'd incorporate this into my module, to log everything (including errors and other information) in a runtimelog.

The module contains a PS Class and an exported function. (see https://github.com/Ostekages/Powershell_logger/blob/main/logger.psm1)

However, here's where I encounter an issue.

When creating an instance of the class, normally it is of TypeName: Logger

But when the Start-Transcript is in the exported function, it is now a TypeName: System.String

For reference, this is the two exported functions, with or without start-transcript:

function UseLogger ($name, $path) {
    return [Logger]::New($name,$path)
}

Export-ModuleMember -Function UseLogger
function UseLogger ($name, $path) {
    Start-Transcript -Path "$Path" -Append -NoClobber
    return [Logger]::New($name,$path)
}

Export-ModuleMember -Function UseLogger

My issue is that the methods from the class, don't work, and just reports No method "log" on type [System.String]

Any information is appreciated greatly!

Regards Oste


Solution

  • Start-Transcript outputs a string, suppress it to get only the logger instance:

    function UseLogger ($name, $path) {
        Start-Transcript -Path "$Path" -Append -NoClobber |Out-Null
        return [Logger]::New($name,$path)
    }