VBA Macro to run PowerShell Command

我的梦境 提交于 2021-02-10 18:49:27

问题


I am trying to create a macro, that would be able to rename all files with ".docx" extension in a folder.

The PowerShell command works when used directly, but when used through the VBA code, it's not executing.

Sub test()
    Dim retval
    Dim pscmd

    pscmd = "PowerShell -ExecutionPolicy Bypass -Command ""Get-ChildItem -Path *.docx -Recurse | Rename-Item -NewName {$_.Name.Substring(0,7) + $_.Extension }"""

    retval = Shell(pscmd, vbNormalFocus)

    Debug.Print pscmd
End Sub

The script is executing without compilation errors, but the files are not being renamed.

What do I need to change?


回答1:


You have to provide the path where your files exist Try this and change the path to suit you

Sub Test()
Dim retval, pscmd

pscmd = "PowerShell -ExecutionPolicy Bypass -Command ""Get-ChildItem -Path " & ThisWorkbook.Path & "\Files\" & " *.docx -Recurse | Rename-Item -NewName {$_.Name.Substring(0,7) + $_.Extension }"""
retval = Shell(pscmd, vbNormalFocus)

Debug.Print pscmd
End Sub


来源:https://stackoverflow.com/questions/52956136/vba-macro-to-run-powershell-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!