Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在PowerShell中定义子例程_Powershell_Subroutine - Fatal编程技术网

如何在PowerShell中定义子例程

如何在PowerShell中定义子例程,powershell,subroutine,Powershell,Subroutine,例如,在C#aremoveallfilesbyextension中,子例程可以如下所示: void RemoveAllFilesByExtenstion(string targetFolderPath, string ext) { ... } 用起来像: RemoveAllFilesByExtenstion("C:\Logs\", ".log"); 如何从PowerShell脚本文件(ps1)中定义并调用具有相同签名的子例程?将其转换为PowerShell非常简单: function Rem

例如,在C#a
removeallfilesbyextension
中,子例程可以如下所示:

void RemoveAllFilesByExtenstion(string targetFolderPath, string ext)
{
...
}
用起来像:

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

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

将其转换为PowerShell非常简单:

function RemoveAllFilesByExtenstion([string]$targetFolderPath, [string]$ext)
{
...
}
但是调用必须使用空格分隔的参数,但不需要引号,除非字符串中有PowerShell特殊字符:

RemoveAllFilesByExtenstion C:\Logs\ .log
OTOH,如果函数指示您要执行的操作,则可以在PowerShell中轻松完成:

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

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

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

    ... code... 
}
要调用它:

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

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

谢谢。“子程序”一词更像是一段“可重用”“可重新调用”的代码,因此我认为“函数”一词是“子程序”的子集。在VBscript中,子程序(关键字:sub)和函数(关键字:函数)实际上是有区别的。前者不返回值,后者返回值。从VBS访问PowerShell的人可能会有点困惑,PowerShell只包含可能或可能不返回值的函数。很抱歉在一篇旧文章中吹毛求疵,但为了清楚起见:C语言引用没有使用术语“subroutine”。提示:必须将局部函数放在主函数声明之后,如下所示:
[CmdletBinding()]参数(…)…函数myLocalFunction(…){…}…