I’m new to PowerShell and am working on my first function. I’ve been having a hard time puzzling out why I can’t properly specify a second parameter here when I try to run my function.
First off, here is the code. Like I said, this is a learning exercise, so it is very basic. Also, while testing I commented out the “Remove-Item” command.
After I import the module and then run it, I’m getting the following behavior.
PS C:\users\swhite\Documents\WindowsPowerShell> remove-oldfiles "c:\test1" 30
remove-oldfiles : A positional parameter cannot be found that accepts argument '30'.
At line:1 char:1
+ remove-oldfiles "c:\test1" 30
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [remove-oldfiles], ParameterBindingException
+ FullyQualifiedErrorId : PositionalParameterNotFound,remove-oldfiles
Also, something that is very odd to me is that although I specified the property of Mandatory=$true, the second parameter isn’t being required. I know this because if I run with just a path the function works.
Also, make sure you’re running this in a “fresh” session. E.g., if you’ve loaded this function into the console, it won’t re-read the file just because you’ve made changes. The old one will still be in memory messing with you.
In your first code you are missing a comma after the 1st parameter and have an unnecessary one after the second parameter which may be causing this behavior.
For the first scenario, you are provide 22 and it doesn’t know what to do with it. The second is most likely what you are doing which is providing a path with a space, so it would see it as 3 params in that example. It should be “C:\My Scripts” to pass it as a string.
Here is an updated function with some basics. Write-Verbose is your friend. It allows you to show troubleshooting information or run silently just by having the -Verbose switch or no switch respectively. Usually, when you are using functions, you want to gather additional information about what is happening. If you just piped directly to Remove-Item, you don’t know what is being removed, so in the function you can split things up so that you can get verbose information if required