使用Powershell

时间:2015-05-12 21:15:44

标签: excel powershell

我使用powershell来自动完成日常任务。它本质上是一个宏,用于刷新链接到外部源的数据,然后发送电子邮件。问题是Excel在尝试刷新数据时会自动提示输入用户名/密码。我做了一些挖掘,并且无法通过设置DisplayAlert = False来绕过它,并且无法从Excel的设置中进行更改。我的凭据已保存,因此我真正需要做的是让脚本按下"输入"。

我目前进行了以下设置:使用Windows Scheduler,我首先启动一个Powershell脚本,该脚本将打开Excel并运行宏来刷新数据。当Excel提示输入凭据时,宏将被卡住。我有第二个任务,计划在第一个任务后2分钟运行,其目的是按下"输入"摆脱提示。

我已经为第二项任务尝试了几个脚本,但我似乎无法做到正确。 我试过的内容如下:

[void]   [System.Reflection.Assembly]::LoadWithPartialName("'Microsoft.VisualBasic")
[void] [System.Reflection.Assembly]::LoadWithPartialName("'System.Windows.Forms")
$wshell = New-Object -ComObject wscript.shell;
$wshell.AppActivate("Windows Security")
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")

$excel = [Runtime.Interopservices.Marshal]::GetActiveObject('Excel.Application')
[void] [System.Reflection.Assembly]::LoadWithPartialName("'Microsoft.VisualBasic")
[void] [System.Reflection.Assembly]::LoadWithPartialName("'System.Windows.Forms")
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")

关于如何绕过/接受提示的任何想法?

提前致谢。

2 个答案:

答案 0 :(得分:0)

请分享数据链接以获取更多详细信息,但是,我会简单地以编程方式重新创建数据链接,如果确实存在通知&登录可以保存,例如宏接受传递和登录

如果它是SQL连接,那么它看起来像这样:

Sub Recreate(serverInstance as String, database as String, userId as String, password as String) 
    sConn = "OLEDB;Provider=SQLOLEDB;Data Source=" & _
                    serverInstance & ";Initial Catalog=" & database & _
                    ";User ID=" & userId & ";Password=" & password & ";"

    Set qt = wks.QueryTables.Add(Connection:=sConn, _
                    Destination:=Target)
    With qt
            .CommandType = xlCmdSql
            .CommandText = sql
            .Name = sName
            .RefreshStyle = xlOverwriteCells
            .Refresh BackgroundQuery:=False 'Execute SQL
        End With
End Sub

答案 1 :(得分:0)

我们使用的解决方案与您尝试过的解决方案略有不同。也许它在细节中......

[void] [System.Reflection.Assembly]::LoadWithPartialName
("'Microsoft.VisualBasic")
[Microsoft.VisualBasic.Interaction]::AppActivate("Windows Security")

[void] [System.Reflection.Assembly]::LoadWithPartialName("'System.Windows.Forms")
[System.Windows.Forms.SendKeys]::SendWait("{ENTER}")