Search code examples
powershellfor-loopforeachlogicstring-comparison

How to check all strings before doing the next step


I want to perform string-comparison. I use a foreach loop, but I want to do move-item after all strings have been compared.

My concept is " If all of strings not match, do move-item. "

How can I do that?

here is my present code but it is " if match,do move-item

$Myfile=dir *my file name*
$directory=dir D:\example    (there are many directory)

foreach($dir in $directory){
 if($dir match $Myfile.basename ){
   move-item $Myfile.fullname -destination D:\example
 }
}

I want to do move-item after string comparison to ensure that my file name doesn't exist $directory here is what I want to achieve

if( ("all of the directory Name") -notmatch $myfile.basename ){
  move-item XXX to XXX
}

if I use -notmatch , it will do move-item at the first time loop. So I need to do move-item after checking them all...


Solution

  • You can set a variable to true if something matches:

    $Myfile=dir *my file name*
    $directory=dir D:\example    (there are many directory)
    
    $move = $false
    foreach($dir in $directory){
        if($dir match $Myfile.basename ){
            $move = $true
        }
    }
    if ($move){
        move-item $Myfile.fullname -destination D:\example
    }