我正在尝试编写一个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个文件时,结果看起来很好,其中每个元素包含完整路径和文件名。但是,当只找到一个对象/文件时,该数组现在每个元素存储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
感谢帮助!!
答案 0 :(得分:0)
在将值存储在其中之前,只需将$a
声明为数组即可。 PowerShell旨在自动进行类型转换。因此,当您将数组推入其中时,$a
将成为一个数组。当您只推送一个值时,PowerShell会将其确定为字符串。
在使用之前在函数中声明$a = @()
或者像@PetSerAl建议的那样,并在运行中声明它。