如何在 PowerShell 中定义子例程

发布于 2025-01-05 05:20:30 字数 313 浏览 2 评论 0原文

例如,在 C# 中,RemoveAllFilesByExtenstion 子例程可以像这样声明:

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

并像这样使用:

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

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

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

残月升风 2025-01-12 05:20:30

将其转换为 PowerShell 非常简单:

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

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

RemoveAllFilesByExtenstion C:\Logs\ .log

OTOH,如果该函数指示您想要执行的操作,则可以是在 PowerShell 中轻松完成:

Get-ChildItem $targetFolderPath -r -filter $ext | Remove-Item

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
颜漓半夏 2025-01-12 05:20:30

PowerShell 中没有子例程,您需要一个函数:

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

    ... code... 
}

调用它:

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

如果该函数不返回任何值,请确保捕获从函数内的命令返回的任何结果。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文