使用字符串引用时,引用 Powershell 数组索引会产生意外结果 [英] Referencing Powershell array index produces unexpected results when referenced with string

查看:40
本文介绍了使用字符串引用时,引用 Powershell 数组索引会产生意外结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您有

$arr = @("Filename1", "Filename2")
for($i =0; $i -le $arr.Length -1; $i++) {

   write-host ".\"$arr[$i]
   write-host ".\$arr[$i]"
   write-host $arr[$i] 
}

所以只需要一个循环就会产生:

So taking just one loop through it produces:

".\ Filename1"
".\ Filename1 Filename2[0]"
"Filename1"

仅引用数组[index] 将产生正确的值,但如果我与字符串连接,它会在字符串和值之间放置一个空格.当放置在字符串中时,我认为它正在转储整个内容,因为它正在评估 $array 然后评估 $i 以

Just referencing the array[index] will produce the correct value, but if I concatenated with a string it places a space between the string and value. When placed within the string I assume it is dumping the entire contents because it is evaluating $array then evaluating $i ending up with

".\ filename1 filename2[索引号]"

".\ filename1 filename2[index number]"

但是如果我将单个值分配给一个单独的变量并将其与一个字符串连接起来,就没有空格了吗?这是为什么:

But if I assign the individual value to a separate variable and concatenate it with a string there is no space? Why is that:

示例:

 $name = $arr[$i]
 write-host ".\$name"

output = ".\filename1"

output = ".\filename1"

哪个是正确的.

推荐答案

你要做的:

write-host ".\$($arr[$i])"

所以它被评估为数组索引.

so that it is evaluated as array indexing.

在字符串中访问对象的属性或哈希键等就是这种情况:

It would be the case with something like accessing properties of an object or key of hash etc within the string:

PS > $a = @{test="A";test2="B"}
PS > write-host "$a.test"
System.Collections.Hashtable.test
PS > write-host "$($a.test)"
A

另一种选择是使用字符串格式,当字符串中有很多变量/对象时特别有用:

Another alternative is to use string formatting, especially useful when you have lots of variables / objects in the string:

write-host (".\{0}" -f $arr[$i])

这篇关于使用字符串引用时,引用 Powershell 数组索引会产生意外结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