在 windows 10 powershell 中使用 sqlplus 执行 sql 文件

Executing sql file with sqlplus in windows 10 powershell

我创建了一个 .bat 文件以通过 windows 任务计划定期导出 csv 文件,效果很好。 但是当我切换到 Powershell 时不工作。它 returns(在 ISE 中和右键单击 .ps1“运行 with Powershell”)具有:

SQL*Plus: Release 19.0.0.0.0 - Production on Sun May 2 14:05:52 2021
Version 19.10.0.0.0
Copyright (c) 1982, 2020, Oracle. All rights reserved.
ERROR: ORA-12154: TNS:could not resolve the connect identifier specified

So.I不确定我做错了什么。变量输入是虚拟的。

在我的 .bat 中包含:

SET NLS_LANG=.AL32UTF8
SET hostIp="123.123.1.12"
SET username="user1"
SET password="pass1"
SET port="1521"
SET service="myDBname"
SET sqlPath="C:\My script\TEST_EXPORT.sql"
sqlplus %username%/%password%@%hostIp%:%port%/%service% @"%sqlPath%"

在我的 .ps1 中包含:

cls
$hostIp="123.123.1.12"
$username="user1"
$password="pass1"
$port="1521"
$service="myDBname"
$sqlPath="C:\My script\TEST_EXPORT.sql"
echo "$username/$password@$hostIp`:$port/$service @$sqlPath"
sqlplus "$username/$password@$hostIp`:$port/$service @$sqlPath"

尝试使用 composite formatting 构建参数字符串。好处是可以构建字符串而不用担心报价问题。请注意,无需转义字符串中的冒号 `:,因为它不会被解释为作用域运算符。

# A variable that contains double quote
$quote = '"'

$("{0}/{1}@{2}:{3}/{4} @{5}{6}{5}" -f $username, $password, $hostIp, $port, $service, $quote, $sqlPath,$quote)
user1/pass1@123.123.1.12:1521/myDBname @"C:\My script\TEST_EXPORT.sql"

另一种构建复杂字符串的替代方法是 string interpolation。下面是三个版本,它们包含不同的技术来包含双引号。这同样适用于复合格式。

# Double-doublequote version. I'd avoid this, as multiple double quotes are hard to read
"${username}/${password}@{$hostIp}:${port}/${service} @""${sqlPath}"""
user1/pass1@{123.123.1.12}:1521/myDBname @"C:\My script\TEST_EXPORT.sql"
# Backtick-escape version
"${username}/${password}@{$hostIp}:${port}/${service} @`"${sqlPath}`""
user1/pass1@{123.123.1.12}:1521/myDBname @"C:\My script\TEST_EXPORT.sql"
# Quote in a variable version
"${username}/${password}@{$hostIp}:${port}/${service} @${quote}${sqlPath}${quote}"
user1/pass1@{123.123.1.12}:1521/myDBname @"C:\My script\TEST_EXPORT.sql"