Gordon
Gordon

Reputation: 6863

Using Module statement with error trapping

I have a script that I would like to migrate to PS5 and Classes for a number of reasons. It's a big script, so it would need to have a few Modules for the various classes. But, I have customers who are still using Windows 7 and PS2. My initial thought was to provide a way to automate the update of PowerShell, but so far as I can tell the only way to use Classes in Modules involves the Using Module statement, which has to be the very first statements in the script. And also as far as I can tell, anyone trying to run said script on Windows 7/PS2 is going to get a nasty error and I have no mechanism for catching that error and providing a log or other meaningful way of communicating what is going on. Is this a correct assessment, and perhaps Classes in PS 5 are just not yet ready for this kind of situation? I had hoped to move to much better logging with the help of Classes, but from the looks of it either things work, or my script shits the bed and looks really unprofessional. :(

Upvotes: 1

Views: 71

Answers (2)

Josh Desmond
Josh Desmond

Reputation: 690

If using two versions of the script is the direction you head, but you still want to avoid code duplication, perhaps it would be possible to refactor your script as such:

Have three files, script_main.ps1, script_using_imports.ps1, and script_legacy.ps1.

In script_main.ps1, do something like:

$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
if (getPowershellVersion() > $VersionNeeded) { #Pseudocode function names
    $scriptFile = "script_using_imports.ps1"
} else {
    $scriptFile = "script_legacy.ps1"
}

get-content -path "$scriptPath\$scriptFile" -raw | invoke-expression

# The rest of main goes on assuming imports worked.

Then in script_using_imports.ps1 and script_legacy.ps1, you handle the module/class imports as you want.

Not sure if that's helpful for your use case, but it's an idea!


I had to reference this for figuring out how to do the path name stuff.

Upvotes: 2

Jeff Zeitlin
Jeff Zeitlin

Reputation: 10799

You cannot use classes or the USING statement in PowerShell versions earlier than 5, period - the statements simply do not exist. You will need to

(1) maintain two versions of your script, one for PowerShell 5+ and one for PowerShell 4-,

(2) eschew the use of any cmdlets or syntax that are not in PowerShell 2, or

(3) mandate that your customers upgrade WMF and .NET to versions that will support PowerShell 5 or later.

Upvotes: 0

Related Questions