通过电子邮件发送Powershell脚本的所有输出
我有一个Powershell脚本,它循环执行多个文件并将文件信息写入控制台。输出到屏幕的内容正是我需要通过电子邮件发送的内容。通过电子邮件发送Powershell脚本的所有输出
电子邮件部分很简单,但我不知道如何捕获发送到屏幕的内容并将其发送到主体中。这是相关的代码。只有第一次迭代存储在$ emailbody变量中。
EDITED例:
$backupLocations = #List of paths#
$emailBody=""
$currentFile = "nothing"
foreach ($loc in $backupLocations) {
$files = get-childitem "$loc\\*" -recurse -include *.bak
foreach ($file in $files) {
if (test-path $file) {
$prop = Get-ItemProperty -Path "$file"
Write-Output $prop | tee-Object -variable $currentFile
$emailBody += $currentFile
}
}
}
# Code to send $emailBody in an email. That is working fine.#
我看到屏幕上是值得的文件的信息页面,例如这样的:
Directory: \\directory\directory\directory\myfolder
Mode LastWriteTime Length Name
---- ------------- ------ ----
-a--- 5/10/2011 10:00 PM 1986048 file.bak
诚然,我没有RTFM并已基本攻击我的方式,通过Powershell至此,所以请原谅我,如果答案是明显的。
你不应该试图这样的事:
$emailBody=""
foreach ($file in $files) {
if ($file) {
$prop = Get-ItemProperty -Path "$file"
Write-Output $prop | tee-Object -Variable currentFile
$emailBody += $currentFile
}
}
有更好的方法做你虽然做什么。因此,如果您可以详细说明$文件是什么以及是否真的要输出到控制台等等,我们可以看看更好的脚本。
您更新后:
岂不像下面为你工作:
$files = gci "$loc\\*" -recurse -include *.bak
Write-Host $files
$emailBody = $files | ft
我不认为需要什么都重要!像test-path
- 为什么?你正在做一个gci,当然它存在!
这解决了覆盖'$ emailBody'的问题是不是?但是每个文件的'write-output'都不是很好,它会为每个文件打印头文件,对吗? – 2011-05-11 20:16:56
是的,我只是在暗示。基于什么是$文件,他应该可以通过这种方式进行管理或者直接使用'gci'什么的。 – manojlds 2011-05-11 20:18:50
@manojlds,我试过你的代码,但需要把一个值放到$ currentFile中,因为Tee-Object命令行开关报告“无法将参数绑定参数'变量',因为它是空的。”我设置变量等于单词“nothing”,脚本运行。但电子邮件报告显示单词“无”重复100次以上(即每发现一个文件一次) – 2011-05-11 20:50:31
每次迭代您的$emailBody
被覆盖。此外,您的属性的标题将打印为我认为的每个文件。我会尝试:
$props = @() $files | % { $prop = Get-ItemProperty -Path "$file" $props += $prop } $emailbody = $props | format-table -auto
一些基本的问题:是一个函数?或只是你的脚本的一部分?你用'if($ file)'检查什么? – 2011-05-11 19:58:16
@empo,谢谢,我已经添加了其余的代码。我只是在测试$文件是否存在,我发现最好使用'test-path'命令执行 – 2011-05-11 20:48:15
@Ken Pespisa:你还好吗还是仍然有麻烦? – 2011-05-11 20:57:09