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

Time:01-26

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?

CodePudding user response:

So, 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()
}

'''

CodePudding user response:

Then you can simply surround that with a loop iterating over the various shape names you wish to delete like this:

foreach ($name in 'Oval', 'Straight Arrow Connector', 'Text Box') {
    $shapes = @($doc.Shapes | Where-Object {$_.Name -like "$name*"})
    while ($shapes.Count -gt 0) { 
        $shapes[0].Delete()
    }
}
  • Related