我正在解析文本文件中的一堆数据。我得到的数据Get-Content。然后我遍历的每一行$data。在空格上分割每一行,并将这些值加载到数组中。
然后,我遍历$string数组中的每个数组。
如果$string匹配特定值,我想将其从数组中删除。
$index.Delete(), $index.Remove() 不起作用,这就是我所拥有的。
$data = Get-Content "C:\Users\$userName\Desktop\test-data.txt"
foreach($row in $data){
if($row)
{
[Array]$index = $row.Split(" ")
$i = 0
foreach($string in $index){
Write-Host $string
if($string -eq "value1" -or $string -eq "value2" -or $string -eq "value3")
{
$index.Delete() //This does not work.
}
}
Run Code Online (Sandbox Code Playgroud)
我也尝试过类似的方法,但是根本没有用。
for($i -eq $index.length; $i -le 0; $i++)
{
Write-Host $index[$i] #this would hit once then give me an error saying the value is null
if($index[$i] -eq "value1" -or $index[$i] -eq "value2" -or $index[$i] -eq "value3")
{
$index.Remove() #does not hit here at all/nor will it work.
Write-Host $index
}
}
Run Code Online (Sandbox Code Playgroud)
如何从$index阵列中删除某些内容?
有一个更好的方法吗?
任何帮助将不胜感激,谢谢。
最简单的方法是链接-ne运算符:
[Array]$index = $row.Split(" ") -ne $value1 -ne $value2 -ne $value3
Run Code Online (Sandbox Code Playgroud)
每个变量都会删除数组中与变量值匹配的所有元素,并将结果传递给下一个。完成后,数组将包含与任何$ value变量都不匹配的元素。
| 归档时间: |
|
| 查看次数: |
4844 次 |
| 最近记录: |