Created
February 25, 2015 00:02
-
-
Save vors/bc85f24f7c10d97e28e3 to your computer and use it in GitHub Desktop.
Script Analyzer sample 1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<# | |
.SYNOPSIS | |
You should never use Write-Host to create any script output whatsoever. | |
.DESCRIPTION | |
It is generally accepted that you should never use Write-Host to create any script output whatsoever, unless your script (or function, or whatever) uses the Show verb (as in, Show-Performance). | |
That verb explicitly means “show on the screen, with no other possibilities.” Like Show-Command. | |
To fix a violation of this rule, please replace Write-Host with Write-Output in most scenarios. | |
.EXAMPLE | |
Test-WriteHost -CommandAst $CommandAst | |
.INPUTS | |
[System.Management.Automation.Language.CommandAst] | |
.OUTPUTS | |
[PSCustomObject[]] | |
.NOTES | |
Reference: Output, The Community Book of PowerShell Practices. | |
#> | |
function Test-WriteHost | |
{ | |
[CmdletBinding()] | |
[OutputType([PSCustomObject[]])] | |
Param | |
( | |
[Parameter(Mandatory = $true)] | |
[ValidateNotNullOrEmpty()] | |
[System.Management.Automation.Language.CommandAst] | |
$CommandAst | |
) | |
Process | |
{ | |
try | |
{ | |
$commandName = $CommandAst.GetCommandName() | |
# Checks command name, if the command name matches Write-Host or | |
# user-defined aliases, this rule is triggered. | |
if ($null -ne $commandName) | |
{ | |
$alias = (Get-Alias -Definition "Write-Host" -ErrorAction SilentlyContinue).Name | |
if (($commandName -eq "Write-Host") -or | |
($alias -eq $commandName)) | |
{ | |
[PSCustomObject]@{Message = "Avoid Using Write-Host"; | |
Extent = $CommandAst.Extent; | |
RuleName = $PSCmdlet.MyInvocation.InvocationName; | |
Severity = "Warning"} | |
} | |
} | |
} | |
catch | |
{ | |
$PSCmdlet.ThrowTerminatingError($PSItem) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment