October 2017
Intermediate to advanced
440 pages
11h 47m
English
Objects with specific properties can be simulated by creating a PS custom object (or PSObject):
[PSCustomObject]@{
Property = "Value"
}
New methods can be added to an object using Add-Member:
[PSCustomObject]@{} | Add-Member MethodName -MemberType ScriptMethod -Value { }
This approach can be extended to include objects instantiated by New-Object. The following function creates and uses instances of two different .NET types:
function Write-File {
$fileStream = New-Object System.IO.FileStream("C:\Temp\test.txt", 'OpenOrCreate')
$streamWriter = New-Object System.IO.StreamWriter($fileStream)
$streamWriter.WriteLine("Hello world")
$streamWriter.Close()
}
The following mocks replace the first with null, and the second with ...
Read now
Unlock full access