Powershell – ForEach to Out-File in PowerShell

file-ioforeachpowershell

I am trying to output the results of this script to a text file. All of my attempts so far just leave me with a blank text file.

I am not even sure if Out-File is the correct cmdlet. What is the placement and syntax to correctly output my results to a .txt file?

$store = Get-Content C:\Users\store_list.txt <#list of numbers#>

ForEach ($item in $store)
{
    $item = [int]$item
    Write-Host "Item: " $item  <# Used to show list item being operated
                                  on, can be commented out #>

    if ($item -gt 0 -and $item -le 255)
    {
        Write-Host "10.128.$item.50"
    }

    if ($item -ge 256 -and $item -le 511)
    {
        $item1 = $item-256
        Write-Host "10.129.$item1.50"
    }

    if ($item -ge 512 -and $item -le 767)
    {
        $item2 = $item-512
        Write-Host "10.130.$item2.50"
    }
}

Best Answer

The easiest way to accomplish your task would be like this:

$store = Get-Content C:\Users\store_list.txt <#list of numbers#>

ForEach ($item in $store) 
{
    $item = [int]$item
    Write-Verbose "Item:  $item"  <#Use Write-Verbose so you can enable/disable it by
                                passing the -Verbose parameter #>

    if ($item -gt 0 -and $item -le 255)
    {
        "10.128.$item.50" |  Out-File -filePath $filePath -append -encoding utf8
    }
    if ($item -ge 256 -and $item -le 511)
    {
        $item1 = $item-256
        "10.129.$item1.50" |  Out-File -filePath $filePath -append  -encoding utf8
    }
    if ($item -ge 512 -and $item -le 767)
    {
        $item2 = $item-512
        "10.130.$item2.50" |  Out-File -filePath $filePath -append -encoding utf8
    }
}