简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM