13

I would like to utilize my own custom namespaces in a PowerShell .ps1 script or a .psm1 module. Is this possible? If so, what is the syntax to do this?

I found a related link here: Breaking the Powershell namespace limit of global,script

It seems like I will need to make my own custom object, or possibly use a custom associative array for this?

I would like to be able to call my function like this:

[MyCoolNamespace]::Get-CrazyYall

3 Answers 3

19

A module name is similar to a namespace. For example:

Microsoft.PowerShell.Core\Get-Command

is the same as

Get-Command

Normally you don't use module qualified names when invoking commands (cmdlets, functions, or aliases), but it comes in handy if you do have a conflict or want to be 100% certain you are invoking the function you meant to.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks! I think this is actually more along the line of what I want to do. Basically I wanted a namespace so I didn't have to write out long function names (i.e. pseudo namespace).
I accepted this because it was "pure" PowerShell and provides what I wanted, albeit with a different name...
This is far from complete: for example I cannot reach variables exported from the module. Functions and aliases are visible indeed
10

Create a custom type with a static method:

PS C:\> Add-Type @'
>> using System;
>> public class MyCoolNamespace {
>>   public static string Foo() {
>>     return "Foo";
>>   }
>> }
>> '@
>>
PS C:\> [MyCoolNamespace]::Foo()
Foo

3 Comments

thanks! I guess it's only possible by reverting back to C# syntax? I was hoping to write my functions in PowerShell, but put them in a namespace. Is this possible? Is it easy? For instance, what if I already have the function Get-Foo written in PowerShell?
I'm not aware of a way to do this in plain PowerShell.
To me this doesn't answer the question because it's just leveraging C#.
2

You could try using PSTypeNames.

$Var = [PSCustomObject]@{
    foo = [string]::Empty
    bar = $false
}

$Var.PSTypeNames.Insert(0, 'My.Namespace')

$var | get-member

1 Comment

This doesn't seem like a good practice.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.