David Buckley
David Buckley

Reputation: 3

Powershell Log file

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.

:)

Upvotes: 0

Views: 4197

Answers (1)

Ranadip Dutta
Ranadip Dutta

Reputation: 9272

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.

Upvotes: 1

Related Questions