vba - 将 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
我尝试了不同的报价,但没有成功。有任何想法吗 ?
解决方案
您可以将脚本编码为 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。
推荐阅读
- tensorflow - 这么快就用完了内存-tensorflow-gpu
- python - Python如何检查列表中的项目是否为浮点数,如果是,将其更改为字符串?
- javascript - 如何在对象数组中获取最大值
- xslt - BizTalk 映射:如何从循环中提取单行,但可能将其扩展到几个目标字段?
- c# - c# - 如何从选定的列表框项中创建条件?
- node.js - array.forEach 什么时候在 nodejs 中执行?
- r - 使用 plot.ts 在 x-avis 上添加日期而不是数值
- bash - 是否可以编写一个 bash 脚本,该脚本可以使用另一个具有图形界面的程序来编辑文件?
- java - 黄瓜:如何从特定功能文件运行标记场景
- c++ - OpenCV 4.0 -- 等待从 VideoCapture 捕获