I am trying to write a P/S script where a set of extensions are searched and processed, but I am having issues with the file search.
This is my findFiles function -
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])
}
}
So when there is more than 1 file found, the results look good where each element contains the full path and the filename. However, when only a single object/file is found, the array is now storing 1 character per element. Here is the sample output of 2 config files found, and only one of type xml is found. It works fine if I add another file of type 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
Appreciate the help!!
Just declare $a
as an array before you store values in it. PowerShell is designed to typecast automatically. So when you push an array into it, $a
becomes an array. When you push just one value, PowerShell decides it is a string.
Either declare $a = @()
in your function before you use it or do like @PetSerAl suggested and declare it on the go.