Decent technique for creating string array with same value?

Welcome Forums General PowerShell Q&A Decent technique for creating string array with same value?

This topic contains 2 replies, has 3 voices, and was last updated by

 
Participant
2 weeks, 1 day ago.

  • Author
    Posts
  • #132944

    Participant
    Points: 45
    Rank: Member

    For the Start-BitsTransfer cmdlet, assuming I have a $sourcepaths array and my destination is a single directory, is this a decent technique?

    $destarray = [System.Collections.ArrayList]::Repeat('C:\TEMP\',$sourcepaths.count)
  • #133203

    Participant
    Points: 1,124
    Helping Hand
    Rank: Community Hero

    This is cool 👍, didn't know about Repeat() method.

  • #133221

    Participant
    Points: 389
    Helping Hand
    Rank: Contributor

    Yep, this will get you basically the same result as other methods in PowerShell would. Nice find, I hadn't known about this one either! 🙂

    Possible alternate methods:

    $destArray = (1..$sourcePaths.Count).ForEach{ "C:\TEMP" }
    $destArray = foreach ($N in 1..$sourcePaths.Count) { "C:\Temp" }

    Both of those will get you a standard array back, instead of an arraylist, however; so if you need the arraylist at the other end, use ::Repeat()

    That said, ArrayList is effectively deprecated, so I would recommend using List[PSObject] instead... although that initial list may need to be created via a LINQ enumerable expression first, as it seems List lacks the .Repeat() method itself.

You must be logged in to reply to this topic.