Powershell function won't work

Tag: powershell Author: selala2008 Date: 2009-09-06

I found this function in my old powershell folder:

Function listAllPaths([string]$fromFolder,[string]$filter) {
  Get-ChildItem -Path $fromFolder -Recurse $filter | Select-Object -Property FullName

And wanted to test it out. I put it in my profile, started Powershell and typed the following:

PS C:\> listAllPaths("C:\Downloads\Nemi","*.jpg")

That folder is a custom made, it just happens to have the same name as the Vista Downloads folder. The subfolder in question has nothing but jpg files, yet nothing is printed on screen. Can someone tell me what I'm doing wrong?(Because it will probably be me doing something wrong, I'm sure of it).

Best Answer

Classic issue - call PowerShell functions just like you call PowerShell cmdlets - with space delimiters and no parens e.g.:

PS> listAllPaths C:\Downloads\Nemi *.jpg

Note that when invoked like this you don't need double qoutes around args. In PowerShell 2.0 be sure to use Set-StrictMode -version 2.0 and it will catch this error:

PS> Set-StrictMode -Version 2.0
PS> function foo($a,$b) {"$a $b"}
PS> foo(1,2)
The function or command was called as if it were a method. 
Parameters should be separated by spaces. For information about 
parameters, see the about_Parameters Help topic.
At line:1 char:4
+ foo <<<< (1,2)
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : StrictModeFunctionCallWithParens

This is the correct way to call this PowerShell function:

PS> foo 1 2
1 2

FYI the way you are calling listAllPaths results in an array ("C:\Downloads\Nemi", "*.jpg") being passed to your $fromFolder parameter. The $filter parameter receives no value.

I should also mention that you only want to use commas and parens when calling .NET/COM/WMI methods.


Thanks, that's a clear an short explanation.