Deploy SCO IP using Powershell

comObject.types.ps1xml

<Types>
    <Type>
        <Name>System.__ComObject</Name>
        <Members>
            <ScriptMethod>
                <Name>GetProperty</Name>
                <Script>
                    $type = $this.gettype();
                    $type.invokeMember($args[0],[System.Reflection.BindingFlags]::GetProperty,$null,$this,$null)
                </Script>
            </ScriptMethod>
            <ScriptMethod>
                <Name>SetProperty</Name>
                <Script>
                    $type = $this.gettype();
                    $type.invokeMember($args[0],[System.Reflection.BindingFlags]::GetProperty,$null,$this,@($args[1]))
                </Script>
            </ScriptMethod>
            <ScriptMethod>
                <Name>InvokeParamProperty</Name>
                <Script>
                    $type = $this.gettype();
                    $index = $args.count -1 ;
                    $methodargs=$args[1..$index]
                    $type.invokeMember($args[0],[System.Reflection.BindingFlags]::GetProperty,$null,$this,$methodargs)
                </Script>
            </ScriptMethod>
            <ScriptMethod>
                <Name>InvokeMethod</Name>
                <Script>
                    $type = $this.gettype();
                    $index = $args.count -1 ;
                    $methodargs=$args[1..$index]
                    $type.invokeMember($args[0],[System.Reflection.BindingFlags]::InvokeMethod,$null,$this,$methodargs)
                </Script>
            </ScriptMethod>
        </Members>
    </Type>
</Types>

Install-IP.ps1

function LoadTypeData()
{
# Load some TypeData
$SavedEA = $Global:ErrorActionPreference
$Global:ErrorActionPreference = "SilentlyContinue"
Update-TypeData -AppendPath "C:\DeployIP\comObject.types.ps1xml"
$Global:ErrorActionPreference = $SavedEA
}

function global:Get-MsiProperty
{
    PARAM (
    [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
    [String]$Filename,

    [Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true,ValueFromPipeline=$true)]
    [String]$Propertyname
    )

    # A quick check to see if the file exist
    if(!(Test-Path $Filename))
    {
        throw "Could not find " + $Filename
    }     

    # Create an empty hashtable to store properties in
    $msiProp = @{}
    # Creating WI object and load MSI database
    $wiObject = New-Object -com WindowsInstaller.Installer
    #$wiObject | Get-Member
    $wiDatabase = $wiObject.InvokeMethod("OpenDatabase", (Resolve-Path $Filename).Path, 0)
    # Open the Property-view
    $view = $wiDatabase.InvokeMethod("OpenView", "SELECT * FROM Property")
    $view.InvokeMethod("Execute")
    # Loop thru the table
    $r = $view.InvokeMethod("Fetch")
    while($r -ne $null)
    {
        # Add property and value to hash table
        $prop = $r.InvokeParamProperty("StringData",1)
        $value = $r.InvokeParamProperty("StringData",2)
        if ($prop -eq $PropertyName)
        {
            $msiProp = $value
        }
        # Fetch the next row
        $r = $view.InvokeMethod("Fetch")
    }
    $view.InvokeMethod("Close")     

    return $msiProp
}

function Connect-SCOServer{
<#
.SYNOPSIS
   Establishes a connection handle to the Orchestrator COM interface

.DESCRIPTION
    Establishes a connection handle to the Orchestrator COM interface that can be used
    with other functions that require authentication to succeed. This script must
    be run from the Orchestrator Management Server.

.PARAMETER UserName
    A valid user account with rights to perform actions against Orchestrator
    objects such as runbooks, folders, etc. Must be entered in the form of:
    DOMAIN\USERNAME

.PARAMETER Password
    The password associated with the provided user account.

.EXAMPLE
    $ConnectionHandle = Connect-SCOServer -Username "domain\user" -Password "Password"

.OUTPUTS
    System.Int32

#>

[CmdletBinding()]
	PARAM (
		[Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true, ParameterSetName="SpecifyUser")]
        [ValidateNotNullOrEmpty()]
        [String] $UserName = $(throw "Provide a valid user account (domain\username)"),

		[Parameter(Mandatory=$true,ValueFromPipelineByPropertyName=$true, ParameterSetName="SpecifyUser")]
        [ValidateNotNullOrEmpty()]
        [String] $password = $(throw "Provide a password for the user account)")
	)

	PROCESS
    {
        try
        {
	        $oismgr = new-object -com OpalisManagementService.OpalisManager
			$ohandle = New-Object object
			$handle = $handle = New-Object Runtime.InteropServices.VariantWrapper($ohandle)
            $retval = $oismgr.Connect($UserName, $password, [ref]$handle)
            #Write-Host "     Handle: $($Handle)"
            if ($handle.GetType().FullName -eq "System.Int32")
            {
                return $handle
            }
            else
            {
                Write-Error "Unable to get a valid connection handle to Orchestrator!" -ErrorAction Stop
            }
	    }
        catch
        {
            Write-Error "Exception occurred in $($MyInvocation.MyCommand): `n$($_.Exception)"
            throw new-object system.formatexception
        }
    }
}

