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.

:)

Community
  • 1
  • 1
  • There are some other options, but have a look at `Start-Transcript` and see if it meets your needs. – Matthew Wetmore Jan 17 '17 at 04:45
  • Thanks @MatthewWetmore - I'll have a look at that. :) – David Buckley Jan 17 '17 at 05: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: https://technet.microsoft.com/en-us/library/hh360993.aspx – Matthew Wetmore Jan 17 '17 at 06: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. – Walter Mitty Jan 17 '17 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 ... https://en.wikipedia.org/wiki/Scrapbooking – David Buckley Jan 20 '17 at 09:13
  • @MatthewWetmore I've put a couple of `Start-Transcript` lines in my code but haven't really been able to test it yet ... hopefully early next week I'll get there. – David Buckley Jan 20 '17 at 09:15
  • OK, Thanks. That's what I wanted to know. – Walter Mitty Jan 20 '17 at 14:02
  • @MatthewWetmore I tried and have tested the `Start-Transcript` / `Stop-Transcript` lines but it doesn't seem to do anything for things like simple file copies, however it does put some things in for the registry `New-ItemProperty` command. – David Buckley Jan 23 '17 at 02:07

1 Answers1

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.

Ranadip Dutta
  • 8,857
  • 3
  • 29
  • 45
  • That's the same kind of function but you've missed the real question in the post. – David Buckley Jan 20 '17 at 09:11
  • You mentioned that how to capture any output and put it into log if I am not wrong @DavidBuckley – Ranadip Dutta Jan 20 '17 at 09:12
  • 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. – David Buckley Jan 20 '17 at 09:18
  • 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 – Ranadip Dutta Jan 20 '17 at 09:31
  • 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. – David Buckley Jan 23 '17 at 02:10
  • @DavidBuckley: like this : `| Out-File D:\filename.ext`. Please google about pipeline object and out-file for PS – Ranadip Dutta Jan 23 '17 at 02:33