Reputation:
I was researching ways to convert an Array
to a List
collection and the answer suggested here used casting.
In my script, I constructed a List<string>
with a for loop like this:
$backup_details = Get-Content "$env:USERPROFILE\Desktop\source.txt"
$backupItems = New-Object System.Collections.Generic.List[string]
foreach($item in $backup_details){
$backupItems.Add($item)
}
Is there any reason why I should use casting over this method?
Upvotes: 0
Views: 78
Reputation: 36297
I feel like you are over complicating things in the pursuit of your goal. As mentioned, you can simply rebuild the array without the first item, or move that item to a different variable.
Remove the item entirely:
$backupItems = $backup_details | Select -Skip 1
(or you could pipe Get-Content
to Select -Skip 1
initially and skip that step, or even do $backup_details = $backup_details | Select -Skip 1
to redefine itself)
Move the first item to a different variable, in case you want to keep it for later.
$firstItem, $backupItems = $backup_details
And, (courtesy of Nick's comment, because I didn't think of it), you could just cast it as an ArrayList when you import the data:
[Collections.ArrayList]$backupItems = Get-Content "$env:USERPROFILE\Desktop\source.txt"
$BackupItems.RemoveAt(0)
Upvotes: 1