简体   繁体   English

Get-Content读取行时如何调用函数

[英]How to call a function when Get-Content reads a line

I am setting up a script that will send me an email every time a certain log file is written to but when Get-Content reads a new line, the pipe does not call the sendmail function. 我正在设置一个脚本,该脚本将在每次写入某个日志文件时向我发送电子邮件,但是当Get-Content读取新行时,管道不会调用sendmail函数。

The sendmail function is defined before the following line and successfully sends me an email by itself. sendmail函数在下一行之前定义,并且可以成功向我自己发送一封电子邮件。

Get-Content -Tail 0 -Wait app.log | sendmail

You need to learn what a process block is. 您需要了解什么是流程块。 It runs for every element piped in. Put your code in the process block, and it will do what you want, as someone else already answered. 它针对插入的每个元素运行。将您的代码放入流程块中,它将执行您想要的操作,就像其他人已经回答了那样。 Process blocks are really important in powershell. 流程块在Powershell中非常重要。

function hi { 
  process { 
   'hi' 
  } 
}

Get-Content -Tail 0 -Wait app.log | hi
hi
hi
hi

You should get the value from the pipeline through a process block: 您应该通过流程块从管道中获取值:

function sendmail {
    process {
        $secpasswd = ConvertTo-SecureString "password" -AsPlainText -Force 
        $cred = New-Object System.Management.Automation.PSCredential ("username", $secpasswd) 
        Send-MailMessage -SmtpServer mysmtp -Credential $cred -UseSsl -From 'myemail@domain.com' -To 'toemail@domain.com' -Subject 'TEST'
    }
}

This will tell PowerShell that you want this section of code to run for every object passed on the pipeline (every line in this case). 这将告诉PowerShell,您希望此部分代码针对在管道上传递的每个对象(在本例中为每一行)运行。 If you want to access the current object from inside the process block, use $_ as a variable. 如果要从流程块内部访问当前对象,请使用$_作为变量。

See Piping Objects to Functions 请参见将对象管道连接到函数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM