2016-09-16 81 views
1

我想用PowerShell在PowerPoint幻燈片筆記中進行語法更新筆記。能夠做到這一點將節省大量的時間。下面的代碼允許我使用PowerShell編輯筆記字段,但每次都會弄亂格式。powershell編輯幻燈片筆記

$PowerpointFile = "C:\Users\username\Documents\test.pptx" 
$Powerpoint = New-Object -ComObject powerpoint.application 
$ppt = $Powerpoint.presentations.open($PowerpointFile, 2, $True, $False) 
foreach($slide in $ppt.slides){ 
    if($slide.NotesPage.Shapes[2].TextFrame.TextRange.Text -match "string"){ 
     $slide.NotesPage.Shapes[2].TextFrame.TextRange.Text = $slide.NotesPage.Shapes[2].TextFrame.TextRange.Text -replace "string","stringreplaced" 
    } 
} 
Sleep -Seconds 3 
$ppt.Save() 
$Powerpoint.Quit() 

例如,現在它會遍歷每張幻燈片的筆記和更新字串到stringreplaced但隨後的整個筆記文本變得大膽。在我的筆記中,我在筆記的頂部有一個粗體字,然後是下面的文字。例如,在幻燈片記我這個樣子的:

注意標題

幫我這個字符串。

後的PowerShell更新備註字段將其保存到一個新的.pptx文件,但說明現在看起來是這樣的:

注意標題

幫我這個stringreplaced。

有關如何更新幻燈片筆記而不會弄亂筆記中找到的任何格式的任何想法?它只會讓腳本更新的幻燈片格式化。

回答

2

當您更改PPT中textrange的整個文本內容時,如您的代碼所做的那樣,更改後的textrange將選取該範圍中第一個字符的格式。我不知道你怎麼會在PowerShell中做到這一點,但這裏是在PPT VBA演示了同樣的問題,並展示瞭如何使用PPT自身的更換方法,而不是解決問題的例子:

Sub ExampleTextReplace() 
' Assumes two shapes with text on Slide 1 of the current presentation 
' Each has the text "This is some sample text" 
' The first character of each is bolded 

' Demonstrates the difference between different methods of replacing text 
' within a string 

    Dim oSh As Shape 

    ' First shape: change the text 
    Set oSh = ActivePresentation.Slides(1).Shapes(1) 
    With oSh.TextFrame.TextRange 
     .Text = Replace(.Text, "sample text", "example text") 
    End With 
    ' Result: the entire text string is bolded 


    ' Second shape: Use PowerPoint's Replace method instead 
    Set oSh = ActivePresentation.Slides(1).Shapes(2) 
    With oSh.TextFrame.TextRange 
     .Replace "sample text", "example text" 
    End With 
    ' Result: only the first character of the text is bolded 
    '   as it was originally 

End Sub 
+0

使用這種方法似乎採取了全部內容並取而代之。而不是用「示例文本」替換單詞「示例文本」,而是用「示例文本」替換整個.Text文本。 –

+0

不在這裏。也許這個PowerShell版本不是很準確的翻譯。發佈你現在的代碼;也許更熟悉PowerShell的人可以看看。 –

+0

有點老,我知道,但這裏是一個工作的PowerShell片段:'$ presentation.Slides [1] .Shapes [4] .TextFrame.TextRange.Replace($ f0a,$ f1a)''。這項工作很好,不會打擾形狀中的其他格式。 (PowerShell 2016)。 –