如何在PowerShell中定义子例程

Max*_*lov 18 powershell subroutine

RemoveAllFilesByExtenstion例如,在C#中,子程序可以是这样的符号:

void RemoveAllFilesByExtenstion(string targetFolderPath, string ext)
{
...
}
Run Code Online (Sandbox Code Playgroud)

和使用像:

RemoveAllFilesByExtenstion("C:\Logs\", ".log");
Run Code Online (Sandbox Code Playgroud)

如何使用PowerShell脚本文件(ps1)中的相同签名来定义和调用子例程?

Kei*_*ill 32

将此转换为PowerShell非常简单:

function RemoveAllFilesByExtenstion([string]$targetFolderPath, [string]$ext)
{
...
}
Run Code Online (Sandbox Code Playgroud)

但是调用必须使用空格分隔的args但不需要引号,除非字符串中有PowerShell特殊字符:

RemoveAllFilesByExtenstion C:\Logs\ .log
Run Code Online (Sandbox Code Playgroud)

OTOH,如果函数指示您想要做什么,这可以在PowerShell中轻松完成:

Get-ChildItem $targetFolderPath -r -filter $ext | Remove-Item
Run Code Online (Sandbox Code Playgroud)

  • Keith,感谢您提供“ cookies”以及答案。=) (2认同)