Powershell add-type update my first script

Filip 831 Reputation points
2021-06-26T15:47:38.157+00:00

Hello everybody.

I tried this:

$code = @"  
using System;  
namespace HelloWorld  
{  
 public class Program  
 {  
 public static void Main(){  
 Console.WriteLine("Hello world!");  
 }  
 }  
}  
"@  
   
Add-Type -TypeDefinition $code -Language CSharp  
iex "[HelloWorld.Program]::Main()"  

It work.
But when I change the "$code" variable script and "add-type" it secend time it show me an error.

109499-a.png

Why i can't update secend time my script?
How can i do it?

Thanks for help.

Windows for business Windows Server User experience PowerShell
0 comments No comments
{count} votes

Accepted answer
  1. MotoX80 36,291 Reputation points
    2021-06-26T17:16:56.49+00:00

    Using the last example to generate a random class name looks to be the simplest solution.

    https://stackoverflow.com/questions/25730978/powershell-add-type-cannot-add-type-already-exist

    1 person found this answer helpful.
    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. Anonymous
    2021-06-28T08:40:27.32+00:00

    Hi,

    You have to use another type name because it must be unique within a session and can neither be updated nor removed.

    Best Regards,
    Ian Xue

    ============================================

    If the Answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.