Get-Content: Cannot find path because it does not exist

23,864

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.

  1. Move the script file and txt into the same directory.
  2. 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.

Share:
23,864
Nikhil Tamhankar
Author by

Nikhil Tamhankar

Updated on July 14, 2022

Comments

  • Nikhil Tamhankar
    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?

  • Matt
    Matt over 8 years
    Unless you are referring to a bug or something both those statements are the same.
  • Nikhil Tamhankar
    Nikhil Tamhankar over 8 years
    This is not working. Still the same error. What should I do?
  • bdn02
    bdn02 over 8 years
    Maybe a security problem, if you call "type c:\Servers.txt" from command prompt, what happend?