Search code examples
powershellshapescpu-word

Is there a better way to delete shapes in a Word document, with PowerShell?


I have been trying to loop through all the shapes in a Word document, find the shapes, ungroup them, then delete the ones with names "-like" "Straight Arrow Connector*," etc. However, I am doing something wrong and can't figure out what. It's ungrouping all of the shapes; however, it is not deleting every shape.

I tried the following for loop:

foreach($shape in $doc.Shapes){ 
    if($shape.Name -like "Oval*" -or $shape.Name -like "Oval *"){
            if($shape -ne $null) {  #check if the shape exists before trying to delete it
            $shape.Select()
            $shape.Delete()         
            }
    }
    elseif($shape.Name -like "Straight Arrow Connector*" -or $shape.Name -like "Straight Arrow Connector *"){
            if($shape -ne $null) { #check if the shape exists before trying to delete it
            $shape.Select()
            $shape.Delete()
                }
                                    
                
    }
    elseif($shape.Name -like "Text Box *" or $shape.Name -like "Text Box*"){
        if($shape -ne $null) { #check if the shape exists before trying to delete it
            $shape.Select()
            $shape.Delete()
                }
    }
}

But like I said, it didn't delete every shape, even they had names like the ones I was searching for. Is there a better way?


Solution

  • I realized after posting that I should store the shapes in an array and use a while loop to delete everything inside the array. I did this and it worked:

    $shapes2 = $doc.Shapes
    $shapesOval = @()
    foreach($shape in $shapes2)
    {
            if($shape.Name -like "Oval*" -or $shape.Name -like "Oval *"){
                $shapesOval += $shape 
            }
    }
    
    while($shapesOval.Count -gt 0)
    {
            $shapesOval[0].Delete()
    }