VBS代码中的With语句,在PowerShell中的表达方式

The With statement in the VBS code, how expressed in PowerShell

有没有可以快速将VBS代码转换成PowerShell代码的软件或工具?

另外,我想知道,下面的WithVBS代码中的语句,在PowerShell中如何表达?

With语句很棒,可以缩短代码,我可以在PowerShell中实现类似的功能吗?

发现PowerShell代码非常简洁,很好奇上面的代码,如何用最短的PowerShell代码实现同样的功能

'declare and instaciate wrdApp
Dim wrdApp: Set wrdApp = WScript.CreateObject("Word.Application")
'declare wrdDoc
Dim wrdDoc
Dim wdReplaceAll

'Open the document
Set wrdDoc = wrdApp.Documents.Open("c:\test.docx")

'set the value for the replace "constant"
wdReplaceAll = 2

wrdDoc.Select

With wrdApp.Selection.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = "WordToReplace"
    .Replacement.Text = "ReplaceWith"
    .Forward = True
    .Wrap = 1
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
'the Replace argument is the 11'th argument 
    .Execute , , , , , , , , , , wdReplaceAll
End With

'save the document and close Word
wrdDoc.SaveAs2 "c:\test-ok.docx"
wrdApp.Quit

'clean up
Set wrdApp = Nothing
Set wrdDoc = Nothing

PowerShell 没有与 VBScript 的 With 语句等效的语句。而不是

With wrdApp.Selection.Find
    .ClearFormatting
    .Replacement.ClearFormatting
    ...
End With

你可能会这样做:

$find = $wrdApp.Selection.Find
$find.ClearFormatting()
$find.Replacement.ClearFormatting()
...

或者像这样:

$wrdApp.Selection.Find | ForEach-Object {
    $_.ClearFormatting()
    $_.Replacement.ClearFormatting()
    ...
}

此外,据我所知,PowerShell 编译器没有 VBScript 或 VBA。不过,我整理了一些关于如何 translate VBA code to PowerShell 的笔记。