(有些)复杂的PowerShell语法是否有指南?Biztalk示例

Max*_*lle 2 syntax powershell biztalk

我可能不会问一个具体示例的通用问题,但我很难将一些基本命令从PowerShell控制台转换为可重用的函数和自定义cmdlet.有没有关于PowerShell语法的权威指南,有问题,提示和技巧?

例如,我正在尝试创建一个函数,以便自动管理BizTalk主机实例.以下函数不起作用(在运行时失败),而单独粘贴在PowerShell控制台中时,每个单独的行都按预期工作.

function AddNewHostInstance([string]$ServerName, [string]$HostName, [string]$Login, [string]$Password)
{
    [System.Management.ManagementObject]$objServerHost = `
        ([WmiClass]"root/MicrosoftBizTalkServer:MSBTS_ServerHost").CreateInstance()

    $objServerHost["ServerName"] = $ServerName
    $objServerHost["HostName"] = $HostName
    $objServerHost.Map()

    $name = "Microsoft BizTalk Server " + $HostName + " " + $ServerName

    [System.Management.ManagementObject]$objServerHost = `
        ([WmiClass]"root/MicrosoftBizTalkServer:MSBTS_HostInstance").CreateInstance()

    $objHostInstance["Name"] = $name
    $objHostInstance.Install($Login, $Password, $True)
}
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我在这个特殊情况下收到的错误是这样的:

PS C:\Users\username> createHostInstances $server, $host, $user, $pwd
Exception calling "Map" : "Invalid parameter "
At line:14 char:39
+     $objServerHost.Map <<<< ()
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : WMIMethodException
Exception calling "Install" : "Instance of the WMI class is not found.
No instance was found with the specified key.  This could be the result of the instance being deleted by another BizTalk Admin session."
At line:19 char:29
+     $objHostInstance.Install <<<< ($Login, $Password, $True)
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : WMIMethodException
PS C:\Users\username>
Run Code Online (Sandbox Code Playgroud)

[编辑]经过进一步调查,似乎该函数不喜欢通过变量为WMI对象赋予属性.如果我硬编码所有值(而不是依赖于提供的函数参数),那么它按预期工作!

基本上,这有效:

# Using hard-coded value
$objServerHost["HostName"] = "TestHost"
Run Code Online (Sandbox Code Playgroud)

鉴于此,不是:

# Using function supplied parameter
$objServerHost["HostName"] = $HostName
Run Code Online (Sandbox Code Playgroud)

不过,我不明白为什么......

Kei*_*ill 6

就指南而言,最好的书是Bruce Payette的Windows PowerShell in Action.2月份有第二版,但您可以尽早获得电子草稿.那里还有几本免费书籍. 由Tobias Weltner博士掌握PowerShell,我还有一本短短的60页电子书 - 有效的Windows PowerShell.最后一个内容涵盖了许多问题,并为您提供了PowerShell工作方式的心理模型.

WRT错误,我想知道使用PowerShell内置的WMI支持是否会更好运,例如:

$namespace = 'root/MicrosoftBizTalkServer' 
$host = Get-WmiObject -namespace $namespace -class MSBTS_HostInstance
Run Code Online (Sandbox Code Playgroud)

查看生成的WMI对象是否具有适当的数据和方法(Map&Install):

$host | fl *
$host | Get-Member
Run Code Online (Sandbox Code Playgroud)