我正在尝试编写一个powershell脚本,当它执行时,它需要2个变量并将其传递给一个函数。该函数使用输入变量运行命令行。
代码:
function ExecuteSQLScript($sqlfile, $dbconnection) {
& 'sqlplus ' $dbconnection' @'$sqlfile ' <nul'
}
main block:
ExecuteSQLScript('c:\test.sql', 'testing/password@db')
*basically I want the command line to execute:
SQLPLUS testing/password@db @c:\test.sql < nul*
运行命令行调用SQLPLUS在powershell中执行sql文件。
定义您的函数,如下所示:
function ExecuteSQLScript($sqlfile, $dbconnection) {
@() | sqlplus $dbconnection "@$sqlfile"
}
@() | ...
相当于 PowerShell 中 cmd.exe
的 <NUL
(PowerShell 没有 <
运算符); @()
是一个空数组,在管道中枚举,因此将 nothing 发送到外部程序的 stdin 流。
&
仅当命令名称被 引用 和/或包含 变量引用 时才需要调用;虽然您可以使用 & sqlplus ...
,但只需 sqlplus ...
就足够了。
本身充当命令参数的变量引用(上面的
$dbonnection
)永远不需要在PowerShell中引用(除非您想预先显式强制字符串化,例如"$dbconnection"
)
@
是 PowerShell 中的元字符,因此它必须被转义或位于带引号的字符串内;这里,使用 可扩展(双引号)字符串 ("..."
) 来逐字使用 @
并使用字符串插值(扩展)来附加 $sqlfile
的值。
调用,例如:
# Note: *Whitespace* between arguments, no (...)
ExecuteSQLScript 'c:\test.sql 'testing/password@db'