首页 > 解决方案 > 尝试从 Word 宏运行 Powershell 脚本时出现“权限被拒绝”错误

问题描述

我需要使用 word 宏中的参数运行 powershell 脚本。现在,即使尝试简单地从 VBA 运行脚本也没有成功。我执行以下操作:

Sub Powershell_Run()

sCmd = "powershell -file ""C:\Users\i351063\Desktop\Scripts\NewAttempt.ps1"""
Set xShell = CreateObject("Wscript.Shell")
Set xShellExec = xShell.Run(sCmd)
rReturn = xShellExec.Run("C:\Users\i351063\Desktop\Scripts\NewAttempt.ps1")

End Sub

执行此代码会返回错误:Set xShellExec = xShell.Run(sCmd) 行上的“运行时错误 '70': Permission denied”。我做错了什么?如何修复错误?提前非常感谢!

UPD:Powershell 代码(我想将文件名作为参数从 VBA 传递到 PS,现在它已在代码中初始化)

Param([string]$filename)
$filename = "HT.docm"

Add-Type -AssemblyName "Microsoft.Office.Interop.Word" 
$word = [Runtime.Interopservices.Marshal]::GetActiveObject('Word.Application')
$wshell = New-Object -ComObject Wscript.Shell

$doc = $word.Documents | Where-Object {$_.Name -eq "$filename"}
    If (!$doc) 
         {
            $form.Close()
            [void] $wshell.Popup("Failed to find an opened report",0,"Report not found",0x1)
            $word.ScreenUpdating = $true
            Break
        }
    Else {...}

标签: vbapowershellms-word

解决方案


推荐阅读