templates - 如何在Powershell中使用模板设计模式?

标签 templates powershell

我想在函数中创建一个服务器smo对象,然后使用它对传入的脚本块进行一些有用的操作。此后,将删除服务器验证。我想设计类似于模板设计模式实现的功能。我的代码在下面列出,我不确定是否在脚本块中使用$ server变量。有人可以帮忙吗?谢谢。

功能测试{
[CmdletBinding()]
参数(
[Parameter(必填= $ true,位置= 0)]
[目的]
$ instance,

[Parameter(必填= $ true,位置= 1)]
[脚本块]
$脚本
)

[Reflection.Assembly]::LoadWithPartialName('Microsoft.SqlServer.SMO')|零
$ server =新对象('Microsoft.SqlServer.Management.Smo.Server')$ instance

#用$ script做某事

Remove-Variable -Name $ server
}

最佳答案

需要编写脚本块,以便期望服务器变量,例如:

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

然后在您的测试函数中执行脚本块,如下所示:
& $scripblock $server

并且如果脚本块需要多个参数:
test $anInstance {param($server, $name) $server.DoSomething}

请记住使用空格分隔的参数进行调用:
& $scripblock $server "A name"

关于templates - 如何在Powershell中使用模板设计模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9758319/

相关文章:

php - 创建用于呈现公共(public)页面的自定义模板

Windows 批处理脚本复制最近 x 分钟内修改的文件

c++ - 编译期间模板优化中的static_cast

java - 带有数组名称的 playframework 表单输入

powershell - 如何使用powershell遍历文件?

powershell - 如何使用powershell读取文件系统对象属性表的 'details'选项卡的值

powershell - 当前执行的powershell脚本的路径

powershell - 如何在此处字符串中进行变量替换

类中的 C++ 模板

C++模板参数默认函数实现