VBScriptで外部コマンドを実行する方法・Execメソッド †WshShellオブジェクトのExecメソッドを使い、VBScriptで外部コマンドを実行する方法といくつかの実行方法のサンプルを以下に記します。 関連記事 †とりあえずExecメソッドを利用して外部コマンドを起動する †mkdirコマンドを使用し、実行したカレントディレクトリににsakuraディレクトリを作成してみます。 Dim oWshShell, oExec Set oWshShell = CreateObject("WScript.Shell") Set oExec = oWshShell.Exec("mkdir sakura") 上記のVBScriptでsakuraディレクトリが作成されます。 Execメソッドを利用してnotepadを起動してみる †Dim oWshShell, oExec Set oWshShell = CreateObject("WScript.Shell") Set oExec = oWshShell.Exec("notepad") このVBScriptを起動すると、notepadが起動してVBScriptが終了します。 Dim oWshShell, oExec Set oWshShell = CreateObject("WScript.Shell") Set oExec = oWshShell.Exec("notepad") Do While oExec.Status = 0 WScript.Sleep 100 Loop WScript.Echo "Bye!" 外部コマンドが出力する文字列を取得する †WshScriptExecオブジェクトのStdOutプロパティ, StdErrプロパティを利用することにより実現できます。 WshScriptExec.StdOut サンプル †このVBScriptのサンプルは、dirコマンドを実行しdirコマンドがSTDOUTとSTDERRに出力した内容を表示します。 Dim oWshShell, oExec, oStdOut, oStdErr Set oWshShell = CreateObject("WScript.Shell") Set oExec = oWshShell.Exec("cmd /C dir") Set oStdOut = oExec.StdOut Set oStdErr = oExec.StdErr szStr = "STDOUT" & vbCrLf Do While Not oStdOut.AtEndOfStream szStr = szStr & oStdOut.ReadLine() &vbCrLf Loop WScript.Echo szStr szStr = "STDERR" & vbCrLf Do While Not oStdErr.AtEndOfStream szStr = szStr & oStdErr.ReadLine() &vbCrLf Loop WScript.Echo szStr WshScriptExec.StdErr サンプル †上記のサンプルとほとんど同じです。 Dim oWshShell, oExec, oStdOut, oStdErr Set oWshShell = CreateObject("WScript.Shell") Set oExec = oWshShell.Exec("cmd /C dir /ABCDEFG") Set oStdOut = oExec.StdOut Set oStdErr = oExec.StdErr szStr = "STDOUT" & vbCrLf Do While Not oStdOut.AtEndOfStream szStr = szStr & oStdOut.ReadLine() &vbCrLf Loop WScript.Echo szStr szStr = "STDERR" & vbCrLf Do While Not oStdErr.AtEndOfStream szStr = szStr & oStdErr.ReadLine() &vbCrLf Loop WScript.Echo szStr |