Powershell – Writing out Array Elements

 

Background

As I went back and started closing out the many Google Chrome Windows and Tabs that I had opened, I took another look at a blog post titled “A Taste of PowerShell – String Manipulation: Splitting and Joining Strings” –http://tasteofpowershell.blogspot.com/2009/08/string-manipulation-splitting-and.html .

 

Introduction

The Blog post has a very concise code that was quite honestly over my head.  It accesses a data file and read and emit the contents.

Actual Code:


Get-Content people.txt |
>> %{$data = $_.split("`t"); Write-Output "$($data[1]) $($data[0]), $($data[2])"}

 

I tried changing it to


Get-Content people.txt | %{$data = $_.split("`t"); Write-Output "$($data[1]) $($data[0]), $($data[2])"}

 

so that I can see everything on one line, but I am still thinking to myself what does the % sign mean.

Later I found that it is a shortcut for iterating through a list. i.e. for / while.

 

Sample Rewrite attempts

Here is my attempts at rewrites.

 

($data[2]):

Here is what happens when we have ($data[2]) as part of Write-Output

Get-Content people.txt | %{ $data = $_.split("\s+"),3; Write-Output "First Name: ($data[2]) " }

Output:

output1

($arrayPeople[0]):

Here is what happens when we have ($arrayPeople[0]) as part of Write-Output


(Get-Content people.txt ) | %{ $data = $_; $arrayPeople = $data -split "\s+"; Write-Host "First Name: $arrayPeople[0]"; }

Output:

output2

($arrayPeople[0]) ($arrayPeople[1]) (arrayPeople[2]):

Here is what happens when we have ($arrayPeople[0])  ($arrayPeople[1]) ($arrayPeople[2]) as part of Write-Output


(Get-Content peoplepiped.txt ) | %{ $data = $_; $arrayPeople = $data -split '\s+';  Write-Host  "($arrayPeople[0]) ($arrayPeople[1]) in ($arrayPeople[2])" ; }

Output:

output3

 

 

Using format -f argument1, argument2, argument3 ( Works ):

Using format ( -f ) argument1, argument2, argument3

(Get-Content people.txt ) | %{ $data = $_; $arrayPeople = $data -split '\s+'; "{0} {1} in {2} " -f $arrayPeople[1], $arrayPeople[0] , $arrayPeople[2] }

Output:

output4

 

 

Write-Host ( Works ) :

Preceding the array element with a dollar using ($) — $(arrayVar[position])


(Get-Content people.txt ) | `
	%{ 
		$data = $_; 
		$arrayPeople = $data -split '\s+'; 
		Write-Host "$($arrayPeople[0]) $($arrayPeople[1]) in $($arrayPeople[2])" ; 
	 }


Output:

output4

 

 

Summary

When array elements are referenced within a Write-Host statement, please surround with dollar sign ($)….$($Array[array-element]).

Or use composite formatting.

Syntax:


"{} {1} in {2} " -f variable-1, variable-2 , variable-3

 

Sample:


"{0} {1} in {2} " -f $arPeople[1], $arPeople[0] , $arPeople[2]

 

Parting Comment

Sorry it took a bit of time to explain what one hopes will be easy to code; the idea of printing array elements.

Now when I go back and look at the earlier code, I see the importance of the $sign that precedes each array element:


    Get-Content people.txt | %{$data = $_.split("`t"); Write-Output "$($data[1]) $($data[0]), $($data[2])"}

 

Reference

Powershell – Q/A

Powershell – Format

 

Powershell – Composite Formatting

 

Powershell – String Manipulation

 

Powershell – Get-Content

 

Technical : Microsoft – Event Log / Event Viewer – Query via PowerShell

Technical : Microsoft – Event Log / Event Viewer – Query via PowerShell

Introduction

After my fiasco of not paying attention to my Event Log, I need a quick way to aggregate Event Log entries and here is what I came up with through curating Google web postings.

Code



# PowerShell example which groups event then sorts in descending order.
Clear-Host

$logName = "System"

#get date
$dateCurrent = Get-Date

#For the Week
$NDays = -7
$dateNDaysAgo = $dateCurrent.AddDays($NDays)

Write-Host "Log Entries since $dateNDaysAgo"

Get-WinEvent -Logname $logName  | `
where-object { $_.timecreated -gt $date  -and $_.levelDisplayName -in "Critical", "error", "warning" } | `
Group-Object ProviderName, levelDisplayName, ID | `
Sort-Object Count -descending | `
Format-Table Count, Name -auto

Output:

EventLogAggregator

Conclusion

And, yes I have too much time on my hands, and not enough brains; as I need Splunk, Nagios, or System Center.

Addendum

Addendum – 2014.01.20

Tried the code above on an MS Windows Vista Machine, but unfortunately it failed.

The original code was developed and targeted an MS Windows 2012 box.

The error message we got on the Vista box read:


You must provide a value expression on the right-hand side of the '-' operator.
At C:\temp\eventvwr.ps1:16 char:68
+ where-object { $_.timecreated -gt $date  -and $_.levelDisplayName - <<<< in "
Critical", "error", "warning" } | `
    + CategoryInfo          : ParserError: (:) [], ParseException
    + FullyQualifiedErrorId : ExpectedValueExpression

To Correct:



# PowerShell example which groups event then sorts in descending order.
Clear-Host

$logName = "System"

#get date
$dateCurrent = Get-Date

#For the Week
$NDays = -7
$dateNDaysAgo = $dateCurrent.AddDays($NDays)

$logLevel = @("Critical", "Warning", "Error")
$logLevelCritical = "Critical"
$logLevelWarning = "Warning"
$logLevelError = "Error"

Write-Host "Log Entries since $dateNDaysAgo"

Get-WinEvent -Logname $logName  | `
where-object {   ($_.timecreated -gt $date)  `
                 -and ( `
                       ($_.levelDisplayName -eq $logLevelCritical)  `
                   -or ($_.levelDisplayName -eq $logLevelWarning)   `
                   -or ($_.levelDisplayName -eq $logLevelError)     `
                      )  } | `
Group-Object ProviderName, levelDisplayName, ID | `
Sort-Object Count -descending | `
Format-Table Count, Name -auto

References

Event Log

WMI