-1

I am translating vba code to PowerShell

Does with and endwith exist in PowerShell?

What is the alternative?

Could you give me an example?

Itchydon
  • 2,572
  • 6
  • 19
  • 33
  • 3
    No, it does not, but if you show us an example of a `With..EndWith` statement that you'd like to translate, we can probably show you relevant alternatives – Mathias R. Jessen Jul 03 '20 at 14:01
  • i think you want the `using` keyword. this >>> about_Using - PowerShell | Microsoft Docs — https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_using?view=powershell-7 – Lee_Dailey Jul 03 '20 at 16:22
  • Does this answer your question? [Setting multiple properties at once - equivalent of VB's With statement to provide an implied object context](https://stackoverflow.com/questions/42378637/setting-multiple-properties-at-once-equivalent-of-vbs-with-statement-to-provi) – Lance U. Matthews Jul 04 '20 at 19:53

2 Answers2

1

The VBA With ... End With statement is just a shorthand syntax - see With...End With Statement (Visual Basic):

With objectExpression
    [ statements ]
End With

So, for example this VBA script:

With MyVar
    .PropertyX = 100
    .PropertyY = "myvalue"
    .MyMethod()
End With

is equivalent to this VBA script:

MyVar.Property = 100
MyVar.PropertyY = "myvalue"
Myvar.MyMethod()

which translates simply to this in PowerShell:

$myVar.PropertyX = 100
$myVar.PropertyY = "myvalue"
$myvar.MyMethod()

However, if the objectExpression is a longer expression you can just assign it to a temporary variable:

With MyVar.MyProperty.MyOtherProperty
    .PropertyX = 100
    .PropertyY = "myvalue"
    .MyMethod()
End With

becomes this instead in VBA:

MyTempVar = MyVar.MyProperty.MyOtherProperty
MyTempVar.PropertyX = 100
MyTempVar.PropertyY = "myvalue"
MyTempVar.MyMethod()

which translates to PowerShell as follows:

$myTempVar = $myVar.MyProperty.MyOtherProperty
$myTempVar.PropertyX = 100
$myTempVar.PropertyY = "myvalue"
$myTempVar.MyMethod()
mclayton
  • 8,025
  • 2
  • 21
  • 26
0

Best alternative in Powershell:

foreach ($_ in $MyVar) {
    $_.PropertyX = 100
    $_.PropertyY = "myvalue"
    $_.MyMethod()
}

At least I like it...