Import-Methods (modification of post by Joel Bennett view diff)
diff | embed code: <script type="text/javascript" src="http://PoshCode.org/embed/969"></script>download | new post
Add functions to the scope for each static method of a type. Originally from Oisin Grehan
GREAT example: Import-Methods Math -IncludeProperties
- # [CmdletBinding()]
- param(
- #[Parameter(Position=1,ValueFromPipeline=$true)]
- [type]$type
- ,
- #[Parameter()]
- #[Alias("Properties")]
- [switch]$IncludeProperties
- )
- BEGIN {
- function MakeFunction() {
- PROCESS {
- $func = "function:global:$($_.name)"
- if (test-path $func) { remove-item $func }
- $flags = 'Public,Static,InvokeMethod,DeclaredOnly'
- new-item $func -value "[$($type.fullname)].InvokeMember('$($_.name)',$flags, `$null, `$null, `$args[0])"
- }
- }
- function MakeVariable($type) {
- PROCESS {
- $var = "variable:global:$($_.name)"
- if (test-path $var) { Remove-Variable $var -ErrorAction SilentlyContinue }
- new-variable -Name $($_.name) -Value $(Invoke-Expression "[$($type.fullname)]::$($_.name)") `
- -Description "Imported from $($type.FullName)" -Force -Scope Global `
- -Option AllScope, Constant, ReadOnly
- }
- }
- }
- PROCESS {
- if($_) { $type = $_ }
- $type | gm -static -membertype "method" | MakeFunction
- ## Properties as variables:
- if($IncludeProperties) {
- $type | gm -static -membertype "property" | MakeVariable $type
- }
- }
Submit a correction or amendment below (click here to make a fresh posting)
After submitting an amendment, you'll be able to view the differences between the old and new posts easily.
PowerShell Code Repository