PowerTip: Create a Strongly Typed Array in PowerShell

PowerTip: Create a Strongly Typed Array in PowerShell

  • Comments 3
  • Likes

Summary: Learn how to create a strongly typed array.

 

Hey, Scripting Guy! Question I want to create a strongly typed array of system.diagnostics.processes and store it in a variable called $a. How can I do this?

Hey, Scripting Guy! Answer Use a command such as:

[diagnostics.process[]]$a=get-process

Your comment has been posted.   Close
Thank you, your comment requires moderation so it may take a while to appear.   Close
Leave a Comment
  • Why?

  • @JRV because we can :-) It is a good way to ensure that what you are storing is exactly what you think you are storing in your array.

  • Hi,

    @jrv

    ---> you can validate your variable or parameter :

    PS II> [diagnostics.process[]]$b=$null

    PS II> $b=1 # ERROR

    PS II> $b=gdr # ERROR

    PS II> gps *s*

    PS II>

    PS II> type c:\scripts\why\foo.txt

    function foo {

     param(

       [diagnostics.process[]]$b,

       [string]$n

     )

     $b

    }

    PS II> import-function -Path c:\scripts\why\foo.txt -Name foo

    PS II> foo -b 5 # ERROR