Logan Gregory
Logan Gregory

Reputation: 1

Setting Powershell output to a variable

So I'm working on a script that will have a variable set to a file path, then it will Get-ChildItem of that path and if these items are over a certain size then it will print the output of that with the name of the file and the file size.

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"}

I am trying to assign this output, to a variable so I can utilize the second command and send this output in an email to myself. Unless there is a better way to accomplish this.

Upvotes: 0

Views: 784

Answers (2)

Mike Campbell
Mike Campbell

Reputation: 41

As the previous comments have pointed out, it seems like your primary problem might be a misunderstanding about how the Write-* cmdlets work in PowerShell. Write-Host outputs directly to the host/console, bypassing the normal PowerShell output streams. This can be illustrated quickly by running the following commands in a PowerShell session:

$MyVariable1 = Write-Host "Hello, World!"
$MyVariable2 = Write-Output "Hello, World!"
$MyVariable1
$MyVariable2

If you run the above, you'll find that $MyVariable1 has no value assigned (and you could actually test it for that with something like $null -eq $MyVariable1) but $MyVariable2 will have the value 'Hello, World!'.

For your example to work to get your output into a variable you would need to run something like the following:

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

To learn more about PowerShell output streams you might also want to read the about_redirection article.

Upvotes: 0

No Refunds No Returns
No Refunds No Returns

Reputation: 8356

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

Include $content as the body of your email.

Upvotes: 1

Related Questions