I'm trying to import a .txt file that has one folder path per line. I'm trying to see if multiple folder paths exists within the notepad file. I'm unsuccessful right now because it appears that my script is thinking that the entire .txt file is the file path or because I'm not having the script read the .txt file correctly. I'm wondering if this is possible?
$Folder = 'C:\Users\User\Downloads\FolderExist.txt'
Get-Content -Path $Folder
if (Test-Path -Path $Folder) {
"Path exists!"
} else {
"Path doesn't exist."
}
Export-Csv -Path "C:\Users\User\Documents\FolderExist.csv" -NoTypeInformation
This is the error that I'm receiving
Get-Content : Cannot find path 'C:\Users\User\Downloads\FolderExist.txt' because it does not exist.
At line:2 char:1
Get-Content -Path $Folder
~~~~~~~~~~~~~~~~~~~~~~~~~
CategoryInfo : ObjectNotFound: (C:\Users\_Micha...FolderExist.txt:String) [Get-Content], ItemNotFoundException
FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand
CodePudding user response:
The error you're getting says the file you're trying to parse doesn't exist. Make sure that you actually have a file here:
'C:\Users\User\Downloads\FolderExist.txt'
And some general improvements: First, save your text file contents into a variable:
$Folder = 'C:\Users\User\Downloads\FolderExist.txt'
$MyPaths = Get-Content -Path $Folder
Then, to test each path one by one, use a foreach
loop, and capture the output again. Here, I've added the folder path to the output so you can see which folders did and did not exist:
$output = Foreach ($folderPath in $MyPaths) {
if (Test-Path -Path $folderPath) {
Write-Output "Path '$folderPath' exists!"
} else {
Write-Output "Path '$folderPath' doesn't exist."
}
}
Finally, write the results out to a file
$output | Out-File -Path "C:\Users\User\Documents\FolderExist.csv"
file looks like:
Path 'c:\windows\' exists!
Path 'c:\users\' exists!
Path 'c:\bogus\' doesn't exist.