Chapters/using-verbose-warning-informational-output/snippets.ps1

# simply notice the use of Write- commands in the below...
function Get-MachineInfo {
    [CmdletBinding()]
    Param(
        [Parameter(ValueFromPipeline=$True,
                   Mandatory=$True)]
        [Alias('CN','MachineName','Name')]
        [string[]]$ComputerName,
        
        [string]$LogFailuresToPath,

        [ValidateSet('Wsman','Dcom')]
        [string]$Protocol = "Wsman",

        [switch]$ProtocolFallback
    )
 
 BEGIN {}

 PROCESS {
    foreach ($computer in $computername) {
 
        if ($protocol -eq 'Dcom') {
            $option = New-CimSessionOption -Protocol Dcom
        } else {
            $option = New-CimSessionOption -Protocol Wsman
        }
 
        Write-Verbose "Connecting to $computer over $protocol"
        $session = New-CimSession -ComputerName $computer `
                                  -SessionOption $option
  
        Write-Verbose "Querying from $computer"
        $os_params = @{'ClassName'='Win32_OperatingSystem'
                       'CimSession'=$session}
        $os = Get-CimInstance @os_params

        $cs_params = @{'ClassName'='Win32_ComputerSystem'
                       'CimSession'=$session}
        $cs = Get-CimInstance @cs_params

        $sysdrive = $os.SystemDrive
        $drive_params = @{'ClassName'='Win32_LogicalDisk'
                          'Filter'="DeviceId='$sysdrive'"
                          'CimSession'=$session}
        $drive = Get-CimInstance @drive_params

        $proc_params = @{'ClassName'='Win32_Processor'
                         'CimSession'=$session}
        $proc = Get-CimInstance @proc_params |
                Select-Object -first 1

  
        Write-Verbose "Closing session to $computer"
        $session | Remove-CimSession
  
        Write-Verbose "Outputting for $computer"
        $obj = [pscustomobject]@{'ComputerName'=$computer
                   'OSVersion'=$os.version
                   'SPVersion'=$os.servicepackmajorversion
                   'OSBuild'=$os.buildnumber
                   'Manufacturer'=$cs.manufacturer
                   'Model'=$cs.model
                   'Procs'=$cs.numberofprocessors
                   'Cores'=$cs.numberoflogicalprocessors
                   'RAM'=($cs.totalphysicalmemory / 1GB)
                   'Arch'=$proc.addresswidth
                   'SysDriveFreeSpace'=$drive.freespace}
        Write-Output $obj
 
    } #foreach
} #PROCESS

END {}

} #function


# this is what a warning looks like...
write-warning "Danger, Will Robinson!"


# set $VerbosePreference="Continue" for the below to work.
Write-Verbose "Execution Metadata:"
Write-Verbose "User = $($env:userdomain)\$($env:USERNAME)"
$id = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$IsAdmin = [System.Security.Principal.WindowsPrincipal]::new($id).IsInRole(
'administrators')
Write-Verbose "Is Admin = $IsAdmin"
Write-Verbose "Computername = $env:COMPUTERNAME"
Write-Verbose "OS = $((Get-CimInstance Win32_Operatingsystem).Caption)"
Write-Verbose "Host = $($host.Name)"
Write-Verbose "PSVersion = $($PSVersionTable.PSVersion)"
Write-Verbose "Runtime = $(Get-Date)"


# this example adds a prefix so you can tell which
# block you're in
Function TryMe {
[cmdletbinding()]
Param(
[string]$Computername
)

Begin {
    Write-Verbose "[BEGIN ] Starting: $($MyInvocation.Mycommand)"  
    Write-Verbose "[BEGIN ] Initializing array"
    $a = @()

} #begin

Process {
    Write-Verbose "[PROCESS] Processing $Computername"
    # code goes here
} #process

End {
    Write-Verbose "[END ] Ending: $($MyInvocation.Mycommand)"

} #end

} #function



# this variation includes time stamps
Function TryMe {
[cmdletbinding()]
Param(
[string]$Computername
)

Begin {
    Write-Verbose "[$((get-date).TimeOfDay.ToString()) BEGIN ] Starting:`
    $($MyInvocation.Mycommand)"
  
    Write-Verbose "[$((get-date).TimeOfDay.ToString()) BEGIN ] `
    Initializing array"

    $a = @()

} #begin

Process {
    Write-Verbose "[$((get-date).TimeOfDay.ToString()) PROCESS] Processing `
    $Computername"

    # code goes here
} #process

End {
    Write-Verbose "[$((get-date).TimeOfDay.ToString()) END ] Ending: `
    $($MyInvocation.Mycommand)"


} #end

} #function



# quick example of informational output
Function Example {

    [CmdletBinding()]
    Param()

    Write-Information "First message" -tag status
    Write-Information "Note that this had no parameters" -tag notice
    Write-Information "Second message" -tag status

}
Example -InformationAction Continue -InformationVariable x



# capturing informational output to a variable
function Example {
    [CmdletBinding()]
    Param()

    Write-Information "First message" -tag status
    Write-Information "Note that this had no parameters" -tag notice
    Write-Information "Second message" -tag status

}

Example -InformationAction SilentlyContinue -IV x
$x



# filtering informational output
function Example {
    [CmdletBinding()]
    Param()
    Write-Information "First message" -tag status
    Write-Information "Note that this had no parameters" -tag notice
    Write-Information "Second message" -tag status

}

Example -InformationAction SilentlyContinue -IV x

$x | where tags -in @('notice')



# detailed informational example
Function Test-Me {
[cmdletbinding()]
Param()

Write-Information "Starting $($MyInvocation.MyCommand) " -Tags Process
Write-Information "PSVersion = $($PSVersionTable.PSVersion)" -Tags Meta
Write-Information "OS = $((Get-CimInstance Win32_operatingsystem).Caption)"`
-Tags Meta

Write-Verbose "Getting top 5 processes by WorkingSet"
Get-process | sort WS -Descending | select -first 5 -OutVariable s

Write-Information ($s[0] | Out-String) -Tags Data

Write-Information "Ending $($MyInvocation.MyCommand) " -Tags Process

}
test-me -InformationAction Continue
test-me -InformationVariable inf
$inf
$inf | get-member
$inf.where({$_.tags -contains 'meta'}) | select Computer,Messagedata



# see it with write-host
Function Test-Me2 {
[cmdletbinding()]
Param()

Write-Host "Starting $($MyInvocation.MyCommand) " -fore green
Write-Host "PSVersion = $($PSVersionTable.PSVersion)" -fore green
Write-Host "OS = $((Get-CimInstance Win32_operatingsystem).Caption)" `
-fore green

Write-Verbose "Getting top 5 processes by WorkingSet"
Get-process | sort WS -Descending | select -first 5 -OutVariable s

Write-Host ($s[0] | Out-String) -fore green

Write-Host "Ending $($MyInvocation.MyCommand) " -fore green

}