1

I have a PowerShell script that uses Add-Type and for -TypeDefinition I would like to, instead of defining $Source = @""@, define $Source = script.cs.

Is this possible and if so how does one go about doing it?

$Source = Get-Content -Path $PSScriptRoot\script.cs -Raw

Add-Type -ReferencedAssemblies 'System', 'System.Runtime.InteropServices' -TypeDefinition $Source -Language CSharp

Then I use whatever in C# script later on in the PS script. I do believe these are the only two important area right now

1
  • 2
    $Source = Get-Content $PSScriptRoot\script.cs -Raw -- assuming "script.cs" is located in the same folder as the PoSh script. Commented Nov 14, 2021 at 17:09

1 Answer 1

1

Get-Content can grab the contents a file and use it as a string. Here is a link to the documentation. For instance:

$Source = Get-Content -Path .\path\to\script.cs -Raw
Sign up to request clarification or add additional context in comments.

7 Comments

Thanks to you and @zett42. I do need to ask, though, does this make the Add-Type redundant? I'm getting an error now saying Add-Type : Cannot add type. The type name '...' already exists.
Can you expand a little on how you're using Add-Type?
It doesn't make Add-Type redundant. Get-Content is just storing the contents of the file as a string. Double check that the type you are defining in the script doesn't already exist.
It works perfectly if I add it normally through $Source = @"..."@, but then raises this error when I use Get-Content instead. I can't figure out why
Have you tried using Add-Type -Path <Path\to\script.cs>?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.