r/PowerShell • • Oct 06 '20

Script Sharing The Syntax Difference Between Python and PowerShell

https://techcommunity.microsoft.com/t5/itops-talk-blog/the-syntax-difference-between-python-and-powershell/ba-p/1747859?WT.mc_id=modinfra-9656-abartolo
114 Upvotes

66 comments sorted by

View all comments

Show parent comments

0

u/[deleted] Oct 06 '20

[deleted]

-1

u/endowdly_deux_over Oct 06 '20 edited Oct 06 '20

You can define a private scope. You can define getter and setters. Use modules if you need that fine grained control. 90% of the time, you don’t and hidden works just fine.

But if you want those things, define your “class” as a module and export only what you want to be “public”. New-Module to Import-Module -AsCustomClass and continue.

Class inheritance is a thing as a simple part of the normal class syntax. I don’t think partial classes are possible but I don’t see a ton of use in powershell when you can take a more functional tack instead.

Look I’m not disagreeing. I use f# in the back for a lot of tasks and use cmdlets or powershell wrappers if I need them. But powershell is more than an automation language and it does do a lot of systems and general programming tasks easily. It’s far more capable then you suggest. That’s my only point.

0

u/[deleted] Oct 06 '20

[deleted]

1

u/endowdly_deux_over Oct 06 '20 edited Oct 06 '20

Again. Import module as custom object

It’s a class. With private scope. Not a workaround.

You clearly don't believe me. Here, it's this simple:

$TestClass = {
    # 'Constructor'
    param (
        $x
        ,
        $y
    )

    # private
    [string] $a = $x
    [int] $b = $y

    function SetA ($x) {
        $script:a = $x
    }

    function GetA { 
        $script:a
    }

    Export-ModuleMember -Function *
}

# Can be wrapped in a function for easy creation.
$Test = New-Module Test $TestClass -AsCustomObject -ArgumentList 42, 42 

$Test.Get()
# 42

$Test.GetA().GetType()
# IsPublic IsSerial Name                                     BaseType
# -------- -------- ----                                     --------
# True     True     String                                   System.Object

$Test.SetA(30)
$Test.GetA()
# 30

$Test | Get-Member

<#    TypeName: System.Management.Automation.PSCustomObject

    Name        MemberType   Definition
     ----        ----------   ----------
     Equals      Method       bool Equals(System.Object obj)
     GetHashCode Method       int GetHashCode()
     GetType     Method       type GetType()
     ToString    Method       string ToString()
     GetA        ScriptMethod System.Object GetA();
     SetA        ScriptMethod System.Object SetA();   #>

You can gm -force and unless you do some serious reflection, a and b are totally inaccessible.

0

u/[deleted] Oct 07 '20

[deleted]

→ More replies (0)