PowerShell 将字符串拆分为二维数组 [英] PowerShell split string into two dimensional array

查看:58
本文介绍了PowerShell 将字符串拆分为二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TL:DR

使用 PowerShell 我想首先通过换行符 (\n) 拆分文本字符串,将其存储到数组中,然后用逗号将这些数组条目拆分为二维数组.我无法访问(或可能创建)第二维中的任何信息.

Using PowerShell I want to split a string of text first by the new line character (\n), store it into an array, then split those array entries with a comma into a two-dimensional array. I am having trouble accessing (or possibly creating) any information in the second dimension.

信息:

我有以下字符串(存储为 $services):

I have the following string (stored as $services):

SUPER-PC,Microsoft Office ClickToRun Service,ClickToRunSvc,C:\Program Files\Microsoft Office 15\ClientX64\OfficeClickToRun.exe /service,Auto
SUPER-PC,Adobe Acrobat Update Service,AdobeARMservice,C:\Program Files (x86)\Common Files\Adobe\ARM\1.0\armsvc.exe,Auto

预期结果:

我想将字符串拆分两次:

I want to split the string twice:

  1. 在新行上拆分(第一维)
  2. 分割行内的逗号(第二维)

我希望最终结果是一个我可以引用的二维数组.(例如: $services[0][0] 等)

I want the end result of this to be a two dimensional array that I can reference. (Ex: $services[0][0] etc.)

使用的命令:

为了完成新行拆分,我一直在使用以下命令:

To accomplish the new line split I have been using the following command:

$services= $services -split "\n"

要访问新数组结构中的拆分字符串,我可以执行以下操作:

To access the split string in the new array structure I can do the following:

$services[0]

PowerShell 只显示 $services

PowerShell displays only the first line of $services

接下来我使用:

$services[0] = $services[0] -split ','

问题:

当我尝试使用 $services[0][0] 访问第一个数组的第二维时,它显示 S 这是字符数组的第一个字符(SUPER-PC"是字符串的开头),不是我要创建的二维数组.

When I attempt to access the second dimension of the first array using $services[0][0] it displays S which is the first character of the character array ("SUPER-PC" being the start of the string), not the two-dimensional array I want to create.

我哪里出错了?

推荐答案

好吧,我讨厌自己回答,但这比我想象的要简单得多......其他两个答案都是有效的,Mathias 指出了一个明显的疏忽.

Ok I hate to self answer, but this was far more simple than I thought... Both other answers are valid, and Mathias pointed me to an obvious oversight.

$string = $string -split "," $string = $string.split(",") 相同> 正如马蒂亚斯所说:

$string = $string -split "," is not the same as $string = $string.split(",") As Mathias said:

-split 返回一个 string[] 类型的对象,这意味着你不能将字符串以外的任何内容分配给单个项目而不更改整个数组的类型.

-split returns an object of type string[], meaning that you can't assign anything other than a string to a single item without changing the type of the entire array.

所以我最终使用了:

$services= $services.split("`r`n")

然后

$services[0]= $services[0].split(",")

然后我能够使用 services[0][0]

此外,Bacon Bit 的回答很可能更好;我的回答只是以最简单的方式解决了我的问题.

Also, Bacon Bit's answer is in all likelihood better than my answer; my answer just addresses my question in the simplest possible fashion.

这篇关于PowerShell 将字符串拆分为二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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