将参数从一个Powershell函数传递给另一个函数

时间:2017-03-29 16:21:13

标签: powershell

我是PowerShell和开发的新手。我正在尝试编写一个脚本,一旦文件超过一定大小,它将通过电子邮件发送给联系人。我有两个单独的功能都单独工作(一个用于检查文件大小,另一个用于生成sendmail使用的文件),但我无法让它们进行交互。

我想执行函数CheckSize,如果变量$ ExceedsSize设置为1,则调用函数SendMail,否则脚本应该完成而不执行其他操作。

我在论坛中搜索过但找不到任何可以应用于我正在做的事情。

   ##Check file to see if it is over a particular size and then send email once threshold is reached.

param( 
    [string]$SiteName = "TestSite",                                                 #Name of Site (No Spaces)
    [string]$Path = "\\NetworkPath\Directory",                                      #Path of directory to check
    [int]$FileSizeThreshold = 10,                                                   #Size in MB that will trigger a notification email
    [string]$Contacts = "MyEmail@email.com"
    )    

CLS

##Creates variable $ExceedsSize based on newest file in folder.
Function CheckSize {
IF ((GCI $Path -Filter *.txt | Sort LastWriteTime -Descending | Select-Object -first 1 | Measure-Object -property Length -sum).sum / 1000000 -gt $FileSizeThreshold) {$ExceedsSize = 1}
ELSE {$ExceedsSize = 0}

Write-Host $ExceedsSize
}


Function SendMail {
    Param([string]$Template, [string]$Contacts, [string]$WarnTime)

    $EmailLocation = "\\NetworkPath\Scripts\File_$SiteName.txt"

    #Will Generate email from params
        New-Item $EmailLocation -type file -force -value "From: JMSIssue@emails.com`r
To: $Contacts`r
Subject: $SiteName file has exceeded the maximum file size threshold of $FileSizeThreshold MB`r`n"

    #Send Email
    #CMD /C "$SendMail\sendmail.exe -t < $EmailLocation"

    }

2 个答案:

答案 0 :(得分:2)

Write-Host $ExceedsSize

之前或之后添加此内容
return $ExceedsSize

将其添加到底部:

$var = CheckSize

if ($var -eq 1){
    SendMail
}

<强>解释
你有两个功能,但实际上并没有运行它们。底部的部分是这样的。
您的CheckSize函数不会为函数的其余部分返回$ExceedsSize;默认情况下,它仍然在函数的范围内。 return x表示将变量传递回主脚本。 $var =表示已为该变量分配。

答案 1 :(得分:1)

根据其他答案,您需要return $ExceedsSize而不是Write-Host(请参阅此处了解为什么写主机被视为有害:http://www.jsnover.com/blog/2013/12/07/write-host-considered-harmful/)。

您也可以在CheckSize函数中调用SendMail函数,例如:

 if ($ExceedsSize -eq 1){SendMail}

您仍然需要在某处调用CheckSize函数:

CheckSize

您可能还想考虑在内置cmdlet的动词 - 名词样式中命名函数。这确实有助于您和他人更明确地使用它们。选择动词时,最好坚持使用已批准的列表:https://msdn.microsoft.com/en-us/library/ms714428(v=vs.85).aspx

并且还要使用相当独特的名称以避免可能的冲突。

我建议采用以下方式:

Get-NewestFileSize

(虽然这应该是它应该返回的)

Send-CCSMail