1
votes

I want to create a server smo object in my function, then use it do something useful with the passed in scriptblock. After that, the server veriable will be removed. I want to design my function something similar to a template design pattern implementation. My code is listed below, I'm not sure whether how to use the $server variable in the scriptblock. Any one can help? Thanks.

function test{
   [CmdletBinding()]
   param (
        [Parameter(Mandatory = $true, Position = 0)] 
        [object] 
        $instance,

        [Parameter(Mandatory = $true, Position = 1)] 
        [scriptblock] 
        $script
        )

    [Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO') | out-null
    $server = new-object ('Microsoft.SqlServer.Management.Smo.Server') $instance

    # do something with $script

    Remove-Variable -Name $server
}
1

1 Answers

3
votes

The scriptblock needs to be written such that it is expecting a server variable e.g.:

test $anInstance {param($server) $server.DoSomething}

Then in your test function execute the scriptblock like so:

& $scripblock $server

And if the scriptblock needs multiple parameters:

test $anInstance {param($server, $name) $server.DoSomething}

Remember to invoke using space separated args:

& $scripblock $server "A name"