我可以用PowerShell写一个类吗?

我还在学习PowerShell,到目前为止,我还没有在这个网站上find答案,尽pipe有一些search。 随着Powershellbuild立在.NET框架之上,我可以使用Powershell编写自己的自定义类吗?

我不是在讨论实例化.NET类…这个部分很简单。 我想使用PowerShell脚本编写自己的自定义类。 可能? 到目前为止,我的研究让我说这是不可能的。 但是我想确认一下大师的第一个…

看看Add-Type cmdlet。 它可以让你在PowerShell中编写C#和其他代码。 例如(从上面的链接),

C:\PS>$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); } } "@ C:\PS> Add-Type -TypeDefinition $source C:\PS> [BasicTest]::Add(4, 3) C:\PS> $basicTestObject = New-Object BasicTest C:\PS> $basicTestObject.Multiply(5, 2) 

我怀疑你正在寻找的解决scheme是Powershell模块 。 他们执行类通常在其他语言中执行的angular色。 他们给你一个非常简单但结构化的方式来重用你的代码。

以下是如何使用模块获取PS中类的function。 在命令行你可以这样做:

 New-Module -ScriptBlock {function add($a,$b){return $a + $b}; function multiply($a,$b){return $a * $b}; function supersecret($a,$b){return multiply $a $b}; export-modulemember -function add, supersecret} 

那么你将能够:

 PS C:\> add 2 4 6 PS C:\> multiply 2 4 The term 'multiply' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was inc luded, verify that the path is correct and try again. At line:1 char:9 + multiply <<<< 2 4 + CategoryInfo : ObjectNotFound: (multiply:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException PS C:\> supersecret 2 4 8 

正如你所看到的,乘法在模块中是私有的。 更传统的做法是将一个对象作为模块的一个实例。 这是通过-AsCustomObject参数完成的:

 $m = New-Module -ScriptBlock {function add($a,$b){return $a + $b}; function multiply($a,$b){return $a * $b}; function supersecret($a,$b){return multiply $a $b}; export-modulemember -function add, supersecret} -AsCustomObject 

那么你可以:

 PS C:\> $m.add(2,4) 6 PS C:\> $m.multiply(2,4) Method invocation failed because [System.Management.Automation.PSCustomObject] doesn't contain a method named 'multiply'. At line:1 char:12 + $m.multiply <<<< (2,4) + CategoryInfo : InvalidOperation: (multiply:String) [], RuntimeException + FullyQualifiedErrorId : MethodNotFound PS C:\> $m.supersecret(2,4) 8 

这全部展示了dynamic模块的使用,意味着没有任何东西存储到磁盘以供重用。 非常简单的function很好。 如果您希望实际上能够读取代码并在将来的会话或脚本中重复使用它,但是您希望将其存储在.psm1文件中,然后将该文件存储在与文件具有相同名称(减去扩展名)的文件夹中。 然后,您可以将模块导入您的会话中的命令行或另一个脚本。

作为一个例子,让我们说我拿了这个代码:

 function Add{ param( $a, $b ) return $a + $b } function Multiply{ param( $a, $b ) return $a + $b } function SuperSecret{ param( $a, $b ) return Multiply $a $b } Export-ModuleMember -Function Add, SuperSecret 

并将其保存到名为TestModule.psm1的文件夹中:C:\ Windows \ System32 \ WindowsPowerShell \ v1.0 \ Modules \ TestModule

Powershell安装文件夹中的Modules文件夹是一个魔术文件夹,存储在那里的任何模块对于Import-Module cmdlet都是可见的,而不必指定path。 现在,如果我们在命令行运行Get-Module -List ,我们看到:

 ModuleType Name ExportedCommands ---------- ---- ---------------- Script DotNet {} Manifest FileSystem {Get-FreeDiskSpace, New-Zip, Resolve-ShortcutFile, Mount-SpecialFolder...} Manifest IsePack {Push-CurrentFileLocation, Select-CurrentTextAsVariable, ConvertTo-Short... Manifest PowerShellPack {New-ByteAnimationUsingKeyFrames, New-TiffBitmapEncoder, New-Viewbox, Ne... Manifest PSCodeGen {New-Enum, New-ScriptCmdlet, New-PInvoke} Manifest PSImageTools {Add-CropFilter, Add-RotateFlipFilter, Add-OverlayFilter, Set-ImageFilte... Manifest PSRss {Read-Article, New-Feed, Remove-Article, Remove-Feed...} Manifest PSSystemTools {Test-32Bit, Get-USB, Get-OSVersion, Get-MultiTouchMaximum...} Manifest PSUserTools {Start-ProcessAsAdministrator, Get-CurrentUser, Test-IsAdministrator, Ge... Manifest TaskScheduler {Remove-Task, Get-ScheduledTask, Stop-Task, Add-TaskTrigger...} Manifest WPK {Get-DependencyProperty, New-ModelVisual3D, New-DiscreteVector3DKeyFrame... Manifest AppLocker {} Manifest BitsTransfer {} Manifest PSDiagnostics {} Script **TestModule** {} Manifest TroubleshootingPack {} Manifest Citrix.XenApp.Commands... {} 

我们可以看到我们的模块已准备好导入。 我们可以将它导入到会话中,并使用它在原始使用:

 Import-Module TestModule 

或者我们可以再次实例化一个对象:

 $m = Import-Module TestModule -AsCustomObject 

您可以使用PowerShell 5.0中引入的class关键字

这是Trevor Sullivan的一个例子 。 ( 在这里存档)

 ################################################## ####### WMF 5.0 November 2014 Preview ########### ################################################## class Beer { # Property: Holds the current size of the beer. [Uint32] $Size; # Property: Holds the name of the beer's owner. [String] $Name; # Constructor: Creates a new Beer object, with the specified # size and name / owner. Beer([UInt32] $NewSize, [String] $NewName) { # Set the Beer size $this.Size = $NewSize; # Set the Beer name $this.Name = $NewName; } # Method: Drink the specified amount of beer. # Parameter: $Amount = The amount of beer to drink, as an # unsigned 32-bit integer. [void] Drink([UInt32] $Amount) { try { $this.Size = $this.Size - $Amount; } catch { Write-Warning -Message 'You tried to drink more beer than was available!'; } } # Method: BreakGlass resets the beer size to 0. [void] BreakGlass() { Write-Warning -Message 'The beer glass has been broken. Resetting size to 0.'; $this.Size = 0; } } 

这适用于Windows 10 Pro。

试驾这样的:

 # Create a new 33 centilitre beer, named 'Chimay' $chimay = [Beer]::new(33, 'Chimay'); $chimay.Drink(10) $chimay.Drink(10) # Need more beer! $chimay.Drink(200) $chimay.BreakGlass()