Pass the array to the constructor instead:
$readOnly = New-Object 'System.Collections.ObjectModel.ReadOnlyCollection[byte]' -ArgumentList @(,$arr)
or (PowerShell 5.0 and up):
$readOnly = [System.Collections.ObjectModel.ReadOnlyCollection[byte]]::new($arr)
Now, your question title specifically says copy array elements - beware while you won't be able to modify $readOnly
, its contents will still reflect changes to the array that it's wrapping:
PS C:\> $arr[0] = 100
PS C:\> $arr[0]
100
PS C:\> $readOnly[0]
100
If you need a completely separate read-only collection, copy the array to another array first and then overwrite the variable reference with the read-only collection:
$readOnly = [byte[]]::new($arr.Count)
$arr.CopyTo($readOnly, 0)
$readOnly = [System.Collections.ObjectModel.ReadOnlyCollection[byte]]::new($readOnly)
Now you can modify $arr
without affecting $readOnly
:
PS C:\> $arr[0] = 100
PS C:\> $arr[0]
100
PS C:\> $readOnly[0]
10