我可以使用 PowerShell 编写类吗? [英] Can I write a class using PowerShell?

查看:43
本文介绍了我可以使用 PowerShell 编写类吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

PowerShell 构建在 .NET 框架之上,我可以使用 PowerShell 编写自己的自定义类吗?

With PowerShell being built on top of the .NET framework, can I write my own custom class using PowerShell?

我不是在谈论实例化 .NET 类……那部分很简单.我想使用 PowerShell 脚本编写自己的自定义类.是否可以?到目前为止,我的研究使我认为这是不可能的.

I'm not talking about instantiating .NET classes... that part is plain enough. I want to write my own custom classes using PowerShell scripts. Is it possible? So far my research leads me to say that this isn't possible.

我仍在学习 PowerShell,尽管进行了几次搜索,但到目前为止我还没有在该网站上找到答案.

推荐答案

查看 Add-Type cmdlet.它允许您在 PowerShell 中编写 C# 和其他代码.例如(来自上面的链接),在 PowerShell 窗口中,

Take a look at the Add-Type cmdlet. It lets you write C# and other code in PowerShell. For example (from the above link), in a PowerShell window,

$source = @"
public class BasicTest
{
    public static int Add(int a, int b)
    {
        return (a + b);
    }

    public int Multiply(int a, int b)
    {
        return (a * b);
    }
}
"@

Add-Type -TypeDefinition $source

[BasicTest]::Add(4, 3)

$basicTestObject = New-Object BasicTest
$basicTestObject.Multiply(5, 2)

这篇关于我可以使用 PowerShell 编写类吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