Monday, April 25, 2011

Capturing Non-Standard Powershell CmdLet Output for Flow Control

Currently trying to build a script utilizing cmdlets from the MS released "Team Foundation Server Power Tools" package.

I'm attempting to flow command logic from the success or failure of the "Update-TfsWorkspace" cmdlet however I can't seem get a return code out of the call nor can I capture the output using Out-String. I'm using Powershell v1.

update-tfsworkspace "C:\doesnotexist\" -recurse -version T

Yields a message of "Unable to determine the workspace." which is the error I'm trying to catch.

$ret = update-tfsworkspace "C:\doesnotexist\" -recurse -version T

Is expected to give me a $true/$false indicating success/fail but doesn't work.

update-tfsworkspace "C:\doesnotexist\" -recurse -version T | Out-Null

Is expected to prevent the cmdlet from writing the message but doesn't work.

trap{echo "fail"}
update-tfsworkspace $workspace_path -recurse -version T

Is expected to catch an error and write "fail" but doesn't work.

$msg = update-tfsworkspace $workspace_path -recurse -version T | Out-String

Is expected to populate a $msg variable with the host output but doesn't work.

I'm totally out of ideas here. Help would be appreciated!

From stackoverflow
  • Little hacky, but since I don't have TFS to try to figure something else out, see if this helps.

    Gabe : As mentioned the following is able to access the cmdlet output: PS> powershell.exe -noprofile -file test.ps1 > test.log PS> Get-Content test.log
  • I would say that this cmdlet wasn't written correctly. First, since it didn't succeed it should have emitted an error object which would have caused $? to return false which you could have checked or trapped. Second, you can't suppress the error message using -ea 0. It looks like this snapin is using the Host api to write an error string to the host console. That's a spew!! For now, you could do what EBGreen suggests:

    $msg = powershell.exe -nologo update-tfsworkspace "C:\doesnotexist\" -recurse -version T 2>&1

    Just watch out for all the text your profile script spits out when a new instance of PowerShell starts up.

  • Your problem here is that the cmdlet is writing an error (Non-Terminating Error), but not throwing an exception (Terminating Error). You can make it throw an exception by adding the ErrorAction parameter:

    trap{echo "fail"}
    update-tfsworkspace $workspace_path -recurse -version T -ErrorAction "Stop"
    

    This will cause the cmdlet to make all errors terminating (throwing an exception if it writes to the error stream).

0 comments:

Post a Comment