Private/New-ScriptMessage.ps1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
function New-ScriptMessage
{
<#
    .SYNOPSIS
        Helper Function to show default message used in VERBOSE/DEBUG/WARNING
     
    .DESCRIPTION
        Helper Function to show default message used in VERBOSE/DEBUG/WARNING
        and... HOST in some case.
        This is helpful to standardize the output messages
     
    .PARAMETER Message
        Specifies the message to show
     
    .PARAMETER Block
        Specifies the Block where the message is coming from.
     
    .PARAMETER DateFormat
        Specifies the format of the date.
        Default is 'yyyy\/MM\/dd HH:mm:ss:ff' For example: 2016/04/20 23:33:46:78
     
    .PARAMETER FunctionScope
        Specifies the FunctionName to retrieve.
        0 is New-ScriptMessage
        1 is the function calling New-ScriptMessage
        2 is for example the script/function calling the function which call New-ScriptMessage
        etc...
     
    .EXAMPLE
        New-ScriptMessage -Message "Francois-Xavier" -Block PROCESS -Verbose -FunctionScope 0
         
        [2016/04/20 23:33:46:78][New-ScriptMessage][PROCESS] Francois-Xavier
     
    .EXAMPLE
        New-ScriptMessage -message "Connected"
         
        if the function is just called from the prompt you will get the following output
        [2015/03/14 17:32:53:62] Connected
     
    .EXAMPLE
        New-ScriptMessage -message "Connected to $Computer" -FunctionScope 1
         
        If the function is called from inside another function,
        It will show the name of the function.
        [2015/03/14 17:32:53:62][Get-Something] Connected
     
    .NOTES
        Francois-Xavier Cat
        www.lazywinadmin.com
        @lazywinadm
        github.com/lazywinadmin
#>

    
    [CmdletBinding(SupportsShouldProcess=$true)]
    [OutputType([string])]
    param
    (
        [String]$Message,
        [String]$Block,
        [String]$DateFormat = 'yyyy\/MM\/dd HH:mm:ss:ff',
        [int]$FunctionScope = "1"
    )
    
    PROCESS
    {
        if($PSCmdlet.ShouldProcess($Message,"show default message used in VERBOSE/DEBUG/WARNING"))
        {
            $DateFormat = Get-Date -Format $DateFormat
            $MyCommand = (Get-Variable -Scope $FunctionScope -Name MyInvocation -ValueOnly).MyCommand.Name
            IF ($MyCommand)
            {
                $String = "[$DateFormat][$MyCommand]"
            } #IF
            ELSE
            {
                $String = "[$DateFormat]"
            } #Else
            
            IF ($PSBoundParameters['Block'])
            {
                $String += "[$Block]"
            }
            Write-Output "$String $Message"
        }
    } #Process
}