PowerShell:使用调用者的输入(参数)执行命令行

问题描述 投票:0回答:1

我正在尝试编写一个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文件。

powershell parameters arguments io-redirection
1个回答
0
投票

定义您的函数,如下所示:

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'
  • 也就是说,必须像 shell 命令那样调用 PowerShell 函数、cmdlet、脚本和外部程序 - foo arg1 arg2
     - 
    不像 C# 方法那样 - foo('arg1', 'arg2')
    如果您使用
    ,
     来分隔参数,您将构造一个 
    数组,命令将其视为 单个参数 请参阅
    此答案此答案了解更多信息。
© www.soinside.com 2019 - 2024. All rights reserved.