[英]Pass parameter from one Powershell function to another
我是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"
}
在Write-Host $ExceedsSize
之前或之后添加此Write-Host $ExceedsSize
:
return $ExceedsSize
将此添加到底部:
$var = CheckSize
if ($var -eq 1){
SendMail
}
说明
您有两个功能,但实际上没有运行它们。 底部的部分可以做到这一点。
您的CheckSize函数不会为该函数的其余部分返回$ExceedsSize
。 默认情况下,它仍在功能范围内。 return x
表示将变量传递回主脚本。 $var =
表示分配了该变量。
对于其他答案,您需要return $ExceedsSize
而不是使用Write-Host
(请参阅此处以了解为什么Write-Host被认为是有害的: http : //www.jsnover.com/blog/2013/12/07/write-host -考虑到有害/ )。
您也可以从CheckSize函数中调用SendMail
函数,例如:
if ($ExceedsSize -eq 1){SendMail}
您仍然需要在其他地方调用CheckSize函数:
CheckSize
您可能还需要考虑以内置cmdlet的动词-名词样式命名函数。 这确实有助于使它们对您和他人的使用更加明确。 选择动词时,最好坚持使用批准的列表: https : //msdn.microsoft.com/zh-cn/library/ms714428(v=vs.85).aspx
并使用相当独特的名称,以避免可能的冲突。
我建议采取以下措施:
Get-NewestFileSize
(尽管那是应该返回的内容)
和
Send-CCSMail
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.