首页 > 解决方案 > VBS代码中的With语句,在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

标签: powershellvbscript

解决方案


PowerShell 没有 VBScriptWith语句的等效项。代替

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。不过,我整理了一些关于如何将 VBA 代码转换为 PowerShell的注释。


推荐阅读