1

My very rudimentary script does not out put the results of the query to a file.

I've tried Out-File, Export-CSV. Sometimes a file is written, but it doesn't contain any data. Its just blank.

And I believe write-host is something I should not be using, but am not skilled enough to know how i SHOULD be dealing with powershell results.

# Read input file of computer names and paths
$computers = Get-Content C:\temp\test-path-test.txt
$paths = Get-Content C:\temp\test-path-test-paths.txt

# Nested Loop through each computer name in the array, and each path
foreach ($computer in $computers) {

    foreach ($path in $paths) {

    $exists = Test-Path "\\$computer\$path"

    If ($exists -eq $true ) { Write-Host  $computer, $path, 'This Path Exists'}

    Else { Write-Host $computer, $path 'Path Not Found' } 
    }
}

I was hoping it would output a csv file of ComputerName,Path, and whether the path exists or not.

Can anyone shed any light on how I can better output the results of this to a file?

2 Answers 2

2

Create a [PSCustomObject] and gather output from the nested foreach in a variable

$computers = Get-Content C:\temp\test-path-test.txt
$paths = Get-Content C:\temp\test-path-test-paths.txt

# Nested Loop through each computer name in the array, and each path
$Data = foreach ($computer in $computers) {
    foreach ($path in $paths) {
        [PSCustomObject]@{
            Computer = $Computer
            Path     = $Path
            Exists   = Test-Path "\\$computer\$path"
        }
    }
}
$Data
$Data | Export-Csv -Path New.csv -NoTypeInformation
Sign up to request clarification or add additional context in comments.

Comments

0

Created a custom object, add it to a list of results. Export the results however you want.

Something like this should work for you:

$results = @()

foreach ($computer in $computers){
    foreach ($path in $paths){

        $exists = Test-Path "\\$computer\$path"

        $results.Add(New-Object -TypeName PSObject -Property (@{Computer=$computer; Path=$path; Exists=$exists}))

    }
}

$results | Export-Csv -NoTypeInformation "C:\Path\To\Export.csv"

Leave a comment if you have any issues :-)

2 Comments

Thanks. I'll give it a shot.
@Wilmo Please mark one of the responses as an answer to your question and upvote it for future visitors :-)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.