简体   繁体   中英

Extra empty column in the Out-GridView (powershell 4)?

I have the following code snippet:

 function MyTestString { [string]$OutString $OutString = 'ABCDEFG' #$OutString | Out-GridView -Wait -Title "String inside function" return $OutString } $MyString = MyTestString | Out-GridView -Wait -Title "Getting Extra Column"

When I run it in Powershell , I get an extra empty column in the grid view. If Out-GridView is placed inside the function then there is no empty column. The same thing is happening with Export-Clixml .

How can I avoid the empty column in the grid? I would like to know why do I get an empty column in GridView .

Here's a screen shot of the extra empty column:

Thank you for your help.

That would be extra row instead of column, and it's caused by the function body. Let's examine it.

function MyTestString
{
    [string]$OutString
    $OutString = 'ABCDEFG'
    return $OutString
}

MyTestString     

ABCDEFG

Okay, looks like a direct call returns extra row. Is it really so?

$o=MyTestString
$o 

ABCDEFG

Let's look inside $o :

$o.GetType()
IsPublic IsSerial Name                                     BaseType
-------- -------- ----                                     --------
True     True     Object[]                                 System.Array

Now we are getting somewhere. The function returns an array. How about its contents?

PS C:\> $o[0]


PS C:\> $o[1]
ABCDEFG

The zeroth element doesn't contain anything but emptiness. This looks strange, so let's make sure Powershell is using strict mode (which it doesn't do per default. And that is a brain-dead a design decision.)

Set-StrictMode -Version 'latest'
MyTestString
The variable '$OutString' cannot be retrieved because it has not been set.
At line:3 char:13
+     [string]$OutString
+             ~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (OutString:String) [], 
RuntimeException
    + FullyQualifiedErrorId : VariableIsUndefined

Let's see the function body again:

{   
    [string]$OutString
    $OutString = 'ABCDEFG'
    #$OutString | Out-GridView -Wait -Title "String inside function"
    
    return $OutString
}

Note the [string] part? That isn't a varaible declaration. It will return its contents to the pipeline. When Powershell isn't in strict mode, it returns a big fat of nothing - the empty element at $o[0] . When in strict mode, Powershell notes that an uninitialized variable is being accessed.

As for a fix, assign a value to OutString - unless you were trying to work with parameters.

function MyTestString
{   
    [string]$OutString = 'ABCDEFG'
    return $OutString
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM