为什么我的PowerShell脚本中没有返回任何数据

时间:2019-05-21 21:23:49

标签: oracle powershell

add-type -AssemblyName System.Data.OracleClient
$username = "SYSTEM"
$password = "password"
$data_source = "production"
$connection_string = "User Id=$username;Password=$password;Data Source=$data_source"

try{
$statement = "SELECT SYSDATE FROM DUAL"
$con = New-Object System.Data.OracleClient.OracleConnection($connection_string)

$con.Open()

$cmd = $con.CreateCommand()
$cmd.CommandText = $statement

$result = $cmd.ExecuteReader()
# Do something with the results...
Write-Host $result + "data"
If($result.HasRows) {
    try {
    while ($result.Read())
        {
            "[0] : " + $result.GetValue(0)
        }
    }
    catch
    {
        #log error
    }
    finally
    {
        $con.Close() 
    }
}

} catch {
    Write-Error (“Database Exception: {0}`n{1}” -f `
        $con.ConnectionString, $_.Exception.ToString())
} finally{
    if ($con.State -eq ‘Open’) { $con.close() }
}

我正在从DUAL执行SELECT SYSDATE

我预计19年5月21日

但是不返回任何数据。 (也没有错误)

1 个答案:

答案 0 :(得分:1)

如以上注释中所述,您必须将$result的内容发送到PowerShells输出流。输出流用于实现Powershell的管道功能。如果您将代码包装在例如“ myCode.ps1”并通过以下方式调用它:

.\myCode.ps1

$result的内容被推送到输出流(管道)中。由于没有其他cmdlet附加到myCode.ps1的调用中,因此Powershell主机(=您的命令行)将接收内容。主机的默认行为是转储内容。

因此,将以下内容添加到您的代码中:

$result = $cmd.ExecuteReader()
# Return $result to the pipeline
$result

详细了解管道here和流here

UPDATE1 :此link或多或少地描述了问题的代码示例。 Orcale .NET数据提供程序可能丢失了。通过以下方式添加:

 Add-Type -Path "PathToDll\Oracle.ManagedDataAccess.dll" 

希望有帮助。

相关问题