Gaurav Gaurav - 3 months ago 11
PowerShell Question

Need to find out if particular folder exists on the server..if yes then which drive C: or D

I need to find out if folder named

Backupeventlog
exists on the server. If yes then which drive C: or D: drive. Also is this folder empty and if not empty what is the date of latest file that has been created under this folder.

Below is the script that I was working, but it doesn't seem to work. :(

$a = Get-Content C:\Lists\Servers.txt
foreach ($Servers in $a)
{
if (Test-Connection $Servers -Count 1 -ea 0 -Quiet)
{
if ("Test-Path \\$Servers\D$\Backupeventlog\*" -or "Test-Path \\$Servers\C$\Backupeventlog\*")
{
$latest = Get-ChildItem \\$Servers\C$\Backupeventlog -Force |
Sort-Object LastWriteTime -Descending |
Select-Object -First 1
Write-Host $Servers - Backupeventlog exists in C: drive and latest file in folder is of date $latest.Lastwritetime
$latest1 = Get-ChildItem \\$Servers\D$\Backupeventlog -Force |
Sort-Object LastWriteTime -Descending |
Select-Object -First 1
Write-Host $Servers - Backupeventlog exists in D: drive and latest file in folder is of date $latest1.Lastwritetime
}
else
{
Write-Host $Servers - Backupevent folder does not exist or empty
}
}
Else
{
Write-Host $Servers - not pinging.
}
}

Answer

Do individual checks, and don't put the entire command in double quotes (otherwise PowerShell will just echo the command string without actually executing the command):

if (Test-Path \\$Servers\C$\Backupeventlog\*) {
  $latest = Get-ChildItem \\$Servers\C$\Backupeventlog -Force |
            Sort-Object LastWriteTime -Descending |
            Select-Object -First 1
  Write-Host 'drive C:'
} elseif (Test-Path \\$Servers\D$\Backupeventlog\*) {
  $latest = Get-ChildItem \\$Servers\D$\Backupeventlog -Force |
            Sort-Object LastWriteTime -Descending |
            Select-Object -First 1
  Write-Host 'drive D:'
} else {
  Write-Host 'not found'
}

If the backup folder can only exist on one of the drives and you can neglect information about servers that have neither you could also do a pipeline like this to get just the latest file from each server where the backup folder exists:

Get-Content C:\Lists\Servers.txt |
  Where-Object { Test-Connection $_ -Count 1 -Quiet } |
  ForEach-Object {
    Get-ChildItem "\\$_\C$\Backupeventlog\*", "\\$_\D$\Backupeventlog\*" -EA SilentlyContinue |
      Sort-Object LastWriteTime -Descending |
      Select-Object -First 1 -Expand FullName
  }

Since the full path still contains the drive information you can extract the drive letter later if required.