powershellforeachcopy-pasteget-childitemforeach-object

How to copy a pictures but only certain filename with powershell


H want to copy some photos from a folder to another. in the folder has a lot of photos, but I only want to copy a certain filename that i input to a multiple textbox.

this is what I did so far:

` $USBFolder = "F:"

$Filname = $Textbox.Text -split ','

$ImageSource = "c:\Folder"

$Filnename | ForEach-Object {Get-ChildItem -FIlter *.jpg | Where-Object {$_.Basename -match $Filename} | Copy-Item -Destination $USBFolder -Force} `

But it didnt do anything. please tell me what I do wrong?


Solution

  • Avoid using to many conditions and Cmdlets in a single pipeline.
    Is not performatic, and it makes it hard to debug.
    Do it step by step, specially if you're not experienced in PS.
    Try out this code, and read the comments.

    
    $listOfNames = $Textbox.Text.Split(',')
    $allPhotos = Get-ChildItem -Path <# The path to your folder #> -Filter *.jpg
    foreach ($file in $allPhotos) {
    
        # If the text from the list is exactly the file name, you want to use -in.
        # I.E.: the list is 'superPicture', 'notSuperPic'
        # and the file name is 'superPicture.jpg'.
        # We want to know if the Base Name is IN that list.
        if ($file.BaseName -in $listOfNames) {
            Copy-Item -Path $file.FullName -Destination $USBFolder -Force
        }
    
        # If you want to know if a file name contains the text of any item of the list
        # we iterate through the list and use the -like operator.
        # The '*' is the wildcard here.
        # I.E.: the file name is 'superMegaNeatPic.jpg'
        # and the text is 'MegaNeat'
        foreach ($text in $listOfNames) {
            if ($file.BaseName -like "*$text*") {
                Copy-Item -Path $file.FullName -Destination $USBFolder -Force
            }
        }
    }
    

    In your case, using -match is not ideal, because -match uses regex, which can complicate things for simple file names.
    Is important to notice that in the first 'if', we are checking if a text is 'in' a list of text. So the text in the list must be equal the file base name.

    On the second 'if' we are looking for files which contain the text of at least one text in the list.

    Hope it helps!