Debugging Statements in Powershell Functions


Yesterday I needed to put together a simple powershell script to handle log file rotation. It should have been finished quickly- instead I got bogged-down in troubleshooting a simple issue with debug statements

 

Notes:

  • Powershell 2.0.1.1
  • Windows Server 2008 R2
  • Write-Host seems to solve the problem elegantly

While creating a powershell script I wanted to display status messages to the user at certain points. In previous scripts I was able to do this by placing text strings in-line. For more complex scripts involving powershell functions this does not seem to work.

I had created a function with an in-line string like this:

function CreateLogFolder()
{
   $DateTime = Get-Date -format yyyyMMddhhmm 
   $LogFolder = $HistoricalLogsDir + "\" + "APPNAME_" + $DateTime 
   New-Item $LogFolder -type directory | Out-Null 

   "Created new log instance folder" 

   return $LogFolder

}

Upon execution of the above function I got this error:

Copy-Item : Cannot convert 'System.Object[]' to the type 'System.String' required by parameter 'Destination'. Specified method is not supported.
At C:\LogCapture_test.ps1:77 char:13
+    Copy-Item <<<<  $LogFolder\* $LogInstanceFolder -recurse
    + CategoryInfo          : InvalidArgument: (:) [Copy-Item], ParameterBindingException
    + FullyQualifiedErrorId : CannotConvertArgument,Microsoft.PowerShell.Commands.CopyItemCommand

 

Commenting out the in-line string literal seemed to solve the problem. Considering the success I had previously had with this method, I decided to investigate a little further.

It appears that any statement which is not captured by a variable is "Returned" from the function. This is the case even if you have a return statement at the end of the powershell script. In my case I am taking the output of this function and using it in a Copy-Item statement like this:

   $LogInstanceFolder = CreateLogInstanceFolder
   Copy-Item $APPLogFiles\* $LogInstanceFolder -recurse

 

The value of the $LogInstanceFolder variable contained "Created new log instance folder" in addition to the actual log file location. When Copy-Item attempted to copy the files it failed since there is no valid location starting with "Created new log instance folder"

As a solution to this problem, use Write-Host. It will allow you to output text to users without "returning" the string to the function's return recipient.

   "Created new log instance folder"     then becomes
   Write-Host "Created new log instance folder"