Arrays 我不断地得到;无法索引到System.String类型的对象中。”;当我在PowerShell中更改数组的值时

Arrays 我不断地得到;无法索引到System.String类型的对象中。”;当我在PowerShell中更改数组的值时,arrays,powershell,Arrays,Powershell,我正在尝试创建一个PowerShell脚本,用于创建文件夹(嵌套和多个)。我设法让嵌套的文件夹工作,我对此很陌生,但我似乎无法让多个文件夹工作。我基本上想做一个字符串数组,每个项目都是用户输入的字符串。我尝试了所有的方法,但似乎都不起作用,任何帮助都将不胜感激,这是我的代码 echo "Folder Creator for FS2019 by Skaytacium, enter the values for unlimited nested folders! Remember though, 2

我正在尝试创建一个PowerShell脚本,用于创建文件夹(嵌套和多个)。我设法让嵌套的文件夹工作,我对此很陌生,但我似乎无法让多个文件夹工作。我基本上想做一个字符串数组,每个项目都是用户输入的字符串。我尝试了所有的方法,但似乎都不起作用,任何帮助都将不胜感激,这是我的代码

echo "Folder Creator for FS2019 by Skaytacium, enter the values for unlimited nested folders! Remember though, 260 characters is the max nesting limit!"

$count = Read-Host -Prompt 'How many folders? Value'
$count = [int16]$count

$sub = Read-Host -Prompt 'Do you wanna nest? 2/1'

$namestring = "./"
$storay

[string]$array = "0", "0", "0"

$arac = 0
$arac = [int16]$arac


if ($sub -eq "2") {
    echo "The specified folders will be nested"

    while ($count -gt 0) {

        $namestring = $namestring + (Read-Host -Prompt 'Name') + "/"
        $count--
        echo $namestring

        if ($count -eq 0) {
            md $namestring
        }
    }
}

elseif ($sub -eq "1") {
    echo "The specified folders will be consecutive (in the same dir)"

    while ($count -gt 0){
        $storay = Read-Host "Name"
        $array[1] = @("please help")
        echo $array
        $arac++
        $count--
    }
}

Pause
谢谢, Sid更换:

[string] $array = "0", "0", "0"  # !! creates *single* string
与:

在原始命令中,变量左侧的
[string]
类型约束导致输入数组(隐式类型为
[object[]]
)转换为单个字符串(
[string]
),内容为
0
(PowerShell通过使用分隔符
$OFS
(默认为空格)连接数组元素来字符串化数组。)
相反,
[string[]
生成一个数组,其元素是
string
类型的

PowerShell中包含的
[…]
-文字表示.NET类型。它被称为类型文本

  • 如果将此类类型文字放置在变量赋值的左侧,则类型约束该变量,这意味着它只能存储属于该类型实例的值,并且如果可能,它会自动尝试将其他类型的实例转换为该类型;有关类型约束的详细信息,请参见

  • 您还可以使用类型文字将表达式转换为该类型(就像您的代码在语句
    $arac=[int16]$arac
    中所做的那样),这也意味着将操作数转换为该类型,作为一次性操作

在type literal
[string[]]
中,类型名称
string
后的
[]
指定该类型的元素数组;除了封闭的
[…]
,此符号与.NET方法使用的符号相同;有关更多信息,请参阅

请注意,例如,PowerShell的类型转换比C#的灵活得多;它们通过内置的转换规则和尝试自动使用适当的构造函数和静态的
.Parse()
方法得到增强


请注意,您不需要严格的类型约束
[string[]]
,除非您希望确保以后分配给此数组的元素会自动执行到字符串的转换

# OK, but creates [object[]] array that now happens to contain [string]
# instances, but the type of the elements isn't locked in.
$array = "0", "0", "0"

至于您看到的具体错误消息

因为
$array
只是代码中的一个
[string]
,在字符串的字符数组中使用
[0]
索引进行索引

从技术上讲,这适用于从数组中获取字符,但不能设置它们:

# OK, but creates [object[]] array that now happens to contain [string]
# instances, but the type of the elements isn't locked in.
$array = "0", "0", "0"
# GET the 1st character from the string stored in $var
PS> $var = 'foo'; $var[0]
f     # 1st character in the string

# !! You CANNOT SET characters that way
PS> $var[0] = 'F'
InvalidOperation: Unable to index into an object of type "System.String".