无法从 powershell 中的数组中删除字符串

Cannot remove a string from an array in powershell

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

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

}

你最好不要一开始就把它放在数组中。

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

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

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