function Install-SCOIntegrationPack{
<#
.SYNOPSIS
  Registers and optionally deploys an Integration Pack to the current computer.
  Assumes the current computer is a Management Server (and a Designer/Runbook Server
  in the case of deploying the IP)

.DESCRIPTION

.PARAMETER Handle
  The handle to the COM interface created using New-SCOConnection

.PARAMETER Filename
  The path and filename of the OIP file to be imported

.PARAMETER Deploy
  Switch parameter used when you want to also deploy the IP.

.EXAMPLE
  Install-SCOIntegrationPack -OIPFile "C:\Files\Test.OIP" -Deploy

.OUTPUTS

#>
    [CmdletBinding()]
	PARAM (

		[Parameter(Mandatory=$true)]
        [Int] $Handle,

		[Parameter(Mandatory=$true)]
        [String] $Filename,

        [Parameter(Mandatory=$false)]
	    [Switch] $Deploy

	)
    BEGIN
    {
        $oismgr = new-object -com OpalisManagementService.OpalisManager -Strict
        #oismgr | Get-Member
        $sh = new-object -com shell.application
        LoadTypeData

        #Write-Host "     Handle: $($Handle)"
    }
    PROCESS
    {
        try
        {

            if ($(Test-Path $filename) -eq $false)
            {
                Write-Error "File Not Found!"
                return
            }
            [System.IO.FileInfo]$oipFile = gi $filename

            $extractDir = $(Join-Path -Path $oipFile.DirectoryName -ChildPath $oipFile.BaseName)
	        if (Test-Path $extractDir)
            {
                ri $extractDir -Recurse -Force
            }

	        $ipSourceDirObj = $sh.namespace($oipFile.DirectoryName)
	        $ipSourceDirObj.NewFolder($oipFile.BaseName)
            $extractDirObj = $sh.namespace($extractDir)

            Write-Debug "`n`nExtracting files from the OIP"
            $zipFileName = Join-Path $oipFile.DirectoryName "$($oipFile.BaseName).zip"
            if (Test-Path $zipFileName)
            {
                ri $zipFileName -Force
            }
            $zipFile = $oipFile.CopyTo($zipFileName)
	        $zipFileObj = $sh.namespace($zipFile.FullName)

	        $extractDirObj.CopyHere($zipFileObj.Items(),8 -and 16 -and 256)

            $commonFiles = ${Env:CommonProgramFiles(x86)}
            if ($null -eq $commonFiles)
            {
                $commonFiles = ${Env:CommonProgramFiles}
            }
            $PacksDir = Join-Path $commonFiles "Microsoft System Center 2012\Orchestrator\Management Server\Components\Packs"
            $ObjectsDir = Join-Path $commonFiles "Microsoft System Center 2012\Orchestrator\Management Server\Components\Objects"

            if ($(Test-Path $PacksDir) -eq $false)
            {
                Write-Error "Could not find $($PacksDir)"
                return
            }
            if ($(Test-Path $ObjectsDir) -eq $false)
            {
                Write-Error "Could not find $($ObjectsDir)"
                return
            }

            # Copy the MSI File to %Common Files%\Microsoft System Center 2012\Orchestrator\Management Server\Components\Objects
            $msiFile = $extractDirObj.self | gci | Where {$_.extension -eq ".msi"}

            $newMSIfile = $(Join-Path $ObjectsDir $msiFile.Name)
            if (Test-Path $newMSIfile)
            {
                ri $newMSIfile -Force
            }
	        $msiFile.CopyTo($newMSIfile)
            $productName = Get-MSIProperty -Filename $msiFile.FullName -Propertyname "ProductName"
            $productCode =  Get-MSIProperty -Filename $msiFile.FullName -Propertyname "ProductCode"

            #now use the MgmtService to install the IP
	        [System.IO.FileInfo]$capfile = $extractDirObj.self | gci | Where {$_.extension -eq ".cap"}
	        if ($capfile)
	        {
	            Write-Host "     Extracting $($capFile)"
	            $capXml = New-Object XML
	            $capXml.Load($capfile.Fullname)

	            # Need to modify the CAP file to add Product ID and Product Name because Deployment Manager
                # reads the MSI file for this and inserts it into the DB so it displays in the UI. The COM
                # interface does not do this, so it needs to be done manually if you want it displayed.
                #
	            #     <ProductName datatype="string">IP_SYSTEMCENTERDATAPROTECTIONMANAGER_1.0.OIP</ProductName>
	            #    <ProductID datatype="string">{9422FCC6-11C4-4827-AC49-C5FD352C8AA0}</ProductID>

                [Xml]$prodName = "<ProductName datatype=`"string`">$($ProductName)</ProductName>"
	            [Xml]$prodID = "<ProductID datatype=`"string`">$($ProductCode)</ProductID>"

	            $c = $capXml.ImportNode($prodName.ProductName, $true)
	            $d = $capXml.ImportNode($prodID.ProductID, $true)

	            $capXml.Cap.AppendChild($c)
	            $capXml.Cap.AppendChild($d) 

	            $oIPinfo = new-object object
	            $ipinfo = $ipinfo= New-Object Runtime.InteropServices.VariantWrapper($capXml.get_innerxml())
	            #Write-Host "     Importing Integration Pack $($capXml.get_innerxml())"
	            Write-Host "     Importing Integration Pack $($extractDir+'\\'+$capFile)"
	            $retval = $oismgr.AddIntegrationPack($Handle, [ref]$ipinfo)
		    }

            # Copy the OIP File to the %Common Files%\Microsoft System Center 2012\Orchestrator\Management Server\Components\Packs
            # directory and change the name to the GUID of the IP
            $productCodeOipFilename = "$($ProductCode).OIP"

            $newOIPfile = $(Join-Path $PacksDir $productCodeOipFilename)
            if (Test-Path $newOIPfile)
            {
                ri $newOIPfile -Force
            }
            write-host "new OIP file: $($newOIPfile)"
            $oipFile.CopyTo($newOIPfile)

            if ($PSBoundParameters.ContainsKey('Deploy') -eq $false)
            {
                return
            }

            if ($(Test-Path $newMSIfile) -eq $false)
	        {
                Write-Error "Could not find $($newMSIfile)"
                return
            }

	        Write-Verbose "Running msiexec to install  $($newMSIfile)"

            $proc = New-Object System.Diagnostics.Process
            $proc.StartInfo.FileName = "msiexec.exe"
            $proc.StartInfo.Arguments =  "/i `"$($newMSIfile)`" ALLUSERS=1 /q"
            $proc.Start() | out-null
            $proc.WaitForExit()

        }
        catch
        {
            Write-Error "Exception occurred in $($MyInvocation.MyCommand): `n$($_.Exception)"

        }

    }    

}

