有没有更好的方法来删除Word文档中的形状,使用PowerShell?

pokxtpni  于 2023-02-16  发布在  Shell
关注(0)|答案(2)|浏览(167)

我一直试图在Word文档中循环所有的形状,找到形状,将它们取消分组,然后删除名称为“-like”“Straight Arrow Connector*”等的形状。然而,我做错了什么,无法找出是什么。但是,它并没有删除每个形状。
我尝试了下面的for循环:

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

但是就像我说的,它并没有删除所有的形状,即使它们的名字和我搜索的名字一样。有更好的方法吗?

ni65a41a

ni65a41a1#

然后,您可以简单地用一个循环来包围它,该循环迭代您希望删除的各种形状名称,如下所示:

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

scyqe7ek2#

发帖后我意识到我应该把形状存储在一个数组中,然后使用while循环删除数组中的所有内容。我这样做了,效果很好:

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

相关问题