Get-Content: Cannot find path because it does not exist
Solution 1
As per a comment your txt file is in the root of C: and that should be fine. Problem is nowhere does your script confirm the running location relative to that txt file. I imagine if you called Get-Location
you would see the a different path and likely the one where the script is running from.
Either of the following options would be preferable.
- Move the script file and txt into the same directory.
- Use the absolute path when calling the path(s).
foreach($server in (gc "c:\Servers.txt")){
Solution 2
Go to ControlPanel/Appearanceand Personalization/FileExplore Options/View and uncheck "Hide extensions for known file types. Now check your *.txt file possibly you will see Computres.txt.txt Delete last .txt
Solution 3
I was having a similar problem. What I was doing wrong was my folder options was set to hide extensions for known file types, resulting in my .txt file actually being a .txt.txt file.
Nikhil Tamhankar
Updated on July 14, 2022Comments
-
Nikhil Tamhankar almost 2 years
I wrote the following script in which
Servers.txt
file contains a list of servers:$Result = @() foreach ($server in (gc .\Servers.txt)) { $computer = [ADSI](”WinNT://” + $server + “,computer”) $Group = $computer.psbase.children.find(”Administrators”) function getAdmins { $members = ($Group.psbase.invoke(”Members”) | % { $_.GetType().InvokeMember(”Adspath”, ‘GetProperty’, $null, $_, $null) }) -replace ('WinNT://DOMAIN/' + $server + '/'), '' -replace ('WinNT://DOMAIN/', 'DOMAIN\') -replace ('WinNT://', '') $members } $Result += Write-Output "SERVER: $server" $Result += Write-Output ' ' $Result += ( getAdmins ) $Result += Write-Output '____________________________' $Result += Write-Output ' ' } $Result > c:\results.txt Invoke-Item c:\results.txt
If I run this script, I get the error:
PS C:> C:\LocalUsers.ps1 Get-Content : Cannot find path 'C:\Servers.txt' because it does not exist. At C:\LocalUsers.ps1:3 char:23
- foreach($server in (gc <<<< .\Servers.txt)){
- CategoryInfo : ObjectNotFound: (C:\Servers.txt:String) [Get-Content], ItemNotFoundException
- FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetContentCommand
Why do I keep getting this error? How do I solve this?
- foreach($server in (gc <<<< .\Servers.txt)){
-
Matt over 8 yearsUnless you are referring to a bug or something both those statements are the same.
-
Nikhil Tamhankar over 8 yearsThis is not working. Still the same error. What should I do?
-
bdn02 over 8 yearsMaybe a security problem, if you call "type c:\Servers.txt" from command prompt, what happend?