获取内容:找不到路径,因为它不存在

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

我编写了以下脚本,其中 Servers.txt 文件包含服务器列表:

$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

如果我 运行 这个脚本,我得到错误:

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

为什么我总是收到这个错误?我该如何解决?

努力改变 ...(gc .\Servers.txt)......(gc -Path .\Servers.txt)...

看这个:https://technet.microsoft.com/en-us/library/hh849787.aspx

根据评论,您的 txt 文件位于 C: 的根目录中,应该 没问题。问题是您的脚本无处确认相对于该 txt 文件的 运行 位置。我想,如果您调用 Get-Location,您会看到一条不同的路径,并且很可能是脚本来自 运行 的路径。

最好选择以下任一选项。

  1. 将脚本文件和txt移动到同一目录。
  2. 调用路径时使用绝对路径。 foreach($server in (gc "c:\Servers.txt")){

我遇到了类似的问题。 我做错的是我的文件夹选项被设置为隐藏已知文件类型的扩展名,导致我的 .txt 文件实际上是一个 .txt.txt 文件。

您的 Servers.txt 文件位于其他位置或其扩展名不同。

使用 Get-Location 确保您位于 Servers.txt 文件的正确路径中。 使用 dir 查看是否在您所在的目录中看到 Servers.txt 文件。

您的 Servers.txt 文件扩展名可能是 Servers.txt.txt

转到 ControlPanel/Appearanceand Personalization/FileExplore Options/View 并取消选中“隐藏已知文件类型的扩展名。 现在检查您的 *.txt 文件,您可能会看到 Computres.txt.txt Delete last .txt