'Is it possible to use with and endwith instructions?

I am translating vba code to PowerShell

Does with and endwith exist in PowerShell?

What is the alternative?

Could you give me an example?



Solution 1:[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()

Solution 2:[2]

Best alternative in Powershell:

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

At least I like it...

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mclayton
Solution 2 Dieter Hug