PowerShell – Default Output Handling

Background

One of the cool things with PowerShell is its interactivity.

The results of every statement is sent back to the Caller:

In most of cases, it is to the Console

Within Functions, it is to the callee

This default handling leads to hard to find errors.

Returned data gets returned as a twin

Sample Code

Code

 
# Fixing Powershell's Busted Resolve-Path Cmdlet
# devhawk.net/2010/01/21/fixing-powershells-busted-resolve=path-cmdlet
function gracefulResolve-Path($filenameBase)
{

        # does file exist
	$fileExists = Test-Path $filenameBase;
	
        # if not, create file
	if (!$fileExists)
	{
	
		Write-Debug "Creating file $filenameBase..."
		
		New-Item $filenameBase -type file 
	}
	
	$filename = Resolve-Path $filenameBase -ErrorAction SilentlyContinue -ErrorVariable _objError;
	
	if (!$fileExists)
	{
	
		Write-Debug "Removing file $filenameBase..."
		
		Remove-Item $filenameBase
	}
	
	return ($filename);
	
}


Observation

The code snippet above can potentially return duplicate data; in terms of the file name passed in.

To avoid this problem, identify code statements that reference functions that return data.

In our sample above:

  1. New-Item
  2. Remove-Item

are such functions.

Remediate

To re-mediate:

Code



# Fixing Powershell's Busted Resolve-Path Cmdlet
# devhawk.net/2010/01/21/fixing-powershells-busted-resolve=path-cmdlet
function gracefulResolve-Path-Old2($filenameBase)
{

	$fileExists = Test-Path $filenameBase;
	
	if (!$fileExists)
	{
	
		Write-Debug "Creating file $filenameBase..."
		
                --consume result of calling function
		New-Item $filenameBase -type file | out-null;

	}
	
	$filename = Resolve-Path $filenameBase -ErrorAction SilentlyContinue
                                 -ErrorVariable _objError;

	if (!$fileExists)
	{
	
		Write-Debug "Removing file $filenameBase..."
		
                --consume result of calling function
		Remove-Item $filenameBase | out-null;

	}
	
	return ($filename);
	
}


Acknowledgment

MS Power-shell Architect\Blogger, Jeffrey Snover, lists some of the ways to suppress return values in function.

The details are listed in this Blog Entry “Suppressing return values in PowerShell functions“.

 


# We can assign the output to a variable
$null = test


# we can cast the expression to void
[void](test)


# We can pipe the objects to Out-Null
test |out-null

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s