0

Firstly I want to point out that I'm a PowerShell ScrapBooker and not really terribly knowledgeable about PowerShell.

I've been working on a script that installs BGInfo ... I have the actual install and uninstall working perfectly, and now I'm moving on to getting the logging sorted out nicely.

I found this article "Create Log File in Powershell" which was wonderful and have incorporated this Function into my script.

Function Write-Log {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$False)]
[ValidateSet("LABEL","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")
IF ($Level -eq "LABEL") {
    $Line = "$Message"
    }
ELSE {
    $Line = "$Stamp $Level $Message"
    }
If($logfile) {
    Add-Content $logfile -Value $Line
}
Else {
    Write-Output $Line
}
}

What I need to know is how to use this to log output from commands.

For Example:

In My script I have this command:

New-ItemProperty -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Run' -Name BgInfo -Value """$InstPath\Bginfo.exe"" $InstPath\$BGTemplateFile $InstOptions" -PropertyType 'String' -Force

or this one:

Copy $SourcePath\Bginfo.exe $InstPath

What I would like to know is how I can use my function to capture ANY output from that command and log it in my log file.

I guess that I would also like to use this information and apply it to any other commands where I want to log something.

Hopefully that's all clear and makes sense and that someone can help me out.

Cheers,

Dave.

:)

8
  • There are some other options, but have a look at Start-Transcript and see if it meets your needs. Commented Jan 17, 2017 at 4:45
  • Thanks @MatthewWetmore - I'll have a look at that. :) Commented Jan 17, 2017 at 5:17
  • I can't do a proper answer from mobile, but if you really want to pipe output from commands into your logging function, the approach is ValueFromPipeline. I'll get an example tomorrow. See also: technet.microsoft.com/en-us/library/hh360993.aspx Commented Jan 17, 2017 at 6:54
  • I'm curious about what a Scrapbooker is. I built a small tool that I'd like to share with beginners, maybe scrapbookers. The tool isn't relevant to this problem, so I'm not posting it here. Commented Jan 17, 2017 at 14:05
  • @WalterMitty What I mean by scrapbooker in this instance is that I do lots of copy and paste from google search results. Someone who is into scrapbooking is woud be doing things like this ... en.wikipedia.org/wiki/Scrapbooking Commented Jan 20, 2017 at 9:13

1 Answer 1

1

I believe you are referring to this function:

function Write-Log 
{ 
    [CmdletBinding()] 
    Param 
    ( 
        [Parameter(Mandatory=$true, 
                   ValueFromPipelineByPropertyName=$true)] 
        [ValidateNotNullOrEmpty()] 
        [Alias("LogContent")] 
        [string]$Message, 

        [Parameter(Mandatory=$false)] 
        [Alias('LogPath')] 
        [string]$Path='C:\Logs\PowerShellLog.log', 

        [Parameter(Mandatory=$false)] 
        [ValidateSet("Error","Warn","Info")] 
        [string]$Level="Info", 

        [Parameter(Mandatory=$false)] 
        [switch]$NoClobber 
    ) 

    Begin 
    { 
        # Set VerbosePreference to Continue so that verbose messages are displayed. 
        $VerbosePreference = 'Continue' 
    } 
    Process 
    { 

        # If the file already exists and NoClobber was specified, do not write to the log. 
        if ((Test-Path $Path) -AND $NoClobber) { 
            Write-Error "Log file $Path already exists, and you specified NoClobber. Either delete the file or specify a different name." 
            Return 
            } 

        # If attempting to write to a log file in a folder/path that doesn't exist create the file including the path. 
        elseif (!(Test-Path $Path)) { 
            Write-Verbose "Creating $Path." 
            $NewLogFile = New-Item $Path -Force -ItemType File 
            } 

        else { 
            # Nothing to see here yet. 
            } 

        # Format Date for our Log File 
        $FormattedDate = Get-Date -Format "yyyy-MM-dd HH:mm:ss" 

        # Write message to error, warning, or verbose pipeline and specify $LevelText 
        switch ($Level) { 
            'Error' { 
                Write-Error $Message 
                $LevelText = 'ERROR:' 
                } 
            'Warn' { 
                Write-Warning $Message 
                $LevelText = 'WARNING:' 
                } 
            'Info' { 
                Write-Verbose $Message 
                $LevelText = 'INFO:' 
                } 
            } 

        # Write log entry to $Path 
        "$FormattedDate $LevelText $Message" | Out-File -FilePath $Path -Append 
    } 
    End 
    { 
    } 
}

Usage:

 Write-Log -Message 'My log Error Message' -Path c:\Logs\Script.log -Level Error

 Write-Log -Message 'My log Warning message' -Level Warn

Note: By default its storing in C:\logs\PowershellLog.log. You can change it on the fly during using also and you can hardcode it in function itself.

Hope it helps.

Sign up to request clarification or add additional context in comments.

6 Comments

That's the same kind of function but you've missed the real question in the post.
You mentioned that how to capture any output and put it into log if I am not wrong @DavidBuckley
Yes .. however your function does exactly the same thing that mine does ... which lets me "Send" messages to the logfile ... what it does not do is capture the output from some commands ... if they are errors or not and send that to the logfile using my function. Please re-read the examples.
Oo. That one. YOu can simply use >> wherever stdout is coming and give your file path after it. It will append the data to the file. You can also use *pipeline and Out-File -path "filepath" * , that will also put the output in the file
I'm not sure what you mean by *pipeline and Out-File -path. Can you please elaborate with examples, specifically around the "Copy" command in my original post.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.