首页 > 解决方案 > 如何正确地将 C# 代码添加到 PowerShell 脚本?

问题描述

$w=@'
using System;
using System.Drawing;

public class img{
    public static String test(){
        Image image = Image.FromFile("C:\\img.png");
        String size = image.Width+"x"+image.Height;
        return size;
    }
}
'@

add-type -typed $w
[img]::test()

我想添加这个 c# 代码,但我得到了错误。如何正确添加c#代码?

标签: .netpowershell

解决方案


由于 C# 代码使用 System.Drawing,因此必须知道Add-Type它的来源。

Add-Type 有-ReferencedAssemblies参数可以做到这一点。像这样,

Add-Type -TypeDefinition $w -ReferencedAssemblies System.Drawing

推荐阅读