Script to list files on a remote Server

SAMUEL VALAPARLA 126 Reputation points
2024-04-02T16:08:48.7166667+00:00

Hi All,

So I'm runnung the below script to be able to retrieve the details of files on a Remote Server at the specified location.

Clear-Host
Set-Location $env:USERPROFILE
Push-Location $env:USERPROFILE
#
# Set Output file Location
#
$OutPutFilename=$env:USERPROFILE+"\Desktop\Filelists.txt"
$ServersFileName=$env:USERPROFILE+"\Desktop\ServerNames.txt"
$ReadDrive=Read-Host "Enter the Drive"
#
# Remove string :\
#
$DriveName=($ReadDrive).Contains(":\")
if ($DriveName=$true)
    {
     $ReadDrive=$ReadDrive.Remove(1,2)
    }
$ReadDirectory=Read-Host "Enter the Directory to List (exclude drive)"
#
# Remove Output file is file already exists
#
if (Test-Path $OutPutFilename)
   {
   Remove-Item $OutPutFilename
   }
$AuthorizedUser=Get-Credential
Get-Content $ServersFilename | ForEach-Object 
  {
  if(-Not(Test-Connection -ComputerName $_ -Count 1 -Quiet))
      {
       Write-Host Server - $_ `t Is currently down or Unreachable -ForegroundColor White -BackgroundColor Red
       return
       }
       else
       { 
        Write-Host `nServer - $_ `t Is Reachable -ForegroundColor Green -BackgroundColor Black
        if (Test-Path -Path \\$_\$ReadDrive$\$ReadDirectory)
           {
            $GCCount=(Get-Childitem "\\$_\$ReadDrive$\$ReadDirectory" -Filter *.txt).count
            if ($GCCount -ge 0)
             { 
              Write-Host Searching.... "\\$_\ReadDrive$\$ReadDirectory"
              WriteHost File listing count is $GCCount -ForegroundColor Green -BackgroundColor Black
              Get-Childitem "\\$_\$ReadDrive$\$ReadDirectory" -Filter *.txt | select @{n='ComputerName';e={_$}},
               FullName, LastAccessTime | select -first 5 | Format-Table -AutoSize | Out-File -Append $OutPutFilename
              }
             }
            else
            {
             Write-Host "`n$_ - Path Not Found `n" -BackgroundColor Red -ForegroundColor Yellow
             }
            return
           }
        }
       Invoke-Item $OutPutFilename

I have already made the Filelists.txt and ServerNames.txt available at the specified location (e.g. C:\Users\User_Name\Desktop\Filelists.txt)

The script prompts me for the below values..

Enter the Drive: E:\

Enter the Directory to List (exclude drive): Folder1\Folder2

cmdlet Get-Credential at command pipeline position 1

Supply values for the following parameters:

Credential

User's image

I go ahead and enter the relevant credentials as prompted.

But after this it's prompting me for certain parameters (as below) which I'm not able to figure out :(

cmdlet ForEach-Object at command pipeline position 2

Supply values for the following parameters:

Process[0]:

I'm basically following the inputs from this link and have compiled the script as per the same.

https://www.slideshare.net/mvcp007/how-to-list-files-on-remote-server-powershell

But for the life of me, I'm unable to proceed beyond the above point. Also the expected execution trace mentioned at the above site doesn't mention this behaviour, so I'm currently lost for options. Can someone please add any tips to help me figure out what I'm missing here?

Thank You.

SV

Windows Server PowerShell
Windows Server PowerShell
Windows Server: A family of Microsoft server operating systems that support enterprise-level management, data storage, applications, and communications.PowerShell: A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
5,396 questions
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
2,128 questions
{count} votes

Accepted answer
  1. Rich Matheisen 45,111 Reputation points
    2024-04-02T18:44:30.84+00:00

    Move the "{" following the ForEach-Object from the line below to the same line as the ForEach-Object.

    The parameter "Member" is positional parameter 0. The PowerShell parser reaches the end of the line without finding any parameters so it asks you for a value for the parameter in position 0.

    If the scriptblock begins on the same line as the ForEach-Object cmdlet and there are no other parameter names, and there are no -Begin, -Process, -End, or -RemaingScripts parameter names, the only scriptblock is assigned to the -Process parameter.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Ian Xue (Shanghai Wicresoft Co., Ltd.) 30,861 Reputation points Microsoft Vendor
    2024-04-03T05:13:37.5533333+00:00

    Hi SAMUEL VALAPARLA,

    The credential $AuthorizedUser is never used in your script. Use Invoke-Command to run commands on remote computers with the specified credential.

    https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/invoke-command

    Clear-Host
    Set-Location $env:USERPROFILE
    Push-Location $env:USERPROFILE
    #
    # Set Output file Location
    #
    $OutPutFilename=$env:USERPROFILE+"\Desktop\Filelists.txt"
    $ServersFileName=$env:USERPROFILE+"\Desktop\ServerNames.txt"
    $ReadDrive=Read-Host "Enter the Drive"
    #
    # Remove string : #
    $DriveName=($ReadDrive).Contains(":")
    #if ($DriveName=$true)
    if ($DriveName -eq $true)
    {
      $ReadDrive=$ReadDrive.Remove(1)
    }
    $ReadDirectory=Read-Host "Enter the Directory to List (exclude drive)"
    #
    # Remove Output file is file already exists
    #
    if (Test-Path $OutPutFilename)
       {
       Remove-Item $OutPutFilename
       }
    $AuthorizedUser=Get-Credential
    Get-Content $ServersFilename | ForEach-Object {
      if(-Not(Test-Connection -ComputerName $_ -Count 1 -Quiet))
      {
        Write-Host Server - $_ `t Is currently down or Unreachable -ForegroundColor White -BackgroundColor Red
        return
      }
      else
      { 
        Write-Host `nServer - $_ `t Is Reachable -ForegroundColor Green -BackgroundColor Black
        $computername = $_
        
        $session = New-PSSession -ComputerName $_ -Credential $AuthorizedUser
        if (Invoke-Command -Session $session -ScriptBlock{
            Test-Path -Path \\$using:computername\$using:ReadDrive$\$using:ReadDirectory} )
        {
          $GC=Invoke-Command -Session $session -ScriptBlock{Get-Childitem "\\$using:computername\$using:ReadDrive$\$using:ReadDirectory" -Filter *.txt }
          if ($GC.Count -ge 0)
          { 
            Write-Host Searching.... "\\$_\ReadDrive$\$ReadDirectory"
            Write-Host File listing count is $GC.count -ForegroundColor Green -BackgroundColor Black
            $ComputerName = $_
            $GC | select @{n='ComputerName';e={$ComputerName}}, FullName, LastAccessTime -first 5| Format-Table -AutoSize | Out-File -Append $OutPutFilename
          }
        }
        else
        {
          Write-Host "`n$_ - Path Not Found `n" -BackgroundColor Red -ForegroundColor Yellow
        }
        Remove-PSSession -Session $session
        return
      }
    }
    Invoke-Item $OutPutFilename
    

    Best Regards,

    Ian Xue


    If the Answer is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.