Downloads:
2,657
Downloads of v 0.9.55:
1,196
Last Update:
14 Dec 2014
Package Maintainer(s):
Software Author(s):
- Glenn Sarti
Tags:
posh powershell puppet- Software Specific:
- Software Site
- Software License
- Package Specific:
- Possible Package Source
- Package outdated?
- Package broken?
- Contact Maintainers
- Contact Site Admins
- Software Vendor?
- Report Abuse
- Download
Posh Puppet Reports
- 1
- 2
- 3
0.9.55 | Updated: 14 Dec 2014
- Software Specific:
- Software Site
- Software License
- Package Specific:
- Possible Package Source
- Package outdated?
- Package broken?
- Contact Maintainers
- Contact Site Admins
- Software Vendor?
- Report Abuse
- Download
Downloads:
2,657
Downloads of v 0.9.55:
1,196
Maintainer(s):
Software Author(s):
- Glenn Sarti
Posh Puppet Reports 0.9.55
- 1
- 2
- 3
Some Checks Have Failed or Are Not Yet Complete
Not All Tests Have Passed
Deployment Method: Individual Install, Upgrade, & Uninstall
To install Posh Puppet Reports, run the following command from the command line or from PowerShell:
To upgrade Posh Puppet Reports, run the following command from the command line or from PowerShell:
To uninstall Posh Puppet Reports, run the following command from the command line or from PowerShell:
Deployment Method:
This applies to both open source and commercial editions of Chocolatey.
1. Enter Your Internal Repository Url
(this should look similar to https://community.chocolatey.org/api/v2/)
2. Setup Your Environment
1. Ensure you are set for organizational deployment
Please see the organizational deployment guide
2. Get the package into your environment
Option 1: Cached Package (Unreliable, Requires Internet - Same As Community)-
Open Source or Commercial:
- Proxy Repository - Create a proxy nuget repository on Nexus, Artifactory Pro, or a proxy Chocolatey repository on ProGet. Point your upstream to https://community.chocolatey.org/api/v2/. Packages cache on first access automatically. Make sure your choco clients are using your proxy repository as a source and NOT the default community repository. See source command for more information.
- You can also just download the package and push it to a repository Download
-
Open Source
-
Download the package:
Download - Follow manual internalization instructions
-
-
Package Internalizer (C4B)
-
Run: (additional options)
choco download poshpuppetreports --internalize --source=https://community.chocolatey.org/api/v2/
-
For package and dependencies run:
choco push --source="'INTERNAL REPO URL'"
- Automate package internalization
-
Run: (additional options)
3. Copy Your Script
choco upgrade poshpuppetreports -y --source="'INTERNAL REPO URL'" [other options]
See options you can pass to upgrade.
See best practices for scripting.
Add this to a PowerShell script or use a Batch script with tools and in places where you are calling directly to Chocolatey. If you are integrating, keep in mind enhanced exit codes.
If you do use a PowerShell script, use the following to ensure bad exit codes are shown as failures:
choco upgrade poshpuppetreports -y --source="'INTERNAL REPO URL'"
$exitCode = $LASTEXITCODE
Write-Verbose "Exit code was $exitCode"
$validExitCodes = @(0, 1605, 1614, 1641, 3010)
if ($validExitCodes -contains $exitCode) {
Exit 0
}
Exit $exitCode
- name: Install poshpuppetreports
win_chocolatey:
name: poshpuppetreports
version: '0.9.55'
source: INTERNAL REPO URL
state: present
See docs at https://docs.ansible.com/ansible/latest/modules/win_chocolatey_module.html.
chocolatey_package 'poshpuppetreports' do
action :install
source 'INTERNAL REPO URL'
version '0.9.55'
end
See docs at https://docs.chef.io/resource_chocolatey_package.html.
cChocoPackageInstaller poshpuppetreports
{
Name = "poshpuppetreports"
Version = "0.9.55"
Source = "INTERNAL REPO URL"
}
Requires cChoco DSC Resource. See docs at https://github.com/chocolatey/cChoco.
package { 'poshpuppetreports':
ensure => '0.9.55',
provider => 'chocolatey',
source => 'INTERNAL REPO URL',
}
Requires Puppet Chocolatey Provider module. See docs at https://forge.puppet.com/puppetlabs/chocolatey.
4. If applicable - Chocolatey configuration/installation
See infrastructure management matrix for Chocolatey configuration elements and examples.
This package was approved by moderator ferventcoder on 15 Dec 2014.
Powershell scripts to convert Puppet YAML reports into different formats (HTML, TeamCity events), and includes a GUI to convert reports on the fly
$packageName = 'poshpuppetreports' # arbitrary name for the package, used in messages
try {
$installDir = Join-Path (Join-Path $PSHome "Modules") "POSHPuppetReports"
# Remove the folder from the powershell modules directory
if (Test-Path $installDir) {
[void] (Remove-Item $installDir -Recurse -Confirm:$false -Force -ErrorAction 'Stop')
}
else
{
Write-Debug "Installation directory doesn't exist"
}
# Removing shortcuts for the reports into the "Start Menu"
$shortcutPath = ([Environment]::GetFolderPath('CommonStartMenu')) + '\POSH Puppet Reports\Report GUI.lnk'
if (Test-Path $shortcutPath) {
[void] (Remove-Item $shortcutPath -Recurse -Confirm:$false -Force -ErrorAction 'Stop')
}
# Remove the file assocication and command for YAML files...
$fileExtRegKey = "HKEY_LOCAL_MACHINE\SOFTWARE\Classes\.yaml"
# Create the file extension if it doesn't exist
if (Test-Path -Path "Registry::$($fileExtRegKey)") {
[string]$yamlFileClass = ""
try
{
$yamlFileClass = (Get-ItemProperty -Path "Registry::$($fileExtRegKey)").PSObject.Properties["(default)"].Value.ToString();
}
catch
{
$yamlFileClass = ""
}
if ($yamlFileClass -ne "") {
$fileAssocRegKey = "HKEY_LOCAL_MACHINE\SOFTWARE\Classes\$yamlFileClass"
[void](Remove-Item -Path "Registry::$($fileAssocRegKey)\Shell\OpenWithPOSHPuppetReportViewer\Command" -ErrorAction "Ignore" -Confirm:$false -Force)
[void](Remove-Item -Path "Registry::$($fileAssocRegKey)\Shell\OpenWithPOSHPuppetReportViewer" -ErrorAction "Ignore" -Confirm:$false -Force)
}
}
Write-ChocolateySuccess "$packageName"
} catch {
Write-ChocolateyFailure "$packageName" "$($_.Exception.Message)"
throw
}
function ConvertFrom-PuppetReport {
[cmdletBinding(SupportsShouldProcess=$false,ConfirmImpact='Low')]
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[string[]]$Report
,[Parameter(Mandatory=$true,ValueFromPipeline=$false)]
[string[]]$Transform
,[Parameter(Mandatory=$false,ValueFromPipeline=$false)]
[string]$TransformDir = ''
,[Parameter(Mandatory=$true,ValueFromPipeline=$false)]
[string]$OutputDir
,[Parameter(Mandatory=$false,ValueFromPipeline=$false)]
[switch]$OutputXML = $false
,[Parameter(Mandatory=$false,ValueFromPipeline=$false)]
[switch]$TeeToWriteHost = $false
)
Begin {
# References
# Report v3/4 Reference for Puppet 2.7.x and 3.x
# http://docs.puppetlabs.com/puppet/3/reference/format_report.html
# Fatal Sanity Checks
# Can't check for piped output until the Process section
if ($TransformDir -eq '') { $TransformDir = "$PSScriptRoot\..\transforms" }
if ($Transform -eq '') { Throw 'No transform was specified'; return; }
$Transform | % {
if (!(Test-Path "$TransformDir\$($_).xsl")) { Throw ('Transform file ' + $_ + '.xsl does not exist'); return; }
}
if ($OutputDir -ne '') {
if (!(Test-Path $OutputDir)) { Throw ('Output directory of ' + $OutputDir + ' does not exist'); return; }
}
}
Process {
# Somewhat fatal Sanity Checks
if ($Report -eq '') { Throw 'No puppet report file was specified'; return; }
if (!(Test-Path $Report)) { Throw ('Report file ' + $Report + ' does not exist'); return; }
# Process the report and transforms...
$yamlFile = $Report
try {
Write-Verbose "Reading $yamlFile ..."
$objYaml = Get-Yaml -FromFile $yamlFile -ErrorAction Stop
$xmlDoc = [xml]"<report />"
Write-Verbose "Creating Resource Status Summary XML..."
Write-ResourceStatusSummary $objYaml $xmlDoc
# TODO: Write out the Metric.Time table to determine the total time
Write-Verbose "Creating Resource Status XML..."
Write-ResourceStatus $objYaml $xmlDoc
if ($OutputXML) {
$filename = Join-Path -Path $OutputDir -ChildPath ( (Get-ChildItem $yamlFile).BaseName + '.xml')
Write-Verbose "Writing XML to $filename ..."
$xmlDoc.innerXml | Out-File $filename -Encoding ASCII -Force -Confirm:$false
}
$Transform | % {
$transformFile = "$TransformDir\$($_).xsl"
$filename = Join-Path -Path $OutputDir -ChildPath ( (Get-ChildItem $yamlFile).BaseName + '.' + $_)
Write-Verbose "Applying transform $transformFile , output to $filename ..."
[void] (Transform-XML -XMLDocument $xmlDoc -transformFilename $transformFile | Out-File $filename -Force -Confirm:$false )
if ($TeeToWriteHost) {
# TODO Write out the file content to Write-Host. Useful if the caller is trapping Stdout
}
Write-Output $filename
}
}
catch
{
Write-Verbose ("ERROR " + $_.ToString())
Throw $_
return ;
}
}
End {
}
}
# Import this modules functions etc.
Get-ChildItem -Path $PSScriptRoot | Unblock-File
Get-ChildItem -Path $PSScriptRoot\*.ps1 | ForEach-Object {
Write-Verbose "Importing $($_.Name)..."
. ($_.Fullname)
}
function Add-CastingFunctions($value) {
if ($PSVersionTable.PSVersion -ge "3.0") { return $value }
return Add-CastingFunctionsForPosh2($value)
}
function Add-CastingFunctionsForPosh2($value) {
return Add-Member -InputObject $value -Name ToInt `
-MemberType ScriptMethod -PassThru -Value `
{ [int] $this } |
Add-Member -Name ToLong `
-MemberType ScriptMethod -PassThru -Value `
{ [long] $this } |
Add-Member -Name ToDouble `
-MemberType ScriptMethod -PassThru -Value `
{ [double] $this } |
Add-Member -Name ToDecimal `
-MemberType ScriptMethod -PassThru -Value `
{ [decimal] $this } |
Add-Member -Name ToByte `
-MemberType ScriptMethod -PassThru -Value `
{ [byte] $this } |
Add-Member -Name ToBoolean `
-MemberType ScriptMethod -PassThru -Value `
{ [System.Boolean]::Parse($this) }
}
$pwd = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests", "")
. "$pwd\$sut"
if ($PSVersionTable.PSVersion -ge "3.0") { return }
Describe "when accessing a yaml scalar value of '5'" {
$patched = Add-CastingFunctionsForPosh2 ("5")
Context "and I do not attempt to cast it" {
It "returns a string" {
$patched.GetType().Name | Should Be "string"
}
}
Context "and I attempt to cast it as an integer" {
It "returns a value that is of type integer" {
$patched.ToInt().GetType().Name | Should Be "Int32"
}
}
Context "and I attempt to cast it as a long" {
It "returns a value that is of type long" {
$patched.ToLong().GetType().Name | Should Be "Int64"
}
}
Context "and I attempt to cast it as a double" {
It "returns a value that is a double" {
$patched.ToDouble().GetType().Name | Should Be "Double"
}
}
Context "and I attempt to cast it as a decimal" {
It "returns a value that is a decimal" {
$patched.ToDecimal().GetType().Name | Should Be "Decimal"
}
}
Context "and I attempt to cast it as a byte" {
It "returns a value that is a byte" {
$patched.ToByte().GetType().Name | Should Be "Byte"
}
}
}
Describe "when accessing boolean values" {
Context "and I'm attempting to cast the value 'true'" {
$patched = Add-CastingFunctionsForPosh2("true")
It "return a value that is a boolean" {
$patched.ToBoolean().GetType().Name | Should Be "Boolean"
}
It "returns a value that is true" {
$patched.ToBoolean() | Should Be $true
}
}
Context "and I'm attempting to cast the value 'false'" {
$patched = Add-CastingFunctionsForPosh2("false")
It "return a value that is a boolean" {
$patched.ToBoolean().GetType().Name | Should Be "Boolean"
}
It "returns a value that is false" {
$patched.ToBoolean() | Should Be $false
}
}
}
function Shadow-Copy($file, $shadowPath = "$($env:TEMP)\poweryaml\shadow") {
if (-not (Test-Path $shadowPath ) ) {
New-Item $shadowPath -ItemType directory | Out-Null
}
try {
Copy-Item $file $shadowPath -Force -ErrorAction SilentlyContinue
} catch {
"Attempted to write over locked file, continuing..." | Write-Debug
}
$fileName = (Get-Item $file).Name
"$shadowPath\$fileName"
}
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests.", ".")
. "$here\$sut"
Describe "Shadow-Copy" {
Setup -File "testfile"
$isolatedShadowPath = "$TestDrive\poweryaml\shadow"
It "copies a file to a transient location" {
Shadow-Copy -File "$TestDrive\testfile" -ShadowPath $isolatedShadowPath
"$isolatedShadowPath\testfile" | Should Exist
}
It "returns a path to the shadow copied file" {
$shadow = Shadow-Copy -File "$TestDrive\testfile" -ShadowPath $isolatedShadowPath
$shadow | Should Be "$isolatedShadowPath\testfile"
}
It "does not complain if trying to overwrite locked files" {
$file = [System.io.File]::Open("$isolatedShadowPath\testfile", 'Open', 'Read', 'None')
$shadow = Shadow-Copy -File "$TestDrive\testfile" -ShadowPath $isolatedShadowPath
$file.Close()
"made it here, therefore no errors" | Should Be "made it here, therefore no errors"
}
}
function Validate-File([string] $file) {
$file_exists = Test-Path $file
if (-not $file_exists) {
"ERROR: '$file' does not exist" | Write-Error
return $false
}
$lines_in_file = [System.IO.File]::ReadAllLines($file)
$line_tab_detected = Detect-Tab $lines_in_file
if ($line_tab_detected -gt 0) {
"ERROR in '$file'`nTAB detected on line $line_tab_detected" | Write-Error
return $false
}
return $true
}
function Detect-Tab($lines) {
for($i = 0; $i -lt $lines.count; $i++) {
[string] $line = $lines[$i]
if ($line.Contains("`t")) {
return ($i + 1)
}
}
return 0
}
$pwd = Split-Path -Parent $MyInvocation.MyCommand.Path
$sut = (Split-Path -Leaf $MyInvocation.MyCommand.Path).Replace(".Tests", "")
. "$pwd\$sut"
Describe "Detect-Tab" {
It "should return the line number the first TAB character is found on" {
$lines = @()
$lines += "valide: yaml"
$lines += " `t "
$line_number_tab_is_in = 2
$result = Detect-Tab $lines
$result | Should Be $line_number_tab_is_in
}
It "should return 0 if no TAB character is found in text" {
$result = Detect-Tab " "
$result | Should Be 0
}
}
Describe "Validate-File" {
Setup -File "exists.yml"
It "should return false if a file does not exist" {
$result = Validate-File "some non existent file"
$result | Should Be $false
}
It "should return true for a file that does exist and does not contain a TAB character" {
$result = Validate-File "$TestDrive\exists.yml"
$result | Should Be $true
}
}
Describe "Validating a file with tabs" {
Setup -File "bad.yml" " `t "
It "should return false" {
Trap [Exception] {
Write-Host caught error
}
$result = Validate-File "$TestDrive\bad.yml"
$result | Should Be $false
}
}
function Load-YamlDotNetLibraries([string] $dllPath, $shadowPath = "$($env:TEMP)\poweryaml\shadow") {
gci $dllPath | % {
$shadow = Shadow-Copy -File $_.FullName -ShadowPath $shadowPath
[Reflection.Assembly]::LoadFrom($shadow)
} | Out-Null
}
function Get-YamlStream([string] $file) {
$streamReader = [System.IO.File]::OpenText($file)
$yamlStream = New-Object YamlDotNet.RepresentationModel.YamlStream
$yamlStream.Load([System.IO.TextReader] $streamReader)
$streamReader.Close()
return $yamlStream
}
function Get-YamlDocument([string] $file) {
$yamlStream = Get-YamlStream $file
$document = $yamlStream.Documents[0]
return $document
}
function Get-YamlDocumentFromString([string] $yamlString) {
$stringReader = new-object System.IO.StringReader($yamlString)
$yamlStream = New-Object YamlDotNet.RepresentationModel.YamlStream
$yamlStream.Load([System.IO.TextReader] $stringReader)
$document = $yamlStream.Documents[0]
return $document
}
function Explode-Node($node) {
if ($node.GetType().Name -eq "YamlScalarNode") {
return Convert-YamlScalarNodeToValue $node
} elseif ($node.GetType().Name -eq "YamlMappingNode") {
return Convert-YamlMappingNodeToHash $node
} elseif ($node.GetType().Name -eq "YamlSequenceNode") {
return Convert-YamlSequenceNodeToList $node
}
}
function Convert-YamlScalarNodeToValue($node) {
return Add-CastingFunctions($node.Value)
}
function Convert-YamlMappingNodeToHash($node) {
$hash = @{}
$yamlNodes = $node.Children
foreach($key in $yamlNodes.Keys) {
$hash[$key.Value] = Explode-Node $yamlNodes[$key]
}
return $hash
}
function Convert-YamlSequenceNodeToList($node) {
$list = @()
$yamlNodes = $node.Children
foreach($yamlNode in $yamlNodes) {
$list += Explode-Node $yamlNode
}
return $list
}
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
. "$here\Casting.ps1"
. "$here\Shadow-Copy.ps1"
. "$here\YamlDotNet-Integration.ps1"
$libDir = "$here\..\Libs"
Describe "Load-YamlDotNetLibraries" {
Setup -Dir "Libs"
Copy-Item "$libDir\*.dll" "$TestDrive\Libs"
It "loads assemblies in a way that the dll's can be deleted after loading" {
$testLibDir = "$TestDrive\Libs"
Load-YamlDotNetLibraries $testLibDir
Remove-Item $testLibDir -Recurse
$testLibDir | Should Not Exist
}
}
#Note The rest of the tests are dependent on the above test passing :-(
Describe "Convert-YamlScalarNodeToValue" {
It "takes a YamlScalar and converts it to a value type" {
$node = New-Object YamlDotNet.RepresentationModel.YamlScalarNode 5
$result = Convert-YamlScalarNodeToValue $node
$result | Should Be 5
}
}
Describe "Convert-YamlSequenceNodeToList" {
It "taks a YamlSequence and converts it to an array" {
$yaml = Get-YamlDocumentFromString "---`n- single item`n- second item"
$result = Convert-YamlSequenceNodeToList $yaml.RootNode
$result.count | Should Be 2
}
}
Describe "Convert-YamlMappingNodeToHash" {
It "takes a YamlMappingNode and converts it to a hash" {
$yaml = Get-YamlDocumentFromString "---`nkey1: value1`nkey2: value2"
$result = Convert-YamlMappingNodeToHash $yaml.RootNode
$result.keys.count | Should Be 2
}
}
Describe "Get-YamlDocumentFromString" {
It "will return a YamlDocument if given proper YAML" {
$document = Get-YamlDocumentFromString "---"
$document.GetType().Name | Should Be "YamlDocument"
}
}
if (Test-Path "build") {
Remove-Item "build" -Recurse -Force
}
mkdir build
vendor\tools\nuget pack PowerYaml.nuspec -OutputDirectory build
. $PSScriptRoot\Functions\Casting.ps1
. $PSScriptRoot\Functions\Shadow-Copy.ps1
. $PSScriptRoot\Functions\YamlDotNet-Integration.ps1
. $PSScriptRoot\Functions\Validator-Functions.ps1
<#
.Synopsis
Returns an object that can be dot navigated
.Parameter FromFile
File reference to a yaml document
.Parameter FromString
Yaml string to be converted
#>
function Get-Yaml([string] $FromString = "", [string] $FromFile = "") {
if ($FromString -ne "") {
$yaml = Get-YamlDocumentFromString $FromString
} elseif ($FromFile -ne "") {
if ((Validate-File $FromFile)) {
$yaml = Get-YamlDocument -file $FromFile
}
}
return Explode-Node $yaml.RootNode
}
Load-YamlDotNetLibraries (Join-Path $PSScriptRoot -ChildPath "Libs")
Export-ModuleMember -Function Get-Yaml
$here = Split-Path -Parent $MyInvocation.MyCommand.Path
Import-Module $here\PowerYaml.psm1 -Force
Describe "PoweYaml when parsing strings" {
It "Obtains a HashTable given a yaml hash" {
$yaml = Get-Yaml -FromString "key: value"
$yaml.GetType().Name | Should Be "HashTable"
}
It "Obtains an Object[] given a yaml array" {
$yaml = Get-Yaml -FromString "- test`n- test2"
$yaml.GetType().Name | Should Be "Object[]"
}
}
Describe "Using Power Yaml to read a file" {
Setup -File "sample.yml" "test: value"
It "Can read the file and get the value" {
$yaml = Get-Yaml -FromFile "$TestDrive\sample.yml"
$yaml.test | Should Be "value"
}
}
Describe "Using Power Yaml to convert integer scalars" {
if ($PSVersionTable.PSVersion -ge "3.0") { return }
It "Obtains an int given an integer value" {
$yaml = Get-Yaml -FromString "key: 5"
$yaml.key.ToInt().GetType().Name | Should Be "Int32"
}
}
Remove-Module PowerYaml
PowerYaml
=========
PowerYaml is a wrapper around [Yaml.Net][] library which is the best .Net Yaml parser I've found so far.
Sample
------
Paste the following into a *sample.yml* file
parent:
child:
a: a value
b: b value
c: c value
child2:
key4: value 4
key5: value 5
And here's the parsing of the above yaml
PS C:\dev\PowerYaml> Import-Module .\PowerYaml.psm1
PS C:\dev\PowerYaml> $yaml = Get-Yaml -FromFile (Resolve-Path .\sample.yml)
PS C:\dev\PowerYaml> $yaml.parent.child
Name Value
---- -----
a a value
b b value
c c value
[Yaml.Net]: http://sourceforge.net/projects/yamldotnet/ "Yaml.Net"
function Get-WPFControl {
[cmdletBinding(SupportsShouldProcess=$false,ConfirmImpact='Low')]
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$true)]
[string]$ControlName
,[Parameter(Mandatory=$true,ValueFromPipeline=$false)]
[System.Windows.Window]$Window
)
Process {
Write-Output $Window.FindName($ControlName)
}
}
Function Invoke-ConvertReport() {
[cmdletBinding(SupportsShouldProcess=$false,ConfirmImpact='Low')]
param(
[Parameter(Mandatory=$true,ValueFromPipeline=$false)]
[string]$YAMLFilename
,[Parameter(Mandatory=$true,ValueFromPipeline=$false)]
[string]$TransformFilename
,[Parameter(Mandatory=$true,ValueFromPipeline=$false)]
[string]$TransformParentPath
,[Parameter(Mandatory=$false,ValueFromPipeline=$false)]
[object]$WPFWindow = $null
)
Process {
$outputDir = ($Env:Temp)
$resultContent = (ConvertFrom-PuppetReport -Report $YAMLFilename -Transform $TransformFilename -TransformDir $TransformParentPath -OutputDir $outputDir -Verbose:($VerbosePreference -eq 'Continue'))
$fileContent = [IO.File]::ReadAllText($resultContent)
if ($TransformFilename.EndsWith('.stdout')) {
$fileContent = "<html><body><pre>" + $fileContent + "</pre></body></html>"
}
if ($WPFWindow -ne $null) {
(Get-WPFControl 'reportBrowser' -Window $WPFWindow).NavigateToString($fileContent)
}
Write-Verbose "Removing temporary file $resultContent ..."
[void](Remove-Item -Path $resultContent -Force -Confirm:$false)
}
}
Function Invoke-ShowMainWindow() {
[cmdletBinding(SupportsShouldProcess=$false,ConfirmImpact='Low')]
param(
[Parameter(Mandatory=$false,ValueFromPipeline=$false)]
[AllowEmptyString()]
[string]$autoloadTransform = ""
,[Parameter(Mandatory=$false,ValueFromPipeline=$false)]
[AllowEmptyString()]
[string]$AutoloadReport = ""
)
Process {
# Load XAML from the external file
Write-Verbose "Loading the window XAML..."
[xml]$xaml = (Get-Content (Join-Path -Path $global:ScriptDirectory -ChildPath 'reportgui.xaml'))
# Build the GUI
Write-Verbose "Parsing the window XAML..."
$reader = (New-Object System.Xml.XmlNodeReader $xaml)
$thisWindow = [Windows.Markup.XamlReader]::Load($reader)
# Wire up the XAML
Write-Verbose "Adding XAML event handlers..."
(Get-WPFControl 'buttonBrowseReportPath' -Window $thisWindow).Add_Click({
# TODO Perhaps create a wizard to enter a server name and automatically create a UNC to the default puppet path? \\<server>\c$\ProgramData....
$dialogWindow = New-Object System.Windows.Forms.FolderBrowserDialog -Property @{
SelectedPath = (Get-WPFControl 'textReportPath' -Window $thisWindow).Text;
ShowNewFolderButton = $false;
Description = "Browse for Puppet Report path";
}
$result = $dialogWindow.ShowDialog()
if ($result.ToString() -eq 'Ok') {
(Get-WPFControl 'textReportPath' -Window $thisWindow).Text = $dialogWindow.SelectedPath
}
})
(Get-WPFControl 'buttonConnect' -Window $thisWindow).Add_Click({
$location = ((Get-WPFControl 'textReportPath' -Window $thisWindow).Text)
if (Test-Path -Path $location) {
# Remove the PuppetReports Drive if it exists...
(Get-PSDrive 'PuppetReports' -ErrorAction 'SilentlyContinue' | Remove-PSDrive)
# Create a PuppetReports: drive
[void](New-PSDrive -Name 'PuppetReports' -PSProvider FileSystem -Root $location -Scope Script)
# Populate the list box
Write-Verbose 'Populating the report list...'
[xml]$xmlDoc = '<reports xmlns=""></reports>'
Get-Item -Path 'PuppetReports:\*.yaml' | Sort-Object ($_.LastWriteTime) -Descending | % {
$xmlNode = $xmlDoc.CreateElement('report')
$xmlNode.SetAttribute('name',$_.name.ToString())
$xmlNode.SetAttribute('datemodified',($_.LastWriteTime.ToString('dd MMM yyyy HH:mm:ss')))
$xmlNode.innerText = ($_.FullName)
$xmlDoc.reports.AppendChild($xmlNode)
}
# Write the xml document to the XAML for databinding
(Get-WPFControl 'xmlReportList' -Window $thisWindow).Document = $xmlDoc
Write-Verbose 'Expanding the report list'
# Expand the Reports List
(Get-WPFControl 'expandReportList' -Window $thisWindow).IsExpanded = $true
# Contract the Report Location
(Get-WPFControl 'expandReportLocation' -Window $thisWindow).IsExpanded = $false
$thisWindow.Title = "Puppet Report Viewer - $location"
}
else
{
[void] ([System.Windows.MessageBox]::Show('The report path does not exist','Error','Ok','Information'))
return
}
})
(Get-WPFControl 'listReports' -Window $thisWindow).Add_MouseDoubleClick({
param($sender,$e)
# Parse the control tree looking for the descendant ListViewItem
$originalSource = [System.Windows.DependencyObject]$e.OriginalSource;
while ( ($originalSource -ne $null) -and ($originalSource.GetType().ToString() -ne 'System.Windows.Controls.ListViewItem') ) {
$originalSource = [System.Windows.Media.VisualTreeHelper]::GetParent($originalSource)
}
if ($originalSource -eq $null) { return; }
# Get the data context (XMLElement)
$dc = $originalSource.DataContext
$reportName = ($dc."#text")
# Get the template name
$index = (Get-WPFControl 'comboReportList' -Window $thisWindow).selectedIndex
if ($index -eq -1) { # No transform has been selected
[void] ([System.Windows.MessageBox]::Show('Please select a Report Type to use','Error','Ok','Information'))
return;
}
$transformName = (Get-WPFControl 'comboReportList' -Window $thisWindow).Items[$index]
# Actually do the conversion
Write-Verbose "Parsing report $($reportName) with transform $($transformName)..."
Invoke-ConvertReport -YAMLFilename $reportName -TransformFilename $transformName -TransformParentPath $transformPath -WPFWindow $thisWindow
Write-Verbose "Conversion finished..."
})
# Populate XAML items
Write-Verbose "Populating XAML controls..."
Get-ChildItem -Path $transformPath | % {
$transfromName = ($_.Name) -replace '.xsl',''
[void]( (Get-WPFControl 'comboReportList' -Window $thisWindow).Items.Add($transfromName) )
}
# Show the readme or autoload a report if specified
if ( ($autoloadReport -ne "") -and ($autoloadTransform -ne "") )
{
Write-Verbose "Converting the report $($autoloadReport) with transform $($autoloadTransform) specified on the command line..."
Invoke-ConvertReport -YAMLFilename $autoloadReport -TransformFilename $autoloadTransform -TransformParentPath $transformPath -WPFWindow $thisWindow
Write-Verbose "Conversion finished..."
# Set the UI to specified report path and transform name
(Get-WPFControl 'textReportPath' -Window $thisWindow).Text = (Split-Path -Path $autoloadReport -Parent)
$comboBox = (Get-WPFControl 'comboReportList' -Window $thisWindow)
for($index = 0; $index -lt $comboBox.Items.Count; $index++) {
if ($comboBox.Items[$index] -eq $autoloadTransform) {
$comboBox.SelectedIndex = $index
break
}
}
}
else
{
$readMe = $global:ScriptDirectory + '\reportgui.readme.html'
if (Test-Path -Path $readMe) {
Write-Verbose "Displaying ReadMe..."
(Get-WPFControl 'reportBrowser' -Window $thisWindow).NavigateToString( ([IO.File]::ReadAllText($readMe) ) )
}
}
# Show the GUI
Write-Verbose "Showing the window..."
[void]($thisWindow.ShowDialog())
Write-Verbose "Cleanup..."
$thisWindow.Close()
$thisWindow = $null
}
}
Function Invoke-ShowSelectTransformWindow() {
[cmdletBinding(SupportsShouldProcess=$false,ConfirmImpact='Low')]
param(
)
Process {
# Load XAML from the external file
Write-Verbose "Loading the Select Transform window XAML..."
[xml]$xaml = (Get-Content (Join-Path -Path $global:ScriptDirectory -ChildPath 'selecttransform.xaml'))
# Build the GUI
Write-Verbose "Parsing the window XAML..."
$reader = (New-Object System.Xml.XmlNodeReader $xaml)
$thisWindow = [Windows.Markup.XamlReader]::Load($reader)
# Wire up the XAML
(Get-WPFControl 'listTransforms' -Window $thisWindow).Add_MouseDoubleClick({
param($sender,$e)
# Parse the control tree looking for the descendant ListViewItem
$originalSource = [System.Windows.DependencyObject]$e.OriginalSource;
while ( ($originalSource -ne $null) -and ($originalSource.GetType().ToString() -ne 'System.Windows.Controls.ListViewItem') ) {
$originalSource = [System.Windows.Media.VisualTreeHelper]::GetParent($originalSource)
}
if ($originalSource -eq $null) { return; }
$thisWindow.DialogResult = "ok"
})
(Get-WPFControl 'buttonUseTransform' -Window $thisWindow).Add_Click({
$listView = (Get-WPFControl 'listTransforms' -Window $thisWindow)
if ($listView.SelectedItem -eq $null) {
[void] ([System.Windows.MessageBox]::Show('Please select a transform from the list','Error','Ok','Information'))
return
}
$thisWindow.DialogResult = "ok"
})
# Populate XAML items
[xml]$xmlDoc = '<transforms xmlns=""></transforms>'
Get-ChildItem -Path $transformPath | Sort-Object ($_.Name) | % {
$transfromName = ($_.Name) -replace '.xsl',''
$index = $transfromName.LastIndexOf('.')
if ($index -gt -1)
{
$typeText = $transfromName.SubString($index + 1, $transfromName.Length - $index - 1)
if ($typeText -eq 'html') { $typeText = 'HTML' }
if ($typeText -eq 'stdout') { $typeText = 'Text' }
}
else
{
$typeText = "Unknown"
}
$xmlNode = $xmlDoc.CreateElement('transform')
$xmlNode.SetAttribute('transformname',$transfromName)
$xmlNode.SetAttribute('typetext',$typeText)
$xmlNode.innerText = ($transfromName)
$xmlDoc.documentElement.AppendChild($xmlNode)
} | Out-Null
(Get-WPFControl 'xmlTransformList' -Window $thisWindow).Document = $xmlDoc
# Show the GUI
Write-Verbose "Showing the window..."
[string]$selectedTransformName = ""
[void]($thisWindow.ShowDialog())
if ($thisWindow.dialogResult) {
$listView = (Get-WPFControl 'listTransforms' -Window $thisWindow)
$xmlElement = $listView.SelectedItem
if ($xmlElement -ne $null) {
$selectedTransformName = $xmlElement.transformName
Write-Verbose "Selected transform from the dialog is $selectedTransformName"
}
}
Write-Verbose "Cleanup..."
[void] ($thisWindow.Close())
$thisWindow = $null
Write-Output $selectedTransformName
}
}
param([string]$Report = '', [string]$Transform = '')
# Setup script defaults
$ErrorActionPreference = "Stop"
$VerbosePreference = "Continue"
# Bootstrap
function Get-ScriptDirectory
{
$Invocation = (Get-Variable MyInvocation -Scope 1).Value
$global:ScriptDirectory = (Split-Path ($Invocation.MyCommand.Path))
$global:ScriptDirectory
}
[void] (Get-ScriptDirectory)
$transformPath = (Join-Path -Path $global:ScriptDirectory -ChildPath '..\transforms')
#Load Required Assemblies
Write-Verbose 'Loading WPF assemblies'
Add-Type �assemblyName PresentationFramework
Add-Type �assemblyName PresentationCore
Add-Type �assemblyName WindowsBase
Write-Verbose 'Loading Windows Forms assemblies'
Add-Type -AssemblyName System.Windows.Forms
Write-Verbose 'Loading the POSHPuppetReports module'
Import-Module "$PSScriptRoot\..\POSHPuppetReports.psd1"
# Check the command line
$cmdLineError = ""
$autoloadReport = ""
$autoloadTransform = ""
if ($Report -ne '') {
Write-Verbose "Report path was specified on the command line"
if (!(Test-Path -Path $Report)) {
Write-Verbose "Report does not exist"
$cmdLineError += "The specified report does not exist`n`r"
}
else
{
Write-Verbose "Report exists"
$autoloadReport = $Report
}
}
if ($Transform -ne '') {
Write-Verbose "Transform name was specified on the command line"
$TransformFile = (Join-Path -Path $transformPath -ChildPath ($Transform + ".xsl"))
if (!(Test-Path -Path $TransformFile)) {
Write-Verbose "Transform does not exist"
$cmdLineError += "The specified transform does not exist`n`r"
}
else
{
Write-Verbose "Transform exists"
$autoloadTransform = $Transform
}
}
if ($cmdLineError -ne '') {
[void] ([System.Windows.MessageBox]::Show($cmdLineError,'Error','Ok','Information'))
}
# Load other PS1 files
Get-ChildItem -Path $global:ScriptDirectory | Where-Object { ($_.Name -imatch '\.ps1$') -and ($_.Name -ne 'reportgui.ps1') } | % {
Write-Verbose "Importing $($_.Name)..."
. ($_.Fullname)
}
if (($autoloadTransform -eq "") -and ($autoloadReport -ne "")) {
# Passed in only the report name. Prompt for the transform name
Write-Verbose "Report name was passed in the command line but no transform. Prompting for which transform to use..."
$autoloadTransform = Invoke-ShowSelectTransformWindow
Write-Verbose "Selected transform is [$autoloadTransform]"
}
Invoke-ShowMainWindow -AutoloadTransform $autoloadTransform -AutoloadReport $autoloadReport
function Transform-XML($xmlDocument, $transformFilename) {
$xmlContentReader = ([System.Xml.XmlReader]::Create( (New-Object System.IO.StringReader($xmlDocument.innerXML))))
$StyleSheet = New-Object System.Xml.Xsl.XslCompiledTransform
$StyleSheet.Load($transformFile)
$stringWriter = New-Object System.IO.StringWriter
$XmlWriter = New-Object System.XMl.XmlTextWriter $StringWriter
$StyleSheet.Transform( [System.Xml.XmlReader]$xmlContentReader, [System.Xml.XmlWriter]$XmlWriter)
Write-Output $stringWriter.ToString()
}
function Write-HashTableToXML($attrName, $attrValue, $rootNode) {
$xmlNode = $rootNode.OwnerDocument.createElement($attrName)
if ($attrValue -ne $null) {
switch ($attrValue.GetType().ToString()) {
'System.String' {
# Special property. Convert it to ms as well
if ($attrName -eq 'evaluation_time') {
$xmlMSnode = $rootNode.OwnerDocument.createElement($attrName + '_ms')
$xmlMSnode.innerText = [int](([float]$attrValue)*1000)
[void]($rootNode.appendChild($xmlMSnode))
}
$xmlNode.innerText = $attrValue;
break ;
}
'System.Object[]' {
if ( ($attrValue[0]).GetType().ToString() -eq 'System.Collections.HashTable' ) {
$attrValue | % { Write-HashTableToXML $attrName $_ $xmlNode }
} else {
$xmlNode.innerText = $attrValue;
}
break ;
}
'System.Collections.Hashtable' { $attrValue.Keys | % { Write-HashTableToXML $_ $attrValue[$_] $xmlNode }; break ; }
default { $xmlNode.innerText = ('Unknown type ' + $attrValue.GetType().ToString()); break ; }
}
}
[void]($rootNode.appendChild($xmlNode))
}
function Write-ResourceStatus($objYaml, $xmlDoc) {
$resourcesNode = $xmlDoc.createElement('resources')
$objYaml.resource_statuses.Keys | % {
$resourceNode = $xmlDoc.createElement('resource')
[void]($resourceNode.SetAttribute('name',$_))
$resource = $objYaml.resource_statuses[$_]
$resource.Keys | % {
$eventsObject = $resource[$_]
if ($_ -eq 'events')
{
# The events resource is special as it can come in as null, an array or hashtable. Need to tailor the XML rendering based on object type
$eventsNode = $xmlDoc.createElement('events')
if ($eventsObject -ne $null) {
switch ($eventsObject.GetType().ToString() ) {
"System.Collections.Hashtable" {
Write-HashTableToXML 'event' $eventsObject $eventsNode
break;
}
"System.Object[]" {
$eventsObject | % {
Write-HashTableToXML 'event' $_ $eventsNode
}
break;
}
default { Throw "Write-ResourceStatus: Unknown object type $($eventsObject.GetType().ToString())"; return $null; }
}
}
[void]($resourceNode.AppendChild($eventsNode))
}
else
{
Write-HashTableToXML $_ $eventsObject $resourceNode
}
}
[void]($resourcesNode.AppendChild($resourceNode))
}
[void]($xmlDoc.DocumentElement.AppendChild($resourcesNode))
}
function Write-ResourceStatusSummary($objYaml, $xmlDoc) {
$reportInfoNode = $xmlDoc.createElement('reportinformation')
$node = $xmlDoc.createElement('host'); $node.innerText = $objYaml.host; [void]($reportInfoNode.appendChild($node))
$node = $xmlDoc.createElement('time'); $node.innerText = $objYaml.time; [void]($reportInfoNode.appendChild($node))
$node = $xmlDoc.createElement('reportformat'); $node.innerText = $objYaml.report_format; [void]($reportInfoNode.appendChild($node))
$node = $xmlDoc.createElement('puppetversion'); $node.innerText = $objYaml.puppet_version; [void]($reportInfoNode.appendChild($node))
$node = $xmlDoc.createElement('status'); $node.innerText = $objYaml.status; [void]($reportInfoNode.appendChild($node))
$node = $xmlDoc.createElement('environment'); $node.innerText = $objYaml.environment; [void]($reportInfoNode.appendChild($node))
[void]($xmlDoc.DocumentElement.appendChild($reportInfoNode))
$statuses = @{}
$resourceMetrics = $objYaml.metrics['resources'].values
$total = 0
for($index = $resourceMetrics.GetLowerBound(0); $index -lt $resourceMetrics.GetUpperBound(0); $index = $index + 3) {
if ($resourceMetrics[$index] -eq 'total')
{
$total = $resourceMetrics[$index + 2]
}
else
{
$statusInfo = @{}
$statusInfo['count'] = $resourceMetrics[$index + 2]
$statusInfo['id'] = $resourceMetrics[$index]
$statuses[$resourceMetrics[$index + 1]] = $statusInfo
}
}
$statusInfo = @{}
$summaryNode = $xmlDoc.createElement('resourcesummary')
[void]($summaryNode.SetAttribute('total',$total))
$statuses.Keys | ForEach-Object {
$node = $xmlDoc.createElement('status')
$node.SetAttribute('name',$_)
$node.SetAttribute('id',$statuses[$_].id)
$node.SetAttribute('count',$statuses[$_].count)
if ($total -gt 0)
{ $node.SetAttribute('percent',[int](($statuses[$_].count / $total)*100)) }
else
{ $node.SetAttribute('percent',0) }
[void]($summaryNode.AppendChild($node))
}
[void]($xmlDoc.DocumentElement.AppendChild($summaryNode))
}
Log in or click on link to see number of positives.
- YamlDotNet.Configuration.dll (fd842329e31c) - ## / 54
- YamlDotNet.Converters.dll (23dd69b6043d) - ## / 57
- YamlDotNet.Core.dll (bbb2783aa136) - ## / 57
- YamlDotNet.RepresentationModel.dll (fb6bd421ca71) - ## / 57
- poshpuppetreports.0.9.55.nupkg (371339ad8881) - ## / 56
- NuGet.exe (ad2f67420e1b) - ## / 55
In cases where actual malware is found, the packages are subject to removal. Software sometimes has false positives. Moderators do not necessarily validate the safety of the underlying software, only that a package retrieves software from the official distribution point and/or validate embedded software against official distribution point (where distribution rights allow redistribution).
Chocolatey Pro provides runtime protection from possible malware.
Add to Builder | Version | Downloads | Last Updated | Status |
---|---|---|---|---|
Posh Puppet Reports 0.9.55 | 1196 | Sunday, December 14, 2014 | Approved | |
Posh Puppet Reports 0.9.53 | 531 | Saturday, November 8, 2014 | Approved | |
Posh Puppet Reports 0.9.51 | 493 | Saturday, September 27, 2014 | Unknown | |
Posh Puppet Reports 0.9.47 | 437 | Sunday, September 14, 2014 | Unknown |
Full list of changes are available on GitHub; https://github.com/glennsarti/Puppet-Reports-in-Powershell/commits/master
Version 0.9.55
BUG FIXES:
- Major - The PowerYAML library was not being copied during the build process so this project would fail to run. Changed build batch file to copy PowerYAML if it doesn't already exist
Version 0.9.53
BUG FIXES:
- Minor - Refactored code so that each function is in its own file.
IMPROVEMENTS:
- Added context menu to open YAML files in the puppet report viewer.
- If you call the ReportGUI with only a puppet report, the user is prompted to select a transform to use.
- Added the ability to pass command line parameters to ReportGUI.CMD.
Version 0.9.51
BUG FIXES:
- Fix - Incorrectly thought the resource status were mutually exclusive however a resource can be counted as both out-of-sync and changed. Removed this logic for the moment until I can come up with a better definition of unchanged
- Fix - The events resource is special as it can come in as null, an array or hashtable. I changed the rendering based on the object type. So now there will always be one 'events' xml node with zero or more 'event' nodes as children. This makes the stylesheet much easier to write and makes more sense in the long run.
IMPROVEMENTS:
- Added better event output to the stylesheet. Failed resources are now coloured red.
- Added creating a shortcut called "Puppet Report GUI" to the 'Start Menu'. This functionality only works in .Net Framework 4.0 or above for the moment.
This package has no dependencies.
Ground Rules:
- This discussion is only about Posh Puppet Reports and the Posh Puppet Reports package. If you have feedback for Chocolatey, please contact the Google Group.
- This discussion will carry over multiple versions. If you have a comment about a particular version, please note that in your comments.
- The maintainers of this Chocolatey Package will be notified about new comments that are posted to this Disqus thread, however, it is NOT a guarantee that you will get a response. If you do not hear back from the maintainers after posting a message below, please follow up by using the link on the left side of this page or follow this link to contact maintainers. If you still hear nothing back, please follow the package triage process.
- Tell us what you love about the package or Posh Puppet Reports, or tell us what needs improvement.
- Share your experiences with the package, or extra configuration or gotchas that you've found.
- If you use a url, the comment will be flagged for moderation until you've been whitelisted. Disqus moderated comments are approved on a weekly schedule if not sooner. It could take between 1-5 days for your comment to show up.