Search code examples
powershellblank-line

Powershell: How to remove first empty blank line in console output of an array?


I have some code (tio.run), which output to console:

$exeoutput = @(
    "     Compression          : CCITT Group 4",
    "     Width                : 3180",
    "     Height               : 4908"
)
$var = $exeoutput.trim() | Select-String "Height|Width|Compress"
echo ----------------
$var
echo ---------------

Output is

----------------

Compression          : CCITT Group 4
Width                : 3180
Height               : 4908
----------------

How to remove first empty blank line after upper ---------------- from console output?


Solution

  • Each element of the $var variable is of the MatchInfo type. You need to cast them to string as follows:

    [string[]]$var
    

    or

    $var.foreach([string])
    

    Read ForEach and Where magic methods:

    ForEach(type convertToType)

    Unique to the ForEach method, you can pass a type into the ForEach method if you want to convert every item in a collection into another type. For example, imagine you have a collection of objects and you want to convert those objects into their string equivalent. Here is what that would look like with the ForEach method:

    # Get a collection of processes
    $processes = Get-Process
    # Convert the objects in that collection into their string equivalent
    $processes.foreach([string])
    

    You could have performed the same task by typecasting the collection into an array of type string (e.g. [string[]]$processes), and typecasting the array is in fact significantly faster, however there’s a very good chance you wouldn’t even notice the difference in execution time unless you were working with a very, very large collection. Despite the time difference, I will tend to prefer the ForEach method syntax in certain situations if it allows me to maintain elegance in the implementation by avoiding extra round brackets in the scripts I write.

    Example code snippet (updated with regard to the Lee_Dailey's comment):

    $var = $exeoutput.trim() | Select-String "Height|Width|Compress"
    '-' * 15
    $var.foreach([string])
    '-' * 15
    

    Result:

    ---------------
    Compression          : CCITT Group 4
    Width                : 3180
    Height               : 4908
    ---------------
    

    Note that echo is an alias for Write-Output cmdlet:

    This cmdlet is typically used in scripts to display strings and other objects on the console. However, because the default behavior is to display the objects at the end of a pipeline, it is generally not necessary to use the cmdlet.

    Note that you can multiply numbers, strings, and arrays (see ˙'-' * 15˙ instead of ----------------).