Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define a subroutine in PowerShell

Tags:

In C# a RemoveAllFilesByExtenstion subroutine could be, for example, decleard like this:

void RemoveAllFilesByExtenstion(string targetFolderPath, string ext)
{
...
}

and used like:

RemoveAllFilesByExtenstion("C:\Logs\", ".log");

How can I defne and call a subroutine with the same signature from a PowerShell script file (ps1)?

like image 214
Maxim V. Pavlov Avatar asked Feb 13 '12 14:02

Maxim V. Pavlov


People also ask

How do I create a parameterized function in PowerShell?

PowerShell uses the parameter value order to associate each parameter value with a parameter in the function. When you use positional parameters, type one or more values after the function name. Positional parameter values are assigned to the $args array variable.


1 Answers

Pretty simple to convert this to PowerShell:

function RemoveAllFilesByExtenstion([string]$targetFolderPath, [string]$ext)
{
...
}

But the invocation has to use space separated args but doesn't require quotes unless there's a PowerShell special character in the string:

RemoveAllFilesByExtenstion C:\Logs\ .log

OTOH, if the function is indicative of what you want to do, this can be done in PowerShell easily:

Get-ChildItem $targetFolderPath -r -filter $ext | Remove-Item
like image 90
Keith Hill Avatar answered Sep 20 '22 18:09

Keith Hill