Consider the following PowerShell snippet:
$csharpString = @" using System; public sealed class MyClass { public MyClass() { } public override string ToString() { return "This is my class. There are many others " + "like it, but this one is mine."; } } "@ Add-Type -TypeDefinition $csharpString; $myObject = New-Object MyClass Write-Host $myObject.ToString();
If I run it more than once in the same AppDomain (e.g. run the script twice in powershell.exe or powershell_ise.exe) I get the following error:
Add-Type : Cannot add type. The type name 'MyClass' already exists. At line:13 char:1 + Add-Type -TypeDefinition $csharpString; + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (MyClass:String) [Add-Type], Exception + FullyQualifiedErrorId : TYPE_ALREADY_EXISTS,Microsoft.PowerShell.Commands.AddTypeCommand
How do I wrap the call to Add-Type -TypeDefinition so that its only called once?
To conditionally add a property to an object, we can make use of the && operator. In the example above, in the first property definition on obj , the first expression ( trueCondition ) is true/truthy, so the second expression is returned, and then spread into the object.
To add a conditional class in Angular we can pass an object to ngClass where key is the class name and value is condition i.e., true or false as shown below. And in the above code, class name will be added only when the condition is true.
Create a new react application or open existing react app. Declare two different CSS style objects named as objectStyle and objectStyleValid with below attributes (in Code). Next we will declare a const variable named “isValid”. Based on its value (true/false) we will try to change the CSS style.
You can use an if statement, if it is within a immediately invoked function.
This technique works well for me:
if (-not ([System.Management.Automation.PSTypeName]'MyClass').Type) { Add-Type -TypeDefinition 'public class MyClass { }' }
Internally, the PSTypeName class calls the LanguagePrimitives.ConvertStringToType() method which handles the heavy lifting. It caches the lookup string when successful, so additional lookups are faster.
I have not confirmed whether or not any exceptions are thrown internally as mentioned by x0n and Justin D.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With