0

I am trying to write a PowerShell script, and I am declaring a variable, al as an ArrayList. However when I execute the script, I get the following output.

4

Now I have figured out which output is being caused by which variable. However, I can't find how to suppress the variables to suppress the output, so only my logs print without the extra clutter. How can I write the two lines to suppress the output?

Note: I will be adding more elements to the array to declaring $al with @() doesn't work in my code.

$al = [System.Collections.ArrayList]@($v1, $v2, $v3, $v4) 

Edit: Removed references to XML because the cause of the print was an echo statement I forgot about.

wolfcall
  • 678
  • 1
  • 8
  • 18
  • 3
    Look for whether you're doing something like `$al.Add($something)` anywhere – Mathias R. Jessen Mar 07 '20 at 22:03
  • 2
    as `Mathias R. Jessen` pointed out, you have an `.Add()` method call somewhere in your code that is creating that stray `4`. one of the reasons that arraylist is disrecommended is the nasty habit of outputting "i added some stuff!" numbers. so, either suppress that with some variant of assigning the output numbers to $Null ... OR do the better thing and use a generic.list. something like >>> $GenericList = [System.Collections.Generic.List[PSObject]]@($V1, $V2, $V3, $v4) <<<. any `.Add()` operations after that will NOT generate those silly index numbers. – Lee_Dailey Mar 07 '20 at 23:22
  • Yep was caused by the Add not the line I thought. – wolfcall Mar 08 '20 at 16:20
  • In short: PowerShell _implicitly outputs_ return values from .NET methods such as [`System.Collections.ArrayList.Add`](https://learn.microsoft.com/en-US/dotnet/api/System.Collections.ArrayList.Add); use `$null = ...` to ignore such outputs; see [the linked answer](https://stackoverflow.com/a/55665963/45375). – mklement0 Mar 09 '20 at 02:30

1 Answers1

1

To suppress unwanted output you use

| out-null

after your command.

See documentation...

Peter Schneider
  • 2,879
  • 1
  • 14
  • 17
  • 3
    [It is recommended to avoid Out-Null when you need to suppress the output of some commands inside large loops… It is recommended to assign to `$null` or `[void]` casting for better performance.](https://powershell-guru.com/powershell-best-practice-12-avoid-out-null/) – JosefZ Mar 07 '20 at 22:05
  • 1
    @JosefZ PowerShell 7 allegedly improves Out-Null performance to where it's better than assigning to null or casting to [void]. Got that straight from the PowerShell team at Ignite, but haven't tested it. – Steven Mar 08 '20 at 02:53
  • 1
    @Steven definitely (not only *allegedly*), `Out-Null` performance is improved in `pwsh` (6 and 7) as compared with `powershell` (5.1). However, the advice linked previously remains valid *for large loops*… – JosefZ Mar 08 '20 at 14:32
  • 1
    @JosefZ That's really awesome to get the extra clarity. Thanks! – Steven Mar 08 '20 at 19:52