1

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 Answer 1

3

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"
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.