get-childitem 的 Powershell 数组元素结果

Powershell array elements results of get-childitem

我正在尝试编写一个 P/S 脚本来搜索和处理一组扩展名,但我在文件搜索方面遇到问题。

这是我的 findFiles 函数 -

function findFiles([string]$extension)
{
## find all files in the working directory with the fileTypes extensions
    Write-Host "in findFiles with extension" $extension
    $dotExt = "." + $extension
    $a = Get-ChildItem -Path "." -recurse | where {$_.extension -eq $dotExt} | Foreach-Object { $_.FullName }   
    Write-Host "$array length is " $a.length
    for ($i=0; $i -lt $a.length; $i++) {
        Write-Host "test: " $a[$i]
        #findVariables($a[$i])
    }
}

因此,当找到超过 1 个文件时,结果看起来不错,每个元素都包含完整路径和文件名。但是,当只找到一个 object/file 时,数组现在每个元素存储 1 个字符。这是找到的 2 个配置文件的示例输出,并且只找到了 xml 类型的一个。如果我添加另一个 xml.

类型的文件,它工作正常
PS C:\Users\Wayne\Desktop\varSubTest> .\varSubAll.ps1
in findFiles with extension config
 length is  2
test:  C:\Users\Wayne\Desktop\varSubTest\rwar2.config
test:  C:\Users\Wayne\Desktop\varSubTest\testFolder\test2.config
in findFiles with extension properties
 length is  0
in findFiles with extension yaml
 length is  0
in findFiles with extension yml
 length is  0
in findFiles with extension json
 length is  3
test:  C:\Users\Wayne\Desktop\varSubTest\test.json
test:  C:\Users\Wayne\Desktop\varSubTest\testFolder\another.json
test:  C:\Users\Wayne\Desktop\varSubTest\testFolder\third.json
in findFiles with extension js
 length is  0
in findFiles with extension xml
 length is  56
test:  C
test:  :
test:  \
test:  U
test:  s
test:  e
test:  r
test:  s
test:  \
test:  W
test:  a
test:  y
test:  n
test:  e
test:  \
test:  D
test:  e
test:  s
test:  k
test:  t
test:  o
test:  p
test:  \
test:  v
test:  a
test:  r
test:  S
test:  u
test:  b
test:  T
test:  e
test:  s
test:  t
test:  \
test:  t
test:  e
test:  s
test:  t
test:  f
test:  o
test:  l
test:  d
test:  e
test:  r
test:  2
test:  \
test:  o
test:  n
test:  e
test:  x
test:  m
test:  l
test:  .
test:  x
test:  m
test:  l

感谢帮助!!

只需将 $a 声明为一个数组,然后再将值存储在其中。 PowerShell 旨在自动进行类型转换。所以当你把一个数组压入其中时,$a 就变成了一个数组。当您仅推送一个值时,PowerShell 将其确定为一个字符串。

要么在你的函数中声明 $a = @(),然后再使用它,要么像@PetSerAl 建议的那样,在移动中声明它。