Powershell function will not work

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 I wanted to check it out. I put it in my profile, started Powershell and typed the following:

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

This folder is custom-made, it just has the same name as the Vista Download folder. The sub-folder in question does not have files , but jpg, but nothing is printed on the screen. Can someone tell me what I'm doing wrong? (Because, probably, I will do something wrong, I am sure of it).

+4
source share
1 answer

The classic problem is that you call PowerShell functions just like you call PowerShell cmdlets — with and without space separators, for example:

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

Note that with this type of call you do not 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, as you call listAllPaths, leads to an array ("C: \ Downloads \ Nemi", "* .jpg") passed to your $ fromFolder parameter. The $ filter parameter does not receive a value.

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

+8
source

All Articles