Asstance on PowerShell Script write-log function

This post was originally published on this site

Hi All, I have created the below function in order to get all output of a runing script, as I’m beginer and not very experienced on powershell so I need your assistance to add some thing to my script

what I need : I need to format my output on console with some color because this function will be used for a long script

 

the script includ some parts like connect to vcenter and other stuff ….and functions

 

below the script

 

function Write-Log {

    [CmdletBinding()]

    Param

    (      

        [Parameter(Mandatory = $true)]

        [string] $FilePath,

 

        [Parameter(Mandatory = $true)]

        [string] $Message,

 

        [ValidateSet(“Info”, “Warning”, “Error”, “Success”)]

        $Level = “Info”,

 

        [switch]$Clear,

 

        [switch]$StartInfo

    )

 

     if (-not (Test-Path ‘.Output’)) {

                New-Item -Path ‘.Output’ -ItemType Directory          

               

               

    }

 

        if ($Clear) {

        Clear-Content -Path $FilePath

    }

 

    if ($StartInfo) {

        [string[]]$StartText = @()

        $StartText += “$(“#” * 56)”

        $StartText += “# Running script : $($MyInvocation.ScriptName)”

        $StartText += “# Start time : $(Get-Date)” 

        $StartText += “# Executing account : $([Security.Principal.WindowsIdentity]::GetCurrent().Name)”

        $StartText += “# ComputerName : $env:COMPUTERNAME”

        $StartText += “$(“#” * 56)”

        $StartText | Out-File -FilePath $FilePath -Append

    }

 

    $FormattedDate = Get-Date -Format “[yyyy-MM-dd][HH:mm:ss]”

    $OutString = “$FormattedDate – $Level – $Message”

    $OutString | Out-File -FilePath $FilePath -Append

 

    switch ($Level) {

        “Info” { Write-Host $OutString -ForegroundColor Gray ; break }

        “Warning” { Write-Host $OutString -ForegroundColor Yellow; break }

        “Error” { Write-Host $OutString -ForegroundColor Red; break }

        “Success” { Write-Host $OutString -ForegroundColor Green; break }

        Default { Write-Host $OutString; break }

    }

   

}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.