Home > OS >  Powershell .ps1 script. Using -contains / -notcontains and Get-ChildItem for getting files in a fold
Powershell .ps1 script. Using -contains / -notcontains and Get-ChildItem for getting files in a fold

Time:04-23

I expected this script to copy files in the FTP folder, only if they don't exist neither in the Pendientes or Procesados Folders. However, every time I run the script, it copies all files from FTP. I must be mising something obvious, but unable to find out. Any ideas?

$ProcesadosLocation  = 'C:\PROCESADOS'
$PdtesLocation = 'C:\PENDIENTES'
$FtpLocation    = 'C:\FTP'

$Procesados  = Get-ChildItem -LiteralPath $ProcesadosLocation -Recurse -File
$Pdtes = Get-ChildItem -LiteralPath $PdtesLocation -Recurse -File
$ftp = Get-ChildItem -LiteralPath $FtpLocation -Recurse -File

ForEach ($File in $ftp)
{
    If    (($Procesados.Name -notcontains $File.Name) -and ($PdtesLocation.Name -notcontains $File.Name ))
    {
        Write-Output "New file detected: $($File.FullName)"
        Copy-Item -LiteralPath $File.FullName -Destination $PdtesLocation    
    }
    
}

CodePudding user response:

Here is one way you could simplify your code:

$ProcesadosLocation = 'C:\PROCESADOS'
$PdtesLocation = 'C:\PENDIENTES'
$FtpLocation = 'C:\FTP'

$ftp = Get-ChildItem -LiteralPath $FtpLocation -Recurse -File
# combine boths arrays of values in one
$excludeMe = @(
    Get-ChildItem -LiteralPath $ProcesadosLocation -Recurse -File
    Get-ChildItem -LiteralPath $PdtesLocation -Recurse -File
).Name

foreach($file in $ftp) {
    if($file.Name -in $excludeMe) {
        # if this is `$true`, just go next
        continue
    }
    Write-Output "New file detected: $($File.FullName)"
    Copy-Item -LiteralPath $file.FullName -Destination $PdtesLocation
}

CodePudding user response:

Since both the -Path and -LiteralPath parameters of Get-ChildItem kan take an array of paths, you can combine the file names to exclude using just one call to Get-ChildItem.

Then, with the help of a Where-Object clause it should be easy enough to only copy files that do not exist in bothg paths:

$ProcesadosLocation = 'C:\PROCESADOS'
$PdtesLocation      = 'C:\PENDIENTES'
$FtpLocation        = 'C:\FTP'

$exclude = (Get-ChildItem -LiteralPath $ProcesadosLocation, $PdtesLocation -Recurse -File).Name

Get-ChildItem -LiteralPath $FtpLocation -Recurse -File |
Where-Object { $exclude -notcontains $_.Name } |
ForEach-Object {
    Write-Output "New file detected: $($_.FullName)"
    Copy-Item -LiteralPath $_.FullName -Destination $PdtesLocation    
}
  • Related