1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

VBAからPowerShellを操作してファイルを削除する

Last updated at Posted at 2025-07-26

はじめに

VBAからPowerShellを経由してファイルの削除を行うコードを紹介します。

通常はKillメソッドやFileSystemObject.DeleteFileメソッドを使用してファイルを削除できるため、使用する機会はまれだと思いますが、何かの参考になれば幸いです。

コード

'**** VBAからPowerShellを起動し、ファイル削除コマンドを実行する  *********
' filePathToDelete : 削除対象ファイルのファイルパス
'*********************************************************************
Public Function DeleteFileWithPowerShell(ByVal filePathToDelete As String) As Boolean
    
    Const psVisible As Integer = 0     'PowerShell画面表示(1)/非表示(0)
    Const psWaitFlg As Boolean = False 'PowerShell実行終了を待つ(True)/待たない(False)
    Dim psCommand As String            'PowerShellコマンド
    Dim psResult As Long               'PowerShell実行成功(0)/実行失敗(1)
    Dim wsh As Object                  'WScriptオブジェクト
    
    'WScriptオブジェクトを作成
    Set wsh = CreateObject("WScript.Shell")
    
    'PowerShellで実行するファイル削除コマンドを作成
    psCommand = "Remove-Item '" & filePathToDelete & "' -Force"
    
    'PowerShellでコマンド実行
    psResult = wsh.Run("powershell -NoLogo -ExecutionPolicy RemoteSigned -Command " & psCommand, psVisible, psWaitFlg)
    
    '実行成功 ※psWaitFlgがFalseの場合、削除可否に関わらず常に0(実行成功)が返却される
    If psResult = 0 Then
        DeleteFileWithPowerShell = True
     
    '実行失敗 ※psWaitFlgがTrueの場合、実行失敗時に1(実行失敗)が返却される
    ElseIf psResult = 1 Then
        DeleteFileWithPowerShell = False
        
    End If
    
End Function

呼び出し側のコードの例

Sub Test()

    Dim filePathToDelete As String '削除対象ファイルのファイルパス
    Dim psResult As Boolean        'PowerShellの実行結果
    
    filePathToDelete = "C:\work\test.txt"
    
    psResult = DeleteFileWithPowerShell(filePathToDelete)
    Debug.Print "実行結果:" & psResult
    
End Sub

PowerShellのパラメータ

使用するパラメータは以下の通りです。

パラメータ 説明
-NoLogo PowerShellスタートアップ時に著作権の見出しを非表示にする。
-ExecutionPolicy RemoteSigned ローカルで作成したスクリプトのみ一時的に実行可能にする。インターネットからダウンロードした署名のないスクリプトはブロックされる。
-Command 実行するスクリプトを指定する。

Remove-Itemコマンドレット

ファイルを削除するコマンド。使用するオプションは以下の通りです。

Remove-Item [パス] [オプション]
オプション 説明
-Path ファイルのパスを指定する。省略可能
-Force 隠しファイルや読み取り専用ファイルなどを削除する

備考

VBAからPowerShellのスクリプトを実行した際に以下のメッセージが表示される場合、セキュリティソフトの設定を確認してみてください。

セキュリティソフトに除外設定オプションの指定ができる場合、PowerShellの実行プログラム(powershell.exe)に適切な除外設定をすることで、VBAからPowerShellのスクリプトを実行できるようになります。

実行時エラー '70':書き込みできません。
image.png

参考サイト

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?