将Powershell脚本转换为VBA字符串

将Powershell脚本转换为VBA字符串,vba,powershell,Vba,Powershell,我已在Powershell ISE中创建了一个脚本,该脚本运行良好: $Connection = New-Object System.Data.SqlClient.SqlConnection $Cmd = New-Object System.Data.SqlClient.SqlCommand #Connection $Server = "*****" $Database = "****" $User ="******" $Pwd = "******" $Connection.Connectio

我已在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
在您的情况下,使用here字符串将脚本文本分配给
$command

$command = @'
    script text here
'@
确保使用一个带引号的字符串,这样就不会解释变量


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

只是想知道这与Bash有什么关系?此外,脚本块周围需要有花括号。为什么在命令行中调用PowerShell两次?另外,
-command
和要执行的脚本文本之间没有空格。