[英]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.