PowerShell从数组中删除项目[0]

32

我有些困难,想要移除数组的第一行(项目ID)。

$test.GetType()

IsPublic IsSerial Name                                     BaseType                                                                                                      
-------- -------- ----                                     --------                                                                                                      
True     True     Object[]                                 System.Array

为了列出我尝试的所有选项,我使用了,$test | gm,它明确说明:

Remove         Method                void IList.Remove(System.Object value)                                                                                              
RemoveAt       Method                void IList.RemoveAt(int index)

所以当我尝试$test.RemoveAt(0)时,我会得到错误:

Exception calling "RemoveAt" with "1" argument(s): "Collection was of a fixed size."At line:1 char:1
+ $test.RemoveAt(1)
+ ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : NotSupportedException

所以我最终发现这里我的数组需要是System.Object类型才能使用$test.RemoveAt(0)。在脚本开头声明所有数组为列表是最佳实践吗?还是在需要此功能时将数组转换为列表,例如使用$collection = ({$test}.Invoke())?这两种类型的优缺点是什么?感谢您的帮助。
12个回答

0

结合其他回答和我的小改动(将其作为我的$profile中的全局函数):

function global:sudo {
    $runArgs = $args

    if($runArgs.Length -le 1) {
        $runArgs = ""
    }
    else {
        $runArgs = $runArgs[1..($runArgs.length - 1)]
        $runArgs = $runArgs -join " "
    }
    
    Start-Process $args[0] -ArgumentList $runArgs -Verb runas    
}

所以,sudo notepadsudo notepad c:\windows\abc.txt 都可以使用,并且参数应该能够优雅地传递(尽管没有彻底检查)


0

有一种更简单、更优雅的方法来实现这个。与之前给出的某些答案不同,这个答案也适用于只有一个元素的数组。它还可以在任何所需的索引处工作。

$arr = @(1,2,3)
$arr -ne $arr[0] #remove first element: @(2,3)
$arr -ne $arr[1] #remove second element: @(1,3)
$arr -ne $arr[-1] #remove last element: @(1,2)

2
谢谢您的补充,但请小心操作,因为它将删除不止第一个元素。这段代码$arr = @(1,2,3,1); $arr = $arr -ne $arr[0]; Write-Host $arr返回的是@(2,3)而不是预期的@(2,3,1) - DarkLite1
啊,对了。抱歉我没有检查我的答案是否有重复值。 - crisc2000

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接