arrays - 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]
}
解决方案
你最好不要把它放在数组中。
更新数组时,必须重写整个数组,因此性能往往很糟糕。
如果要逐项删除,请使用不同的数据类型。
#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}
推荐阅读
- latex - “缺少插入的 $”,即使我使用的是 \begin{equation}
- python - 如何从 pandas read_csv 获取值/行
- google-apps-script - 在一行的第一个空白单元格中设置时间戳
- authentication - Slim 4 - 如果身份验证失败,则具有自定义响应的身份验证中间件
- excel - 打开访问,导入模块并运行宏
- matlab - 如何在 MATLAB 中编写开始时间约束?
- jquery - 为什么通过 jQuery Ajax 将 Plaid 链接结果发布到 ASP.NET MVC 控制器时缺少属性数据?
- kotlin - 通用 Kotlin 工厂到 DRY 构造函数参数
- authentication - 如何通过 keycloak 向 github 企业中的每个用户添加主电子邮件?
- spring-boot - javax.persistence.criteria.CriteriaBuilder#or 是如何工作的?