简体   繁体   English

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

[英]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.我一直在尝试遍历 Word 文档中的所有形状,找到形状,取消组合,然后删除名称为“-like”“Straight Arrow Connector*”等的形状。但是,我做错了,可以弄清楚什么。 It's ungrouping all of the shapes;它正在取消所有形状的分组; however, it is not deleting every shape.但是,它并没有删除所有形状。

I tried the following for loop:我尝试了以下 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()
                }
    }
}

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.所以,我在发布后意识到我应该将形状存储在一个数组中并使用 while 循环删除数组中的所有内容。 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()
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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