powershellrobocopy

Exclude files with no extension with robocopy?


I'm new to Powershell (as of this morning). I have put together this script (directories reflect local testing):

$Destinations = Get-Content "C:\PowerShellConfigFiles\destinationPaths.txt"
$Source = [IO.File]::ReadAllText("C:\PowerShellConfigFiles\sourcePath.txt")
$ExcludeFiles = [IO.File]::ReadAllText("C:\PowerShellConfigFiles\xf.txt")
$ExcludeDirectories = [IO.File]::ReadAllText("C:\PowerShellConfigFiles\xd.txt")

foreach($Destination in $Destinations)
{
    robocopy $Source $Destination /E /xf $ExcludeFiles /xd $ExcludeDirectories
}

In my ExcludeFiles I have a couple extensions such as .xlsx. I also want to exclude files that do not have any extension at all. I haven't been able to find a way to do this with the /xf option. Can this be done, or do I need to explore another approach to handle exluding files with no extension?


Solution

  • Filter a listing of files in $Source with a regex to get a list of files without extensions, and add that list to $ExcludeFiles. Replace /xf $ExcludeFiles with this:

    /xf ($ExcludeFiles + (Get-ChildItem -File $Source -Name | ?{$_ -notmatch '\.'}))    
    

    For compatibility with versions of PowerShell lower than 3.0, which don't support the -File switch for Get-ChildItem, use this instead:

    /xf ($ExcludeFiles + (Get-ChildItem $Source | ?{! $_.PSIsContainer} | select -ExpandProperty Name | ?{$_ -notmatch '\.'})) 
    

    By definition, a file with an extension is a file with a dot in the name, so $_ -notmatch '\.' selects only names without extensions.