Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.1k views
in Technique[技术] by (71.8m points)

powershell - Formatting issues / missing data when multiple commands use Select-Object within a script

I've run into a problem with my PowerShell scripts where I am "losing" output that was going to the console, or being redirected. After much legwork, I simplified it down to an easily documented example of the problem.

Place the following single line in a script (test1.ps1), and invoke it from a basic PowerShell command window:

Get-WmiObject win32_share  | select name, path

and you will likely get two columns of output similar to the following:

PS C:Usersmeemp> ./test1.ps1

name                                    path
----                                    ----
ADMIN$                                  C:Windows
C$                                      C:
IPC$
Users                                   C:Users

but now, create a two line script (test2.ps1) like this, and run it in the same manner:

Get-WmiObject win32_share | select name
Get-WmiObject win32_share | select name, path

and observe the output gets mangled:

PS C:Usersmeemp> ./test2.ps1

name
----
ADMIN$
C$
IPC$
Users
ADMIN$
C$
IPC$
Users

The two commands are actually run , but the second call gets "squeezed" into the output of the first. It lost its second column, and its header and spacing.

This really seems to be a problem of the "first" output not properly "closing out", because it really doesn't seem to matter what the second line is if it pipes into another select statement.

As an aside, my original lines looked a bit more like this:

Get-WmiObject win32_share | select name, path | Write-Output
Get-WmiObject win32_share | select name | Write-Output

So that from a powershell prompt, I could direct the output wherever I desired using redirection

PS C:Usersmeemp> ./test2.ps1 > ./outfile.txt

As stated, actual case is more complez than this, but at this point, I just want to get a understanding of what is happening.

Bug? Or failure to comprehend on my part?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Get-WmiObject win32_share | select name | ft
Get-WmiObject win32_share | select name, path | ft


Get-WmiObject win32_share | ft name
Get-WmiObject win32_share | ft name, path

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...