Search code examples
powershellpowershell-remoting

Can I hide internal helper methods in a Powershell ps1 script?


For example, one (bad) idea I had would be to import a module from a string defined in the file (I don't know if I can do this without first writing this string to the file system)

I'm writing a script that I want to be able to execute remotely, and following this answer I'm using the "Scripts Approach". However, I want to hide some of the functions somehow - I'd like a sort of module within a script.

Or is there a completely different approach to what I'm trying to do? All my scripts/modules are client side, and I want to run them in a remote PSSession. I don't particularly want to handle copying of scripts to the remote server or shared drive.

I am using the following to dot source my script into a remote PSSession:

invoke-command -Session $s -FilePath $p

and then invoking a scriptblock making use of the functions defined in the script file $p. This works, but I don't think this works with modules, and if I want to reuse code in other scripts, I either have to manually import each one into the remote session, or duplicate code in a single monolithic script. Neither is appealing, and neither seems to allow hiding of "private" methods.


Solution

  • You can use New-Module cmdlet:

    New-Module {
        function a {
            b
        }
        function b {
            'function b called'
        }
        Export-ModuleMember a
    }|Out-Null
    a #OK
    b #Error