将Powershell输出设置为变量

时间:2018-12-21 17:53:31

标签: powershell

因此,我正在处理一个将变量设置为文件路径的脚本,然后它将使用该路径的Get-ChildItem,如果这些项目超过一定大小,则它将使用文件名和文件大小。

Get-ChildItem $file | ? {$_.Length -gt 1mb} | ForEach-Object {Write-Host "Users:" $_.name "have Outlook Data Files larger than 8gb, with a total of" ("{0:N2}" -f($_.length/1mb)) "mb"}

我正在尝试将此输出分配给变量,以便我可以利用第二条命令并将此输出通过电子邮件发送给自己。除非有更好的方法可以做到这一点。

2 个答案:

答案 0 :(得分:1)

$content = gci -Recurse -File | ? { $_.Length -gt 40000 }

在邮件正文中包含$ content。

答案 1 :(得分:0)

正如前面的评论所指出的那样,您的主要问题似乎是对Write- * cmdlet在PowerShell中的工作方式有误解。写主机输出直接绕过normal PowerShell output streams到主机/控制台。通过在PowerShell会话中运行以下命令,可以快速说明这一点:

var arr = [{x:1},{x:2},{x:4}]
arr.reduce(function(acc,currVal){return acc + currVal.x}) 
// destructing {x:1} = currVal;
Now currVal is object which have all the object properties .So now 
currVal.x=>1 
//first iteration** : 0 +1 => Now accumulator =1;
//second iteration** : 1 +2 => Now accumulator =3;
//third iteration** : 3 + 4 => Now accumulator = 7;
No more array properties now the loop breaks 
//solution=7

如果执行上述操作,您会发现没有分配$ MyVariable1值(并且您可以使用$MyVariable1 = Write-Host "Hello, World!" $MyVariable2 = Write-Output "Hello, World!" $MyVariable1 $MyVariable2 这样的值对其进行实际测试),但是$ MyVariable2的值将为“ Hello,World!”。 '。

为使您的示例将输出转换为变量,您需要运行以下内容:

$null -eq $MyVariable1

要了解有关PowerShell输出流的更多信息,您可能还需要阅读about_redirection article

相关问题