Invoke-Install-IP.ps1


Param (
    [Parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [String] $OIPfile,
    [Parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [String] $UserName,
    [Parameter(Mandatory=$true)]
    [ValidateNotNullOrEmpty()]
    [String] $UserPassWord
)

Process
{
    #
    . C:\DeployIP\Install-IP.ps1
    $conn = Connect-SCOServer –username $UserName -password $UserPassWord
    Install-SCOIntegrationPack –handle $conn –filename $OIPfile -Deploy
}

IIP.bat

@echo off
set currentDirectory=%~dp0
set OIPFILE=%1
set UserName=%2
set UserPassword=%3
echo %currentDirectory%
md "C:\Program Files (x86)\Common Files\Microsoft System Center 2012"
md "C:\Program Files (x86)\Common Files\Microsoft System Center 2012\Orchestrator"
md "C:\Program Files (x86)\Common Files\Microsoft System Center 2012\Orchestrator\Management Server"
md "C:\Program Files (x86)\Common Files\Microsoft System Center 2012\Orchestrator\Management Server\Components"
md "C:\Program Files (x86)\Common Files\Microsoft System Center 2012\Orchestrator\Management Server\Components\Packs"
md "C:\Program Files (x86)\Common Files\Microsoft System Center 2012\Orchestrator\Management Server\Components\Objects"

@pushd %currentDirectory%
start %SystemRoot%\syswow64\WindowsPowerShell\v1.0\powershell.exe set-executionpolicy remotesigned
ping localhost -n 20
echo "begin" %date%, %time%>>Install-IP.log
start %SystemRoot%\syswow64\WindowsPowerShell\v1.0\powershell.exe .\Invoke-Install-IP.ps1 %OIPFILE% %UserName% %UserPassword%
ping localhost -n 60
echo "end" %date%, %time%>>Install-IP.log
@popd

 

时间: 2024-09-20 17:37:12

Deploy SCO IP using Powershell的相关文章

如何通过PowerShell获取Site Collection下被签出的文件

由于权限的设置,当文件被签出时导致别人不可见了,这对校验文件个数的人来说着实是件烦恼的事.幸好利用PowerShell,可以获取Site Collection下被签出的文件. Resolution Add-PSSnapin Microsoft.SharePoint.PowerShell function GetAllCheckOutFiles([string]$siteUrl){ $spSite=Get-SPSite $siteUrl $spSite.AllWebs|%{ $_.Lists|wh

PowerShell小技巧之配置机器的静态IP_PowerShell

家用电脑安装了一台虚拟机,默认没有配置网络,本来是想利用PowerShell启用无线网络,可是安装过程需要在线获取一些文件,所以失败,无奈只能配置静态IP地址了,参考了Ed Wilson的:Use PowerShell to Configure Static IP and DNS Settings $wmi = Get-WmiObject win32_networkadapterconfiguration -filter "ipenabled = 'true'" $wmi.Enable

使用PowerShell .Net获取电脑中的UUID_实用技巧

UUID含义是通用唯一识别码 (Universally Unique Identifier),这 是一个软件建构的标准,也是被开源软件基金会 (Open Software Foundation, OSF) 的组织应用在分布式计算环境 (Distributed Computing Environment, DCE) 领域的一部分. 组成 UUID是指在一台机器上生成的数字,它保证对在同一时空中的所有机器都是唯一的.通常平台会提供生成的API.按照开放软件基金会(OSF)制定的标准计算,用到了以太网

在SCO的一个网卡上面绑定多个IP地址的方法

ip地址 在SCO的一个网卡上面绑定多个IP地址的方法 在SCO Unix系统中多IP地址的设置是通过该网络接口的别名地址来实现的. 具体步骤如下:(举例为net0网卡的IP地址为192.168.1.2 掩码为255.255.255.0) 1.编辑/etc/tcp文件.vi /etc/tcp 2.找到包含网卡设备文件名net0的ifconfig命令行. 3.通过在命令行后添加ifconfig命令行来为该网卡设置其他的IP地址(即第二个IP地址.第三个IP地址--).若设置该网卡的第2个IP地址为

PowerShell脚本开发之批量扫描IP和端口_PowerShell

前面的文章中曾经发布了对指定IP进行批量端口扫描的方法和脚本,过PowerShell收发TCP和UDP消息包的方法以及通过PowerShell尝试登录SQLServer服务的方法,这构成了PSNet程序集用于通过PowerShell对网络状态进行操作.最近在不断尝试之下,找到了对指定范围的IP段进行扫描和对端口进行扫描的方法,本文将会介绍如何通过PowerShell批量扫描IP及其对应的端口. 依然在PSNet程序集的基础上进行扩展,首先在$env:PSSpace/PSNet/TCPOp下创建脚

PowerShell脚本开发之对指定IP进行端口扫描_PowerShell

前些天看到一篇关于Metasploit与PowerShell的文章,里面提到了一句关于端口扫描的语句,写的很简练,思路很不错,可以抛开笨重的Nmap直接扫描指定的指定IP的端口: 复制代码 代码如下: 1..1024 | %{ echo ((new-object Net.Sockets.TcpClient).Connect("192.168.10.26",$_)) "$_ is open"} 2>$null       语句中直接通过..列举了1到1024之间

PowerShell中把IP转换为长整形数字的方法_PowerShell

IPv4的地址其实可以换成为一个长整形的数字,使用数字类型来表示IP地址时,可以非常方便的进行地址范围的匹配比较.在.NET开发环境中一个IPAddress类,它的Address属性就是十进制的数字,而IPAddressToString属性是我们熟悉的点分十进制的字符串形式. 下面两个过滤器,分别处理"点分十进制"字符串到数字的转换和数字到"点分十进制"的转换. 复制代码 代码如下: //"点分十进制"字符串到数字的转换 filter Conve

PowerShell把IP地址转换成二进制的方法_PowerShell

IPv4地址其实是32位二进制数字,然后我们将它分成四段,每段8位.8位二进制能表达的范围是0~255,所以点分十进制的每一个数字的取值都在0~255之间.有的时候,比如为了换算子网掩码,我们需要将IP地址还原成二进制串的形式,如:11000000101010000000110000100001.今天小编看到一个例子就是来完成这个操作的. 代码如下: 复制代码 代码如下: $ipV4 = '192.168.12.33' -join ($ipV4.Split('.') | ForEach-Obje

构建SCO UNIX下的Web服务器

Internet/Intranet的网络应用过程中,Web服务器的建设必不可少,而国内的企事业单位在组网方案中多考虑向Intranet靠拢.构建自己的Web服务器,利用其中的WWW.E-mail等服务提高办公效率.在国内,SCO UNIX作为一个技术成熟的商用网络操作系统,广泛地应用在金融.保险.邮电等行业中.其自身内建了丰富的网络功能,自SCO OpenServer 5.0版以后,各项网络服务内容大大加强,加上其良好的稳定性和安全性,无需追加任何投资完全可以配置成企业内部的Web服务器,利用各