0

我有一个字符串($dataBaseName 变量)的问题,我通过一个函数从 web.config 文件中提取。

当我写主机时它显示值,当我使用 GetType() 时它显示它是一个 System.String,但在与另一个变量连接时它不会提取值。最终,我想将它用作从我正在编写的模块中调用的参数。

这是我用来获取遇到问题的 $dataBaseName 变量的代码。

# Get WebConfig Detail
$configPath = Get-ItemProperty 'HKLM:\SOFTWARE\Wow6432NodeItem\Key\Settings' `
| Select @{Name="Path";Expression={$_.installPath + "\Item\Web.config" }} `
-ExpandProperty Path
$config = [xml](Get-Content $configPath)

function Get-WebConfigKey($key) {
    $config.SelectSingleNode("//appSettings/add[@key='$key']").Value
}

# Set Database Variable
$databaseName = Get-WebConfigKey "databaseName"

后来我尝试通过将它与计算机变量组合来引用它,使用许多不同的方法来连接它(with ()、string.format 等),但它只会显示 $instance 的值的“ComputerName\”多变的。

$computer = Get-Content env:computername
$instance = $computer + "\" + $databaseName

如果我对数据库名称进行硬编码,它可以正常工作。

$instance = $computer + "\" + "exampleDatabase"

我将这些信息用于 SQL 查询,如下所示。稍后我实际上将使用安全字符串作为密码,但这仅供参考。

$computer = Get-Content env:computername
$instance = $computer + "\" + $databaseName
$server = new-object ('Microsoft.SqlServer.Management.Smo.Server') $instance
$server.ConnectionContext.LoginSecure=$false
$server.ConnectionContext.set_Login("sa")
$server.ConnectionContext.set_Password("examplePassword")
$db = $server.Databases.Item("Maduro")
[String] $sql = "SELECT SomeRow FROM SomeTalbe;"
$result = $db.ExecuteWithResults($sql)
$table = $result.Tables[0]
foreach ($row in $table) {
    $someVarible = $row.SomeRow
}

Web.config 摘录:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
    <appSettings>
        <!--NEXT GEN EF DB INFO-->
        <add key="providerName" value="System.Data.SqlClient" />
        <add key="serverName" value="LOCALHOST\Instance" />
        <add key="databaseName" value="database" />
    </appSettings>
</configuration>
4

0 回答 0