【问题标题】:Convert Powershell script into VBA string将 Powershell 脚本转换为 VBA 字符串
【发布时间】:2018-05-15 13:37:41
【问题描述】:

我在 Powershell ISE 中创建了一个运行良好的脚本:

$Connection = New-Object System.Data.SqlClient.SqlConnection
$Cmd = New-Object System.Data.SqlClient.SqlCommand

#Connection
$Server = "*****"
$Database = "****"
$User ="******"
$Pwd = "******"
$Connection.ConnectionString = "Server= $Server; Database= $Database; 
Integrated Security= False; uid= $User; Password= $Pwd;"
$Connection.Open()

#Execute query
[string]$Query = Get-Content "C:\Users\****\Desktop\testSQL.sql"
$cmd = $connection.CreateCommand()
$cmd.CommandText = $Query
if ($cmd.ExecuteNonQuery() -ne -1)
{
echo "Failed";
}

$Connection.Close()

我设法使用 VBA 从 MS Access 调用此脚本。

Public Sub Script()
    Dim ScriptPath As String
    ScriptPath = "C:\Users\****\Desktop\Reprise_Besoins_2018.ps1"
    Call Shell("powershell -noexit -command powershell.exe -Executionpolicy 
    Bypass -file " & ScriptPath, vbMaximizedFocus)
End Sub

我想直接从 vba 调用此代码,而不使用文件 script.ps1。 我试过这个:

Public Sub Script2()
Dim ScriptText As String
ScriptText = "$Connection = New-Object System.Data.SqlClient.SqlConnection " & vbCrLf & _
            "$Cmd = New-Object System.Data.SqlClient.SqlCommand" & vbCrLf & _
            "$Server = '****' " & vbCrLf & _
            "$Database = '****' " & vbCrLf & _
            "$User ='****' " & vbCrLf & _
            "$Pwd = '****' " & vbCrLf & _
            "$Connection.ConnectionString = 'Server= $Server; Database= $Database; Integrated Security= False; uid= $User; Password= $Pwd;'" & vbCrLf & _
            "$Connection.Open() " & vbCrLf & _
            "[string]$Query = Get-Content 'C:\Users\****\Desktop\testSQL.sql' " & vbCrLf & _
            "$cmd = $connection.CreateCommand() " & vbCrLf & _
            "$cmd.CommandText = $Query " & vbCrLf & _
            "if ($cmd.ExecuteNonQuery() -ne -1)" & vbCrLf & _
            "{echo 'Failed' } " & vbCrLf & _
            "$Connection.Close() "

Call Shell("PowerShell -noexit powershell.exe  -Executionpolicy Bypass -Command" & ScriptText, vbNormalFocus)
End Sub

我尝试了不同的报价,但没有成功。 有什么想法吗?

【问题讨论】:

  • 只是好奇这与 Bash 有什么关系?此外,脚本块需要有花括号。
  • 为什么要在命令行中调用 PowerShell 两次?
  • 另外,-Command 和您要执行的脚本文本之间也没有空格。

标签: vba powershell


【解决方案1】:

您可以将脚本编码为 base64 并使用 powershell.exe -EncodedCommand


来自powershell.exe帮助文档:

# To use the -EncodedCommand parameter:
$command = 'dir "c:\program files" '
$bytes = [System.Text.Encoding]::Unicode.GetBytes($command)
$encodedCommand = [System.Convert]::ToBase64String($bytes)
powershell.exe -encodedCommand $encodedCommand

在您的情况下,使用 here-string 将您的脚本文本分配给 $command

$command = @'
    script text here
'@

请务必在此处使用单引号字符串,以免解释变量。

此时,您可以将$encodedCommand 的输出复制到您的vbscript 中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-03-02
    • 1970-01-01
    • 1970-01-01
    • 2014-10-08
    • 2014-07-11
    • 2021-04-15
    相关资源
    最近更新 更多