Cmdlet output

To properly denote the output of your cmdlet, it is recommended to set the OutputType accordingly. This is, first and foremost, helpful to support IntelliSense and tab completion for the objects that you return:

function Get-ContosoFile
{
[CmdletBinding()]
[OutputType('System.IO.FileInfo')]
param
(
[string]
$Path
)
}
Get-ContosoFile | Where-Object -Property # TAB or Ctrl-Space here

When using your own objects, consider adding a type to them. Not only will this make it easier to discern them with the -is operator later on, it will also make it possible to format them properly. We will revisit that example when we examine the architecture of a module:

function Get-Bob
{
[CmdletBinding()]
[OutputType('Contoso.Bob')]
param
( )

[PSCustomObject]@{
PSTypeName = 'Contoso.Bob'
Name = 'Bob'
}
}

Get-Bob | Get-Member
(Get-Command Get-Bob).OutputType

When returning output, there are some developers that advocate against using a return statement. While this works and is a proper design, using the return statement can improve the cyclomatic complexity of your code by reducing nesting levels and on occasion completely eliminating branching statements like if, elseif, else and switch.

Cyclomatic complexity refers to a software metric that indicates the complexity of your code by basically measuring the number of code paths to cover during tests.

See also: https://en.wikipedia.org/wiki/Cyclomatic_complexity

Instead of nested if statements, you can reduce the level of nesting and use return in some code paths, as shown in the following example:

# Reducing nesting
function foo
{
param
(
$Param1
)

# This horrible creation
if ($Param1)
{
if (Test-Path $Param1)
{
if ((Get-Date).Date -eq '4/20')
{
# Do things
# Hard to maintain deeply nested code
$false
}
else
{
$true
}
}
}

# looks better like this simply by inverting statements
if (-not $Param1) { return }
if (-not (Test-Path -Path $Param1)) { return }

# No last if statement necessary for simple code block
return (-not ((Get-Date).Date -eq '4/20'))
}

When using classes in PowerShell, the return statement is mandatory when you want to return objects from within methods. Write-Output or simply executing any cmdlet or variable will be ignored and not be present in the output of that method. Classes will be introduced in Chapter 6, Working with Data.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.113.188