【问题标题】:Cannot remove a string from an array in powershell无法从PowerShell中的数组中删除字符串
【发布时间】:2021-10-28 00:01:38
【问题描述】:

我正在尝试填充脚本所在的文件路径数组。但我不想要 包含脚本路径的数组仅包含该文件夹中的其他文件。我尝试在使用列表数组填充它后将其删除,但随后我收到一个错误,即该数组是固定大小的。

#To get path in which the script is located
$mypath = $MyInvocation.MyCommand.Path
$myStringPath=$mypath.ToString().Replace("TestingScriptPath.ps1", "")
#Populates files inside the folder
$array = @() 
(Get-ChildItem -Path $myStringPath ).FullName |
foreach{
    $array += $_ 
    
}
#display paths
for($i = 0; $i -lt $array.length; $i++)
{ 
 
 $array[$i]

}

【问题讨论】:

    标签: arrays powershell arraylist


    【解决方案1】:

    你最好不要把它放在数组中。

    当更新一个数组时,整个数组都要重写,所以性能往往很糟糕。

    如果您要逐项删除,请使用不同的数据类型。

    #To get path in which the script is located
    $mypath = $MyInvocation.MyCommand.Path
    $myStringPath=$mypath.ToString().Replace("testingscriptpath.ps1", "")
    
    #Populates files inside the folder
    $array = Get-ChildItem -Path $myStringPath | Where-Object {$_.fullname -ne $mypath}
    
    $array
    

    如果您确实想按照问题中建议的方式进行操作(较慢)

    $ArrayWithFile = Get-ChildItem -Path $myStringPath
    $ArrayWithoutFile = $ArrayWithFile | Where-Object {$_.fullName -ne $mypath}
    

    【讨论】:

      猜你喜欢
      • 2017-05-27
      • 2017-12-18
      • 2021-12-22
      • 2023-01-18
      • 1970-01-01
      • 2013-10-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多