Haven't coded in PowerShell in a few years and have a need to create a custom class. Poked through the docs and a few blogs and custom classes seemed simple enough, but I get the following error whenever I try to load even a simple class from a script.
I've tried running a test script and dot sourcing the file with the class:
The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)
At C:\Temp\test.ps1:1 char:1
. ./classtest.ps1
~~~~~~~~~~~~~~~~~
CategoryInfo : OperationStopped: (:) [], FileLoadException
FullyQualifiedErrorId : System.IO.FileLoadException
Calling the file with the class directly throws the same error:
The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)
At line:1 char:1
.\classtest.ps1
~~~~~~~~~~~~~~~
CategoryInfo : OperationStopped: (:) [], FileLoadException
FullyQualifiedErrorId : System.IO.FileLoadException
I scrapped my entire class and just grabbed a super simple example online as follows(this is what's currently in classtest.ps1 in the above errors):
class student {
[string]$FirstName
[string]$LastName
}
If I paste that class into a running PowerShell window, it works just fine. If I put it in a file and try to run it I get the same errors above whether calling the file directly or attempting to dot source the file into another script.
There's got to be something stupidly simple that I am missing here, how does one use a class in a PowerShell script?
CodePudding user response:
Figured it out. Apparently custom class libraries are touchy in PowerShell. Had to save it off to just standard text file, then load that file with Invoke-Expression
to load it into my PowerShell script. After that I could use it exactly how I would expect it to work.
Invoke-Expression $([System.IO.File]::ReadAllText('C:\Temp\myclass.txt'))
$NewStudent = [student]::new()
$NewStudent.FirstName = "bob"
$NewStudent.LastName = "Johson"
$NewStudent
A bit annoying, but it works.
CodePudding user response:
I agree with what Vivere commented and that you need to add constructor(s) to the class like:
class student {
[string]$FirstName
[string]$LastName
# create an empty student object
student () {}
# overload to create a student object with just the firstname
student ([string]$FirstName) {
# simply return the current value of Count
$this.FirstName = $FirstName
}
# overload to create a student object with both first and lastname
student ([string]$FirstName, [string]$LastName) {
# simply return the current value of Count
$this.FirstName = $FirstName
$this.LastName = $LastName
}
}
Use it like:
$student1 = [student]::new()
$student2 = [student]::new('Name1')
$student3 = [student]::new('Someone', 'Else')