0
votes

I want to make a script. It will read content from a file which recorded path. And run test-path for path in the file to verify if these file/path exists on local machine.

Here is my current powershell code:

Foreach ($path in (get-content C:\temp\pathlist.txt)){
    [PSCustomObject]@{
        path = $path
        Exists = test-path $path
    }
}

However, it will always return 'False' even the path exists and even there is only one line in the txt. I also tried -TotalCount to restrict the line it reads. But it failed again.

Besides, actually I would like to do some string process on the txt. The txt in above code just contain normal path. But the acutal txt I would got has a format as: "C:\Windows\","1" I used to use $path= $path.split(",")[0] to get the "C:\windows". But to fix the always 'False' issue, I use a simple txt instead and remove this part in my code.

2

2 Answers

1
votes

Your code seems to work fine. It must be something with your text formatting, I think? Could you also share the text file you're using to test with?

My text file:

C:\Temp
C:\Windows
C:\NoExist
C:\Program Files

The code:

Foreach ($path in Get-Content .\test.txt) {
   [PSCustomObject]@{
        path   = $path
        Exists = Test-Path $path
   }
}

My output:

path             Exists
----             ------
C:\Temp            True
C:\Windows         True
C:\NoExist        False
C:\Program Files   True

Edit after comment:

You can split your path on " using .split(), example below.

New text file:

"C:\temp\","1"
"C:\Windows\","3"
"C:\NoExist\","1"
"C:\Program Files\","2"

New code:

Foreach ($path in Get-Content .\test.txt) {
    $path = $path.Split('"')
    [PSCustomObject]@{
        path   = $path[1]
        Exists = Test-Path $path[1]
    }
}

Output:

path              Exists
----              ------
C:\temp\           False
C:\Windows\         True
C:\NoExist\        False
C:\Program Files\   True
0
votes

Your code worked fine for me - the only thing I see is that you have a space between for and each but that may only be a typo

I used a file with both, existing and non-existing directories to test your code and it worked fine:

$tested_paths = foreach ($path in (Get-Content ".\paths.txt")) {
    [PSCustomObject]@{
        path_name   = $path
        path_exists = Test-Path $path
    }
}

$tested_paths | Format-Table