When I import my module I can't access the exposed members.
Placed my module in C:\Program Files\WindowsPowerShell\Modules.
When I import my module in powershell by:
Import-Module StuiterModule -Verbose
and then enter Invoke-Reboot it gives the following error:
Invoke-Reboot : The term 'Invoke-Reboot' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or operable program. CHeck the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:1
+ Invoke-Reboot
+ ~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Invoke-Reboot:String [], CommandNotFoundExeption
+ FullyQualifiedErrorId : CommandNotFoundException
Does anyone have an idea what I'm doing wrong?
Update
When I put -Force behind the Import Module everything works. Why is that and how can I fix this?
Code:
StuiterModule.psm1
$Public = #( Get-ChildItem -Path "$PSScriptRoot\Public\*.ps1" )
$Private = #( Get-ChildItem -Path "$PSScriptRoot\Private\*.ps1" )
#($Public + $Private) | ForEach-Object {
Try {
. $_.FullName
} Catch {
Write-Error -Message "Failed to import function $($_.FullName): $_"
}
}
Export-ModuleMember -Function $Public.BaseName
StuiterModule.psd1
#
# Module manifest for module 'StuiterModule'
#
# Generated by: StuiterSlurf
#
# Generated on: 29-5-2018
#
#{
# Script module or binary module file associated with this manifest.
RootModule = 'StuiterModule.psm1'
# Version number of this module.
ModuleVersion = '1.0.0'
# ID used to uniquely identify this module
GUID = '0254592e-b712-4d70-844c-6e38cec20ee5'
# Author of this module
Author = 'StuiterSlurf'
# Copyright statement for this module
Copyright = '(c) 2018 StuiterSlurf. All rights reserved.'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '5.0'
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = 'Invoke-Reboot', 'Start-Program', 'Update-Program'
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = #()
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = #()
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = #{
PSData = #{}
}
}
Public/Invoke-Reboot.ps1
# Reboot system
Function Invoke-Reboot {
[cmdletbinding()]
Param()
Write-Verbose "Starting reboot"
Restart-Computer
}
Related
I'm creating a PowerShell module that I would like to use enums across several functions (that will be exported, if that matters) and classes in the module. The only way I can see to do this is to put all of the code in a single file. That's not an easy maintenance story, however. I want a module file structure similar to the following:
As you can see in the code, Class1 has the Enum1 property flagged as "Unable to find type [Enum1]."
Deploy-MyResource:
function Deploy-MyResource {
[CmdletBinding()]
Param(
[Parameter(Mandatory=$true)]
[Enum1] $EnumParam,
[Parameter(Mandatory=$true)]
[Class1] $ClassParam
)
$class2 = [Class2]::new()
if($class2.Prop1 -eq $ClassParam.Prop1) {
Write-Output "Matches"
}
else {
Write-Output "No match."
}
}
Class1:
Class Class1 {
[string] $Prop1
[int] $Prop2
[Enum1] $EnumProp
DoSomething() {
Write-Output "Did something using $($this.Prop1), $($this.Prop2), & $($this.EnumProp)"
}
}
Enum1:
enum Enum1 {
ValueOne
ValueTwo
}
Here are my PSD1 and PSM1:
PSD1:
#{
# Script module or binary module file associated with this manifest.
RootModule = 'Module1.psm1'
# Version number of this module.
# NOTE keep version in sync with Module1.nuspec
ModuleVersion = '2.7.2'
# ID used to uniquely identify this module
GUID = '24EC97AC-42B1-4719-9EF2-F49C14F8D148'
# Author of this module
Author = 'Me'
# Company or vendor of this module
CompanyName = 'Me'
# Description of the functionality provided by this module
Description = 'Example module for Stack post'
# Minimum version of the Windows PowerShell engine required by this module
PowerShellVersion = '5.1'
# Modules that must be imported into the global environment prior to importing this module
RequiredModules = #()
# Assemblies that must be loaded prior to importing this module
RequiredAssemblies = #('System.Web')
# Functions to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no functions to export.
FunctionsToExport = #('Deploy-MyResource')
# Cmdlets to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no cmdlets to export.
CmdletsToExport = #()
# Variables to export from this module
VariablesToExport = #()
# Aliases to export from this module, for best performance, do not use wildcards and do not delete the entry, use an empty array if there are no aliases to export.
AliasesToExport = #()
# Private data to pass to the module specified in RootModule/ModuleToProcess. This may also contain a PSData hashtable with additional module metadata used by PowerShell.
PrivateData = #{
PSData = #{
#region Unused PSData
# Tags applied to this module. These help with module discovery in online galleries.
# Tags = #()
# A URL to the license for this module.
# LicenseUri = ''
# A URL to the main website for this project.
# ProjectUri = ''
# A URL to an icon representing this module.
# IconUri = ''
# ReleaseNotes of this module
# ReleaseNotes = ''
#endregion Unused PSData
} # End of PSData hashtable
} # End of PrivateData hashtable
#region Unused Props
# Copyright statement for this module
# Copyright = '(c) 2019 appliedis.com. All rights reserved.'
# Supported PSEditions
# CompatiblePSEditions = #()
# Name of the Windows PowerShell host required by this module
# PowerShellHostName = ''
# Minimum version of the Windows PowerShell host required by this module
# PowerShellHostVersion = ''
# Minimum version of Microsoft .NET Framework required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# DotNetFrameworkVersion = ''
# Minimum version of the common language runtime (CLR) required by this module. This prerequisite is valid for the PowerShell Desktop edition only.
# CLRVersion = ''
# Processor architecture (None, X86, Amd64) required by this module
# ProcessorArchitecture = ''
# Script files (.ps1) that are run in the caller's environment prior to importing this module.
# ScriptsToProcess = #()
# Type files (.ps1xml) to be loaded when importing this module
# TypesToProcess = #()
# Format files (.ps1xml) to be loaded when importing this module
# FormatsToProcess = 'Module1.Format.ps1xml'
# Modules to import as nested modules of the module specified in RootModule/ModuleToProcess
# NestedModules = #()
# DSC resources to export from this module
# DscResourcesToExport = #()
# List of all modules packaged with this module
# ModuleList = #()
# List of all files packaged with this module
# FileList = #()
# HelpInfo URI of this module
# HelpInfoURI = ''
# Default prefix for commands exported from this module. Override the default prefix using Import-Module -Prefix.
# DefaultCommandPrefix = ''
#endregion Unused Props
}
PSM1:
# Get public and private function definition files.
$Private = #( Get-ChildItem -Path $PSScriptRoot\Function\private\*.ps1 -Recurse -ErrorAction SilentlyContinue )
$Public = #( Get-ChildItem -Path $PSScriptRoot\Functions\public\*.ps1 -Recurse -ErrorAction SilentlyContinue )
# Dot source the files
Foreach($import in #($Private + $Public))
{
Try
{
Set-StrictMode -Version Latest
. $import.fullname
}
Catch
{
Write-Error -Message "Failed to import function $($import.fullname): $_"
}
}
# Export the public functions
Foreach($import in $Public)
{
Try
{
Export-ModuleMember -Function $import.BaseName
}
Catch
{
Write-Error -Message "Failed to import function $($import.fullname): $_"
}
}
This is what I get when I try to use the module:
Use-Module (outside of the Module1 folder):
Using module .\Module1
$class1 = [Class1]::new()
Deploy-MyResource -EnumParam ValueOne -ClassParam $class1
What am I missing? All of the examples about modules and classes I'm finding are all in a single file.
I've created a repo on GitHub with the code here: https://github.com/SPSamL/PowerShell-Module-With-Classes
There's no good solution to this in pure PowerShell right now. If you need class definitions shared across multiple scripts and other modules, then you'll probably want to build a C# class library and include the DLL with one of your PowerShell module projects.
Whichever classes you would like to use across multiple functions or modules, put inside a single module file.
Afterward, you can utilize the using command: https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_using?view=powershell-7 to import the namespace.
To load classes from a PowerShell module:
using module <module-name>
I use pre-v5 syntax (works with Core), which creates the enum into a global scope.
Add-Type -TypeDefinition #"
public enum Enum1 {
ValueOne,
ValueTwo
}
"#
I have a powershell script gather_objects_from_csv.ps1 which is being scheduled through cmd. I'm using this command:
powershell.exe -noexit "& 'e:\admin\gather_objects_from_csv.ps1'"
to call the powershell script, but it's throwing error for the line in the script
# create an empty hash which will hold a number of smaller hashes, of member details supplied in the csv, then piped to nw_sync_employees_8.ps1
$employees_list = #{}
# import the config.xml file containing the relevant user data, username/password etc...
$config = Import-CliXML nw-config.xml
# import some detail from the "normal" Newsweaver config file
$API_user = $config["API_USER"]
$API_user_password = $config["API_PASSWORD"]
$USE_PROXY = $config["USE_PROXY"]
$verboseMode = $config["VERBOSE_MODE"]
$account_code = $config["ACCOUNT_CODE"]
$source_file = $config["CSV_PATH"]
# check to see if the source file actually exists first
if (-Not (Test-Path $source_file)) {
# if the source file can't be found, there isn't much value in continuing
Write-Host -foregroundcolor red "Could not find specified source file. Check the path, permissions or location of source file specified: " $source_file
Exit
}
# import the source file with a specified delimiter (it is a comma as it is a CSV file which is being imported)
# pipe "|" the csv to a forEach - Object loop to iterate throught the file row by row
$HashTableData = Import-CSV $source_file -Delimiter ',' |`
# ForEach - Object - iterates over each row of the csv
ForEach-Object {
# Empty hash $memberDetails, this will be populated with the information from the csv
$memberDetails = #{}
$EmployeeID = "$($_.EmployeeID)".Trim()
$FirstName = "$($_.LegalFirstName)".Trim()
$LastName = "$($_.LegalLastName)".Trim()
$LegalNameinGeneralDisplayFormat = "$($_.LegalNameinGeneralDisplayFormat)".Trim()
$LegalNameinLocalScript = "$($_.LegalNameinLocalScript)".Trim()
#set the email address as the key for the hashtable $employees_list
#and the value of this "hash of hashes" is the hash table created above ie. memberDetails (csv information)
$employees_list.Set_Item("$($Email)", $memberDetails)
}
# pass/ pipe the hash called $employees_list to the nw_sync script with the relevant parameters
$employees_list | ./nw_sync_employees.ps1 -account_code $account_code -password $API_user_password -user $API_user -permission 'All'
exit
Error line:
nw_sync_employees.ps1: The term ./nw_sync_employees.ps1' is not
recognized as the name of a cmdlet, function, script file, or operable
program. Check the spelling of the name, of if a path was included,
verify that the path is correct and try again.
+ $employee_list | ./nw_sync_employees.ps1 -account_code $account_cod...
+ ~~~~~~~~~~~~~~~~~~~
+CategoryInfo : ObjectNotFound:
(.\nw_sync_employees.ps1:String)[], CommandNotFoundException
+FullyQualifiedErrorId: CommandNotFoundException
powershell script is calling another ps script located in the same folder. When ran through powershell terminal, the same script is not throwing any error. But when I'm trying to call it through commandline it is throwing error.
This line in the .bat works for me :
Powershell.exe "D:\myfolder\myfile.ps1"
with Administrator rights.
I've been working on a powershell script. Because I want to modularize/organize my code a little bit I decided to try making some modules to split up my script.
I am running powershell 5.1.14393.1066
Now I have one main script which imports the modules that it needs, but it can't seem to find my function Is-Template-Name-Set:
Is-Template-Name-Set : The term 'Is-Template-Name-Set' 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 included, verify that the path is correct and try again.
At C:\Users\niels\test1\TemplateScript.ps1:6 char:5
+ If (Is-Template-Name-Set) {
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (Is-Template-Name-Set:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Is-Template-Name-Set is defined in UtilityTemplateModule. Module file (UtilityTemplateModule.psm1):
Function Get-ScriptDirectory() {
return Split-Path $script:MyInvocation.MyCommand.Path
}
Function Is-Template-Name-Set($templateName) {
$templateName -And $templateName -is [String] -And -Not $templateName -eq ""
}
Export-ModuleMember -Function 'Get-*'
Export-ModuleMember -Function 'Is-*'
UtilityTemplateModule description (UtilityTemplateModule.psd1 file):
#{
ModuleVersion = '1.0'
GUID = '082fc8f7-4c7f-4d9f-84a8-b36c3610cdfe'
Author = 'Niels Bokmans'
CompanyName = 'Bluenotion'
Copyright = 'Copyright (c) 2017'
Description = 'General utilities used by the other template modules.'
# Functions to export from this module
FunctionsToExport = '*'
# Cmdlets to export from this module
CmdletsToExport = '*'
# Variables to export from this module
VariablesToExport = '*'
# Aliases to export from this module
AliasesToExport = '*'
}
My main script:
param([String]$templateName="")
Import-Module BuildTemplateModule
Import-Module CdnTemplateModule
Import-Module UtilityTemplateModule
If (Is-TemplateNameSet -templateName $templateName) {
echo "Template name is set!"
$templateId = GetTemplateId -templateName $templateName
if (-Not $templateId -eq -1) {
Restore-Packages
Run-Build-Tasks
Minify-Require-Js
Clean-Downloaded-Dependencies
Copy-Offline-Page
#Deploy $response.templateId
}
} else {
echo "Template name not set!"
exit
}
I'm very new to any powershell work and I'm not sure why the function isn't recognized. I think I'm doing it right, exporting functions in the module itself and also just exporting everything in the description file (?, the .psd1 file).
Any suggestions would be greatly appreciated.
Based on your comment about the system32 powershell modules directory I think you may be putting your modules in the wrong directory.
Per: https://msdn.microsoft.com/en-us/library/dd878350(v=vs.85).aspx
$PSHome\Modules (%Windir%\System32\WindowsPowerShell\v1.0\Modules)
This location is reserved for modules that ship with Windows. Do not install modules to this location.
I suggest moving your modules to:
$Home\Documents\WindowsPowerShell\Modules (%UserProfile%\Documents\WindowsPowerShell\Modules)
Or
$Env:ProgramFiles\WindowsPowerShell\Modules (%ProgramFiles%\WindowsPowerShell\Modules)
Creating any directories in either of those paths that are missing (e.g under Documents the \WindowsPowerShell\Modules folders don't usually exist by default).
Alternatively you could put modules in a custom path and add that path to the PSModulePath environment variable.
Background
I am creating a script, using PowerCLI, to perform mass OVF exports using VMware's ovftool. The script works by performing the following functions:
Through PowerCLI arguments, take in the vCenter address, naming scheme of the VMs to export, and where the OVFs should be exported
Connect to the vCenter instance
Put all VMs that follow the specified naming scheme into a list
Loop through the list and export each VM to an ovf using the ovftool and the built path to the VM
The Script: VMs-to-OVF.ps1
# Take in vCenter address, naming scheme of VMs to be exported, and where the OVFs should be exported
param (
[string]$vcenter = $(throw "
vCenter address required.`n
Example:`n
.\VMs-to-OVF.ps1 -vcenter <192.168.1.200>`n
.\VMs-to-OVF.ps1 -vcenter <vcenter.test.com>"),
[string]$vmNamingScheme = $(throw "
VM naming scheme required.`n
Example:`n
.\VMs-to-OVF.ps1 -vcenter <vcenterIP/DNS> -vmPath </DATACENTER/vm/`n
test/> -vmNamingScheme <test-vm-1>`n
.\VMs-to-OVF.ps1 -vcenter <vcenterIP/DNS> -vmPath </DATACENTER/vm/`n
test/> -vmNamingScheme <test-vm-*>`n"),
[string]$exportLocation = $(throw "
Export location required.`n
Example:`n
.\VMs-to-OVF.ps1 -vcenter <vcenterIP/DNS> -vmPath </DATACENTER/vm/`n
test/> -vmNamingScheme <test-vm-1> -exportLocation 192.168.1.100:\`n
.\VMs-to-OVF.ps1 -vcenter <vcenterIP/DNS> -vmPath </DATACENTER/vm/`n
test/> -vmNamingScheme <test-vm-*> -exportLocation X:\`n")
)
# Connect to vCenter
Connect-VIServer -Server $vcenter
# $VMs is an array of VM names that will be exported
# $vmNamingScheme gives the VM naming pattern we are looking for
$VMs = $(get-vm -name $vmNamingScheme | select name | format-list | out-string)
$VMs = $VMs.replace("Name : ","")
$VMs = $VMs.replace(" ","")
$VMs = $VMs.split("`n")
$VMs = $VMs|?{$_ -ne $VMs[1]}
# This loop iterates through the $VMs array and performs an OVF export, to the location
# specified in $exportLocation, for each VM name in the array
# $vmPath is comprised of the path to the VM and $VM holds the actual VM name
foreach ($VM in $VMs){
if ($VMs -ne $null){
# ***THIS SCRIPT ASSUMES THE get-vmfolderpath SCRIPT IS IN THE SAME DIRECTORY AS ITSELF***
# get the folder path of the VM using the get-vmfolderpath script (this will align with
# the path in vSphere Folders and Templates view)
$vmPath = "get-vm -name $VM | .\get-vmfolderpath.ps1"
&$vmPath
# ***THIS SCRIPT ASSUMES THE DEFAULT INSTALL PATH FOR THE ovftool PROGRAM
# run the ovftool command with the proper arguments
&'C:\Program Files\VMware\VMware OVF Tool\ovftool.exe' vi://$vcenter$vmPath$VM $exportLocation
}
}
Accompanying Script: get-vmfolderpath
param(
[Parameter(Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
[string]$folderid,
[switch]$moref
)
$folderparent=get-view $folderid
if ($folderparent.name -ne 'vm'){
if($moref){
$path=$folderparent.moref.toString()+'\'+$path
}
else{
$path=$folderparent.name+'\'+$path
}
if ($folderparent.parent){
if($moref){
get-vmfolderpath $folderparent.parent.tostring() -moref
}
else{
get-vmfolderpath($folderparent.parent.tostring())
}
}
}
else {
if ($moref){
return (get-view $folderparent.parent).moref.tostring()+"\"+$folderparent.moref.tostring()+"\"+$path
}
else {
return (get-view $folderparent.parent).name.toString()+'\'+$folderparent.name.toString()+'\'+$path
}
}
Errors
The ovftool command built in each iteration of the for loop will work if you copy and paste the text into the PowerCLI console, but not when run directly from the script. The following errors are produced when the custom ovftool command is run from within the script:
The term 'get-vm -name VM-NAME | .\get-vmfolderpath.ps1' 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 included, verify
that the path is correct and try again.At
C:\Users\username\Desktop\VMs-to-OVF.ps1:85 char:4
+ &$vmPath
+ ~~~~~~~
+ CategoryInfo : ObjectNotFound: (get-vm -name CA...mfolderpath.p
s1:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Things I Have Checked:
The output of "get-vm -name vm_name | .\get-vmfolderpath.ps1" run directly in the PowerCLI console returns the proper VM path
All variables output the expected values
If the exact ovftool command generated in the script is run in the PowerCLI console then it will properly export the VM
Just closing the loop on this. I found a solution to my issue. My guess is that something is lost when you manipulate the list of VMs returned by the Get-VM cmdlet. In the VMs-to-OVFs script, if all of the "$VM =" lines are replaced by the single line below, then that information is retained.
$VMs = get-vm -name $vmNamingScheme
In the for loop use the ".Name" attribute to pass each individual VM object to the get-vmfolderpath script.
$vmPath = get-vm -name $VM.Name | .\get-vmfolderpath.ps1
With PowerShell being built on top of the .NET framework, can I write my own custom class using 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.
I'm still learning PowerShell, and so far I haven't found an answer on this website, despite a few searches.
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)
I suspect that the solution that you are looking for is PowerShell Modules. They perform the roles that classes typically perform in other languages. They give you a very simple, yet structured, way to reuse your code.
Here is how to get the functionality of classes in PowerShell using modules. At the command line you could do this:
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}
Then you would be able to:
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 included, 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
As you can see multiply is private within the module. More traditionally you would instantiate an object that is an instance of the module. That is done via the -AsCustomObject parameter:
$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
Then you could:
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
This all demonstrates the use of dynamic modules meaning nothing is stored to disk for reuse. It is fine for very simple functionality. If you want to actually be able to read the code and reuse it in future sessions or scripts, however, you would want to store it in a .psm1 file and then store that file in a folder with the same name (minus the extension) as the file. Then you can import the module into your session at the command line or into another script.
As an example of this, let's say I took this code:
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
And saved it to a file called TestModule.psm1 in the folder: C:\Windows\System32\WindowsPowerShell\v1.0\Modules\TestModule
The Modules folder in the PowerShell install folder is a magic folder and any modules stored there are visible to the Import-Module cmdlet without having to specify a path. Now if we run Get-Module -List at the command line we see:
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... {}
We can see that our module is ready to import. We can import it into the session and use it in the raw using:
Import-Module TestModule
Or once again we can instantiate an object:
$m = Import-Module TestModule -AsCustomObject
You can use the class keyword that was introduced in PowerShell 5.0
Here is an example by Trevor Sullivan. (Archived here.)
##################################################
####### 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;
}
}
This works on Windows 10 Pro.
Test drive it like this:
# 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()