【问题标题】:Passing connection variables from xml to powershell将连接变量从 xml 传递到 powershell
【发布时间】:2013-06-18 15:00:35
【问题描述】:

我正在尝试创建一个 SQL powershell 脚本来检查多个 SQL 服务器上的某些条件。我想连接的服务器列表存储在一个 XML 文件中。这个想法是,powershell 将解析 XML 文件并一次登录到每个服务器。我无法让这个工作。我是 powershell 新手,所以也许我没有做一些简单的事情?

这里是仅列出 3 个服务器的缩写 XML:

<Objs Version="1.1.0.1">   <Obj RefId="0">
    <TN RefId="0">
      <T>System.Data.DataRow</T>
      <T>System.Object</T>
    </TN>
    <ToString>System.Data.DataRow</ToString>
    <Props>
      <S N="InstanceName">SERVER1\INSTANCE1</S>
      <S N="DatabaseName">master</S>
    </Props>   </Obj>   <Obj RefId="1">
    <TNRef RefId="0" />
    <ToString>System.Data.DataRow</ToString>
    <Props>
      <S N="InstanceName">SERVER1\INSTANCE2</S>
      <S N="DatabaseName">master</S>
    </Props>   </Obj>   <Obj RefId="2">
    <TNRef RefId="0" />
    <ToString>System.Data.DataRow</ToString>
    <Props>
      <S N="InstanceName">SERVER2\INSTANCE1</S>
      <S N="DatabaseName">master</S>
    </Props>   </Obj> </Objs>

这是我遇到问题的代码部分:

$filepath="\\Server\Test\SQLServerInfo.xml" [xml]$xml = Get-Content $filepath

$group = $xml.Objs.Obj.Props

# Parse the XML file  
     foreach ($i in $group) {

             $CurrentServer = $i.S.Item(0)
             $CurrentDB = $i.S.Item(1)

             $CurrentServer   # Show value of variable
             $CurrentDB       # Show value of variable

        # Connect to the SQL Server
            $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
            $SqlCmd = New-Object System.Data.SqlClient.SqlCommand
            $SqlConnection.ConnectionString = "Server=$CurrentServer;Database=$CurrentDB;Integrated Security=SSPI"
            $SqlConnection.ConnectionString
            $SqlConnection.Open()

脚本失败,提示找不到服务器或无法访问。

有趣的是,当我将变量打印到屏幕上时($CurrentServer 和 $CurrentDB),值是正确的。但是,如果我将这两行更改为:

写入主机“$CurrentServer”
写入主机“$CurrentDB”

我得到以下输出:

System.Xml.XmlElement
System.Xml.XmlElement

当我告诉脚本在分配变量后显示 $SqlConnection.ConnectionString 时,它再次显示 System.Xml.XmlElement 而不是实际变量。所以,我不知道这些变量是如何通过 XML 分配的。

我的问题是如何将我的变量放入连接字符串中。

提前致谢。

【问题讨论】:

    标签: sql powershell


    【解决方案1】:

    将此作为您的连接字符串:

    $SqlConnection.ConnectionString = "Server=$($CurrentServer.'#text');Database=$($CurrentDB.'#text');Integrated Security=SSPI"
    

    【讨论】:

      猜你喜欢
      • 2016-08-02
      • 2015-12-29
      • 1970-01-01
      • 2019-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多