我已经在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
我想在不使用文件script.ps1的情况下直接从vba调用此代码。 我试过这个:
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
我尝试了不同的引用而没有成功。 有什么想法吗?
答案 0 :(得分:0)
您可以将脚本编码为base64并使用/**
* Rethrows a {@code Throwable}, wrapping it in {@code CompletionException} if it isn't already wrapped.
*
* @param <T> the return type expected by the caller
* @param throwable a Throwable
* @return an undefined value (the method always throws an exception)
* @throws CompletionException wraps {@code throwable}
*/
public <T> T rethrowException(Throwable throwable)
{
if (throwable instanceof CompletionException)
throw (CompletionException) throwable;
if (throwable == null)
throwable = new NullPointerException("throwable may not be null");
// According to https://stackoverflow.com/a/49261367/14731 some methods do not wrap exceptions
throw new CompletionException(throwable);
}
来自powershell.exe -EncodedCommand
帮助文档:
powershell.exe
在您的情况下,使用here-string:
将脚本文本分配给# 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
请务必使用单引号here-string,以便不解释变量。
此时,您可以复制$command = @'
script text here
'@
的输出并将其放入您的vbscript中。