Alex Rivera | Logout

How to suppress PowerShell Get-Content output

Asked 2012-01-24T09:54:04.883
8

I have a PS script:

script.ps1

[System.Xml.XmlDocument] $Config;

function Get-ScriptDirectory
{
    Split-Path $script:MyInvocation.MyCommand.Path
}

function Load-Config
{
    $configPath = Join-Path (Get-ScriptDirectory) config.xml
    $global:Config = [xml](gc $configPath) 
}

Load-Config

config.xml

<Configuration>
</Configuration>

Later in the script I'm working with $Config variable. When I run this script it writes the output to the console, which contains the root element of the xml. Something like:

Configuration
--------------

Is there exists any way how to suppress this output?

Thanks.

Edit
Report

2 Answers

6

Probably the output isn't caused by the assignment statement (a voidable statement), but by this line:

[System.Xml.XmlDocument] $Config;

In PowerShell, typically, all statements return a value (except for voidable statements). I think that the first time you run the script no output will be written to the console. However on subsequent runs $Config will still contain the value of the previous run, and its value will be written to the screen.

  • piping to the Out-Null cmdlet: [System.Xml.XmlDocument] $Config | Out-Null
  • casting to void: [void][System.Xml.XmlDocument]$Config
  • assigning to $null: $null = $Config
  • or simply not 'declaring' the $Config variable

are ways to suppress this behaviour.

answered 2012-01-24T12:32:41.993
1

Somewhere you're dumping the variable from your script. As it falls out of the pipe it gets passed to Out-Host and that will yield the output you see.

The actual solution is to make sure you don't return anything from your script. As I cannot see your code I can't point to where, but somewhere there is a pipeline or statement that leaks the object into output. Are you sure you're using an assignment at every place you need?

answered 2012-01-24T10:13:05.443

Your Answer