Stephen Sugumar
Stephen Sugumar

Reputation: 545

Powershell Out-file not working

I have a powershell script which gathers some file information on some remote servers. When writing to the console, I see the results just fine, but they don't seem to be getting written into the specified out-file:

out-file -filepath $filepath -inputobject $date -force -encoding ASCII -width 50
ForEach($server in $serverLists)
{
$result += $server
$result += $break

ForEach($filePath in $filePaths)
{
    $result += $filePath
    $result += $break

    $command = "forfiles /P " + $filePath + " /S /D -1 > C:\temp\result.txt"
    $cmd = "cmd /c $command"

    Invoke-WmiMethod -class Win32_process -name Create -ArgumentList $cmd -ComputerName $server
    sleep 2
    $result += Get-Content \\$server\C$\temp\result.txt
    $result += $break
    $result += $break
    write-host $result
    #out-file -filepath $filepath -Append -inputobject $result -encoding ASCII -width 200
    Remove-Item \\$server\C$\temp\result.txt
}
$result += $break
}

out-file -filepath $filepath -Append -inputobject $result -encoding ASCII -width 200

Upvotes: 0

Views: 1696

Answers (1)

user4003407
user4003407

Reputation: 22102

You use same variable $filepath in two places: as loop variable for foreach loop and outside of loop. foreach loop does not restore value of loop variable after loop ends. So, right after loop ends loop variable will have last value of loop or value where loop was interrupted by break command. If you does not want variable value to be overwritten by foreach loop, then you should choose different name for loop variable.

Upvotes: 2

Related Questions