Fabricating objects

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	est.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 an object that supports the methods used by the script:

Mock New-Object { } -ParameterFilter { $TypeName -eq 'System.IO.FileStream' } 
Mock New-Object { 
    [PSCustomObject]@{} | 
        Add-Member WriteLine -MemberType ScriptMethod -Value { } -PassThru | 
        Add-Member Close -MemberType ScriptMethod -Value { } -PassThru 
} -ParameterFilter { $TypeName -eq 'System.IO.StreamWriter' } 
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.179.100