Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell function won't work

Tags:

powershell

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).

like image 239
KdgDev Avatar asked Sep 22 '09 15:09

KdgDev


People also ask

Why is my PowerShell not working?

The error “Powershell has stopped working” is caused by a virus (poweliks) on your computer. You are likely experiencing the computer at it's peak levels of slowness.

How do I run a function in PowerShell?

A simple functionA function in PowerShell is declared with the function keyword followed by the function name and then an open and closing curly brace. The code that the function will execute is contained within those curly braces.

What does $_ do in PowerShell?

The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.

What does @() mean in PowerShell?

Array subexpression operator @( )Returns the result of one or more statements as an array. The result is always an array of 0 or more objects. PowerShell Copy.


1 Answers

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.

like image 85
Keith Hill Avatar answered Nov 25 '22 07:11

Keith Hill