I've referenced this question to get me this far: redirecting test-path output to text file
I'm essentially using the same examples provided, I just need to create an output of the invalid file paths also.
I'm attempting to check if files exist via UNC paths. so I'm targeting specific files (C:\Users\Goalie\Desktop\folder\1.txt, \2.txt, \3.txt) I know each file path already, I'm just attempting to see if the files at those UNC paths are actually there or not.
\paths.txt includes several UNC file paths. Ex:
C:\Users\Goalie\Desktop\folder\1.txt
C:\Users\Goalie\Desktop\folder\2.txt
C:\Users\Goalie\Desktop\folder\3.txt
The below code currently works, however, only for the valid file paths. I need the invalid file paths as well.
$inputfile = "C:\Users\Goalie\Desktop\folder\paths.txt"
$outputexistingfiles = "C:\Users\Goalie\Desktop\folder\existingfiles.txt"
$outputmissingfiles = "C:\Users\Goalie\Desktop\folder\missingfiles.txt"
Get-Content $inputfile |
Where-Object {Test-Path $_} |
Out-File -FilePath $outputexistingfiles -Append
Note: This will be used to test several million paths in its final stage. Is this the most efficient method? I've read that the below version of test-path is faster, however, I'm not sure how to incorporate it into the above as it outputs either True or False, instead of the actual UNC path.
$inputfile = "C:\Users\Goalie\Desktop\folder\paths.txt"
$filepaths = Get-Content $inputfile
$filepaths.ForEach({Test-path $_ -PathType leaf}) | Out-File -FilePath $outputmissingpaths -Append
Many thanks for any help. -Goalie
CodePudding user response:
This should should list the missing paths:
Get-Content $inputfile |
Where-Object {!(Test-Path $_)} |
Out-File -FilePath $outputmissingfiles -Append
CodePudding user response:
This will be used to test several million paths in its final stage. Is this the most efficient method?
Your use case calls for:
A
switch
statement for efficient line-by-line reading of a text filecombined with direct use of .NET APIs for efficient writing of text files, using the
System.IO.StreamWriter
class.
$inputfile = 'C:\Users\Goalie\Desktop\folder\paths.txt'
# Initialize the output file writers.
# Note: Be sure to use *full* paths, because .NET's working directory
# usually differs from PowerShell's
$outExisting = [System.IO.StreamWriter] 'C:\Users\Goalie\Desktop\folder\existingfiles.txt'
$outMissing = [System.IO.StreamWriter] 'C:\Users\Goalie\Desktop\folder\missingfiles.txt'
switch -File $inputfile {
default {
if ([System.IO.File]::Exists($_)) {
$outExisting.WriteLine($_)
} else {
$outMissing.WriteLine($_)
}
}
}
$outExisting.Close(); $outMissing.Close()