LoginSignup
2
3

More than 1 year has passed since last update.

VBSでPowerShell起動

Last updated at Posted at 2023-01-16

概要

ps1をダブルクリックすると実行されずに開いてしまうので、ダブルクリックで実行出来るようにするためVBSを起動ファイルとして使用する

実装

vbs
'====================================
' ps1の起動用スクリプト
'====================================
Option Explicit

'FileSystemObject、ShellObject
Dim fileSystemObj
Dim WshShell

'VBSパス、VBS格納フォルダ、ps1パス
Dim vbsPath
Dim vbsFolder
Dim ps1Path

'オブジェクト参照
Set fileSystemObj = CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")

'VBSパス
vbsPath = Wscript.ScriptFullName
'VBS格納フォルダ
vbsFolder = fileSystemObj.GetFile(vbsPath).ParentFolder
'ps1パス
ps1Path = vbsFolder & "\TEST.ps1"

'.ps1が存在するかを確認
If fileSystemObj.FileExists(ps1Path) Then
    'ps1起動オプション
    Const OPT = "Powershell -ExecutionPolicy Unrestricted -NoExit "
    'ps1起動
    WshShell.Run OPT & ps1Path,[※1],true 
ELSE
    msgbox ps1Path,,"NotFileExists"
End If

'オブジェクト解放
Set fileSystemObj = Nothing
Set WshShell = Nothing
Wscript.Quit

[※1]
1 = 表示
0 = 非表示

上記だとフォルダ名に空白、()などがあった時にパスが読み取れなくなるので以下のようにエスケープさせる

vbs

'====================================
' ps1の起動用スクリプト
'====================================
Option Explicit

'FileSystemObject、ShellObject
Dim fileSystemObj
Dim WshShell

'VBSパス、VBS格納フォルダ、ps1パス
Dim vbsPath
Dim vbsFolder
Dim ps1Path

'オブジェクト参照
Set fileSystemObj = CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")

'VBSパス
vbsPath = Wscript.ScriptFullName
'VBS格納フォルダ
vbsFolder = fileSystemObj.GetFile(vbsPath).ParentFolder
'ps1パス
ps1Path = vbsFolder & "\TEST.ps1"
2023/1/27修正
- ps1Path = Replace(ps1Path," ","` ") 
- ps1Path = Replace(ps1Path,"(","`(")
- ps1Path = Replace(ps1Path,")","`)")

+ ps1Path = Chr(34) & ps1Path & Chr(34)
'.ps1が存在するかを確認
If fileSystemObj.FileExists(Replace(ps1Path,"`","")) Then
    'ps1起動オプション
    Const OPT = "Powershell -ExecutionPolicy Unrestricted -NoExit "
    'ps1起動
    WshShell.Run OPT & ps1Path,[※1],true 
ELSE
    msgbox ps1Path,,"NotFileExists"
End If

'オブジェクト解放
Set fileSystemObj = Nothing
Set WshShell = Nothing
Wscript.Quit

2
3
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
2
3