簡體   English   中英

如何在PowerShell中定義子例程

[英]How to define a subroutine in PowerShell

例如,在C#中, RemoveAllFilesByExtenstion子例程可以是這樣的decleard:

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

和使用像:

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

如何使用PowerShell腳本文件(ps1)中的相同簽名來定義和調用子例程?

將此轉換為PowerShell非常簡單:

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

但是調用必須使用空格分隔的args但不需要引號,除非字符串中有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

如果您沒有返回任何值的函數,請確保捕獲函數內部命令返回的任何結果。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM