23

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

Maxim V. Pavlov
  • 10,303
  • 17
  • 74
  • 174

2 Answers2

44

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
Keith Hill
  • 194,368
  • 42
  • 353
  • 369
  • hint: the **local function** must be put **after the main function declaration** like this: `[CmdletBinding()] param( ... ) ... function myLocalFunction( ... ) { ... } ...` – Andreas Covidiot Jun 16 '20 at 09:16
3

There are no subroutines in PowerShell, you need a function:

function RemoveAllFilesByExtenstion    
{
   param(
     [string]$TargetFolderPath,
     [string]$ext
   )  

    ... code... 
}

To invoke it :

RemoveAllFilesByExtenstion -TargetFolderPath C:\Logs -Ext *.log

If you don't the function to return any value make sure you capture any results returned from the commands inside the function.

Shay Levy
  • 121,444
  • 32
  • 184
  • 206
  • 6
    Thanks. The term sub-routine is more "a reusable" "re-callable" piece of code, so the term "function" is a subset of "subroutine" in my opinion. – Maxim V. Pavlov Feb 13 '12 at 15:02
  • 2
    In VBscript there is actually a distinction between a subroutine (keyword: sub) and a function (keyword: function). The former returns no value and the latter does. Folks going to PowerShell from VBS might get a little confused that PowerShell only has functions which may ore may not return a value. – Andy Arismendi Feb 13 '12 at 16:52