首页 > 解决方案 > 将 Powershell 脚本转换为 VBA 字符串

问题描述

我在 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

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

标签: vbapowershell

解决方案


您可以将脚本编码为 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

在您的情况下,将您的脚本文本分配给$command使用此处的字符串:

$command = @'
    script text here
'@

请务必使用单引号 here-string,以免解释变量。

此时,您可以将输出复制$encodedCommand并放入您的 vbscript。


推荐阅读