【发布时间】: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