我正在尝试创建一个创建文件夹(嵌套和多个)的 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
谢谢, 席德
最佳答案
替换:
[string] $array = "0", "0", "0" # !! creates *single* string
与:
[string[]] $array = "0", "0", "0" # creates *array* of strings
在您的原始命令中,变量左侧的 [string]
类型约束导致输入数组(隐式类型为 [object[]]
)转换为内容为 0 0 0
的单个字符串 ([string]
)
(PowerShell 通过将数组的元素与分隔符 $OFS
连接来对数组进行字符串化,分隔符默认为空格。)
相比之下,[string[]]
生成一个数组,其元素 为string
类型。
PowerShell 中的 [...]
封闭文字指的是 .NET 类型。它被称为类型文字。
如果您将这样的类型字面量放在变量赋值的左侧,您就type-constrain那个变量,这意味着它只能存储作为该类型实例的值,并且如果可能,它会自动尝试将其他类型的实例转换为该类型;见this answer有关类型约束的更多信息。
您还可以使用类型字面量将表达式转换 为该类型(就像您的代码在语句 $arac = [int16] $ 中所做的那样) arac
),这也意味着将操作数转换为该类型,作为一次性操作。
在类型文字[string[]]
中,类型名称string
之后的[]
指定了一个数组 该类型的元素;除了封闭的 [...]
,此 表示法 与 .NET Type.GetType()
使用的相同。方法;见this answer获取更多信息。
例如,请注意 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]
索引进行索引字符数组。
从技术上讲,这适用于从数组中获取字符,但您不能设置它们:
# 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".
关于arrays - 当我在 PowerShell 中更改数组的值时,我不断收到 "Unable to index into an object of type System.String.",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59018136/
相关文章:
angular - ViewChild 与 Directive 获取 ViewContainerRe
reactjs - React 中的 forwardingRef 与回调 refs 有什么区别?
flutter - 将 mapEventToState 与传入流一起使用的最佳实践?
graphql - gatsby-source-contentful 不适用于 gatsby-tra
r - 代码相当于 RStudio 查看器 Pane 中的 'broom' 图标?
android - 无法再在 Android Studio 中运行单独的插桩测试
hibernate - Spring JPA 审计因多个数据源而失败
visual-studio-code - VSCode 个人快捷方式在笔记本编辑器中不起作用