简体   繁体   中英

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?

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

'''

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM