1

I am trying to insert strings into an array of an array but it's not working. Here is what I'm trying to do:

[string[]] $workArray::new(6,2)

$workArray[0,1] = "C:\Users\"
$workArray[0,2] = "Document.xlsm"

However I'm getting this error: "Unable to index into an object of type System.String."

Any suggestions I'll be forever grateful!

Andrew Morton
  • 24,203
  • 9
  • 60
  • 84
  • 2
    Call the array constructor like this: `$workArray = [string[,]]::new(6, 2)` – zett42 Apr 06 '22 at 18:55
  • @zett42 thanks. I called the constructor like that and then tried to add the strings, getting another error now : Index was outside the bounds of the array. Do arrays start a 1 in powershell? – CluelessDawg1337 Apr 06 '22 at 18:59
  • @CluelessDawg1337 Arrays start at 0 in PowerShell, so `$workArray[0, 0]` and `$workArray[0, 1]` for the code in the example. If you get into the habit of putting a space after a comma, it makes it easier to read. – Andrew Morton Apr 06 '22 at 19:04
  • 1
    My first comment apparently requires PS 7.x. In PS 5.x you need this syntax instead: `$workArray =New-Object 'string[,]' 6, 2` – zett42 Apr 06 '22 at 19:06

1 Answers1

0
$workArray = [string[,]]::new(6, 2)
$workArray[0,0] = "C:\Users\"
$workArray[0,1] = "Document.xlsm"

PowerShell is zero indexed.

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_arrays?view=powershell-7.2