I am translating vba code to PowerShell
Does with
and endwith
exist in PowerShell?
What is the alternative?
Could you give me an example?
I am translating vba code to PowerShell
Does with
and endwith
exist in PowerShell?
What is the alternative?
Could you give me an example?
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()
Best alternative in Powershell:
foreach ($_ in $MyVar) {
$_.PropertyX = 100
$_.PropertyY = "myvalue"
$_.MyMethod()
}
At least I like it...