首页 > 解决方案 > powershell 在简单数组操作期间无法索引到空数组

问题描述

我是 powershell 新手,遇到了问题。我尝试使用格式“x,y,b”来制作一个读取描述国际象棋位置的 txt 文件的 powershell 脚本,其中 x 和 y 是颜色为 b 的国际象棋的平面坐标。

我在ps中写了以下代码:

function makeboard2d($file){
    $blankline=-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,-1
  $board2d=$blankline,$blankline,$blankline,$blankline,$blankline,$blankline,$blankline,$blankline,$blankline,$blankline,$blankline,$blankline,$blankline,$blankline,$blankline
    $board=Get-Content $file
    
    for ($i=0;$i -le $board.Length;$i++){
     
        $x=$board[$i][0]
        $y=$board[$i][2]
        $b=$board[$i][4]
        
        $board2d[$x][$y]=$b
    }
    
}
makeboard2d("G:\board.txt")

txt 文件 G:\board.txt 具有以下内容,格式为“x,y,b”:

1,2,1
3,3,0

我首先要做的是构建一个空白的 15×15 棋盘($board2d),每个条目都设置为 -1,这意味着没有放置国际象棋。然后我需要从 G:\board.txt 中读取输入行(例如 1,2,1),即玩家 A 和 B 的交替移动,并使用这样的输入列来修改上述二维板,$板2d。这里错误发生在循环内的 $x=$board[$i][0] 中。

你能提供一些指导吗?

确实谢谢你。

标签: powershell

解决方案


cmdlet将文件作为字符串Get-Content的一维数组读取。如果你想让它成为一个多维数组,你可以这样做

# initialize board to an array of arrays with all -1 values:
$board2d = for ($i = 0; $i -lt 15; $i++) { ,@(-1,-1,-1) }

# set board to whatever is in the file
$file = 'D:\Test\board.txt'
$board2d = Get-Content -Path $file
for ($i = 0; $i -lt $board2d.Count; $i++) { $board2d[$i] = ($board2d[$i] -split ',') }

数组值都将是字符串类型。如果您需要它们作为计算目的的数字,请执行以下操作:

for ($i = 0; $i -lt $board2d.Count; $i++) { $board2d[$i] = [int[]]($board2d[$i] -split ',') }

按索引引用不同的值(索引从 0 开始)

# $board2d[0][0]  --> first element in the array, X value
# $board2d[0][1]  --> first element in the array, Y value
# $board2d[0][2]  --> first element in the array, Color value
# $board2d[1][0]  --> second element in the array, X value
# $board2d[1][1]  --> second element in the array, Y value
# $board2d[1][2]  --> second element in the array, Color value

但是,使用具有命名属性的对象数组可能会更舒服:

# initialize board to an array of objects with all properties set to -1:
$board2d = for ($i = 0; $i -lt 15; $i++) { [PsCustomObject]@{X = -1; Y = -1; Color = -1} }

# set board to whatever is in the file
$file = 'D:\Test\board.txt'
$board2d = Import-Csv -Path $file -Header X,Y,Color

同样,从文件中读取的所有值都是字符串类型。要转换为整数,您可以执行以下操作:

$board2d = Import-Csv -Path $file -Header X,Y,Color | 
           Select-Object @{Name = 'X'; Expression = { [int]$_.X}},
                         @{Name = 'Y'; Expression = { [int]$_.Y}},
                         @{Name = 'Color'; Expression = { [int]$_.Color}}

现在您可以通过属性名称引用不同的值

# $board2d[0].X      --> first element in the array, X value
# $board2d[0].Y      --> first element in the array, Y value
# $board2d[0].Color  --> first element in the array, Color value
# $board2d[1].X      --> second element in the array, X value
# $board2d[1].Y      --> second element in the array, Y value
# $board2d[1].Color  --> second element in the array, Color value

推荐阅读