首页 > 解决方案 > Cannot remove a string from an array in powershell

问题描述

I'm trying to populate an array of file paths where ever the script is located in. But I don't want the array to include the path of the script only the other files in that folder. I have tried removing it after it is populated by using a list array instead but then I get an error that the array is a fixed size.

#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]

}

标签: arrayspowershellarraylist

解决方案


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

更新数组时,必须重写整个数组,因此性能往往很糟糕。

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

#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}

推荐阅读