Question about [void] and best way/practice to return an array from a function

  Kiến thức lập trình

So I tried to create a function that will look for my external drives by FriendlyName and if drive is plugged in to my PC I add it to the array list as a PATH with drive letter (“X:”) so I can use it later for copying as a destination path. If external drive is not available then it will not be added. So If I have 3 ssds pluged I will have array with 3 paths returned, if only 2.. only 2 paths, 1 only 1.

I just wanted to try more dynamic way of detecting my external drives then hard codding it since sometimes assigned drive letter might change but FriendlyName will be the same for my ssds.

#That’s how I used to have it

[System.Collections.ArrayList]$DestSSD = @(
    "X:" #SSD-1
    "T:" #SSD-2
    "A:"  #SSD-3
)

I found online a simple template of function that returns an array and I modified it with my code. Everything works but I have some question.

  1. What [void] is doing in this case?
  2. why at the end there’s ,$target not “return $target”?
  3. Is [OutputType([System.Collections.ArrayList])] necessary, function works without it but maybe it’s good practice to specify the output? (I’m new to PowerShell so first time seeing it)

Without void and , it doesn’t really work and for now I have hard time understanding what it does in my function and why I need to use it. That brings me to my last question —> I wonder if this approach/logic and my function is actually good or there’s a better way/practice to do what I’m trying to do. Thanks for you help!

function GetSSDsPath {
    [OutputType([System.Collections.ArrayList])]
    Param(
        [array]$SSDList,
        [System.Collections.ArrayList]
        $Target = @()
    )
    foreach ($ssdName in $SSDList) {
        $SSD = Get-PSDrive | Where-Object {$_.Description -eq $ssdName}
        if($SSD){
            [void]$Target.Add("$($SSD):") #example "X:"
        }else{
            Write-Host "$($ssdName) not found"
        }
    }
    ,$Target
}

$ssdList = "SSD-1", "SSD-2", "SSD-3"
[System.Collections.ArrayList]$DestSSD = GetSSDsPath $ssdList

1

LEAVE A COMMENT