2019年02月21日


PATH 環境変数をセミコロンで区切って一つづつコマンドプロンプトに表示するバッチファイル path-list.bat

echo で VBScript の実行文を表示して、%temp%\_.vbs に書き出してそのまま実行するという、バッチファイルです。システム用とユーザ用を別々に作成して実行しています。

PATH コマンドの代りに使えます。

@echo off
echo ▼ システム
cmd /c echo Set ws=WScript.CreateObject("WScript.Shell"):Set wv=ws.Environment("SYSTEM"):pt=wv("PATH"):ad=Split(pt,";"):For I=0 To Ubound(ad):Wscript.echo ws.ExpandEnvironmentStrings(ad(I)):Next>%temp%\_.vbs&cscript.exe /NOLOGO %temp%\_.vbs
echo ▼ ユーザ
cmd /c echo Set ws=WScript.CreateObject("WScript.Shell"):Set wv=ws.Environment("USER"):pt=wv("PATH"):ad=Split(pt,";"):For I=0 To Ubound(ad):Wscript.echo ws.ExpandEnvironmentStrings(ad(I)):Next>%temp%\_.vbs&cscript.exe /NOLOGO %temp%\_.vbs
pause







posted by at 13:42 | ツール | このブログの読者になる | 更新情報をチェックする



WSF : 架空氏名作成スクリプト

選択する漢字によっては、さらに架空度が増します。

結果をコマンドプロンプトへ出力する事を前提としているので、Wscript.exe でスクリプトが実行された場合、Crun という関数で コマンドプロンプトを開いて cscript.exe でスクリプトを強制的に再実行させるようにしています。

<JOB>
<OBJECT id="WshShell" progid="WScript.Shell" />
<SCRIPT language="VBScript">
' ***********************************************************
' 処理開始
' ***********************************************************
nMax = 20	' 取得する人数

Crun

' 1、2 は教育漢字の最初
strName1 = "愛悪圧安暗案以位囲委意易異移胃衣遺医域育一印員因引飲院右宇羽"
strName2 = "雨運雲営映栄永泳英衛液益駅円園延沿演遠塩央往応横王黄億屋恩温"
strName3 = "男也一行樹之朗七人"
strName4 = "子代美恵"

For i = 1 to nMax

	' 姓1文字目
	nTarget = Random( 1, Len(strName1) )
	strName = Mid( strName1, nTarget, 1 )

	' 1文字目と2文字目が一致したら除外
	nTarget2 = nTarget
	Do while( nTarget = nTarget2 )
		nTarget2 = Random( 1, Len(strName1) )
	Loop

	' 姓2文字目
	strName = strName & Mid( strName1, nTarget2, 1 ) & " "

	' 名1文字目
	nTarget = Random( 1, Len(strName2) )
	strName = strName & Mid( strName2, nTarget, 1 )

	' 性別
	nTarget = Random( 0, 1 )

	' 性別によって名2文字目を決定
	if nTarget = 0 then
		nTarget = Random( 1, Len(strName3) )
		strName = strName & Mid( strName3, nTarget, 1 )
	else
		nTarget = Random( 1, Len(strName4) )
		strName = strName & Mid( strName4, nTarget, 1 )
	end if
	
	Wscript.Echo strName

Next

' ***********************************************************
' 範囲内ランダム値取得
' ***********************************************************
Function Random( nMin, nMax )

	Randomize
	Random = nMin + Int(Rnd * (nMax - nMin + 1))

End function

' ***********************************************************
' Cscript.exe で強制実行
' ***********************************************************
Function Crun( )

	Dim str

	str = WScript.FullName
	str = Right( str, 11 )
	str = Ucase( str )
	if str <> "CSCRIPT.EXE" then
		str = WScript.ScriptFullName
		strParam = " "
		For I = 0 to Wscript.Arguments.Count - 1
			if instr(Wscript.Arguments(I), " ") < 1 then
				strParam = strParam & Wscript.Arguments(I) & " "
			else
				strParam = strParam & Dd(Wscript.Arguments(I)) & " "
			end if
		Next
		Call WshShell.Run( "cmd.exe /c cscript.exe " & Dd(str) & strParam & " & pause", 3 )
		WScript.Quit
	end if

End Function

' ***********************************************************
' ダブルクォート
' ***********************************************************
Function Dd( strValue )

	Dd = """" & strValue & """"

End function

</SCRIPT>
</JOB>





posted by at 13:13 | WSHのオブジェクト | このブログの読者になる | 更新情報をチェックする


2019年02月20日


VBScript : プリンタ名の一覧


※ 一覧なので、cscript.exe PrinterList.vbs としたほうがいいでしょう。( スクリプトでは、Wscript.exe で実行した場合 コマンドプロンプトを開いて Cscript.exe で実行しなおすようになっています )



item.Name は FolderItem オブジェクトのプロパティです
FolderItem Properties (Windows)
右端のアイコンよりダウンロードできます
Crun

Set objShell = CreateObject("Shell.Application")
Set objFolder = objShell.NameSpace(&H4)
Set colItems = objFolder.Items

For each item in colItems

	if item.Name <> "プリンタの追加" then
		Wscript.Echo item.Name
	end if

Next

' **********************************************************
' Cscript.exe で実行を強制
' Cscript.exe の実行終了後 pause で一時停止
' **********************************************************
Function Crun( )

	Dim str,WshShell

	str = WScript.FullName
	str = Right( str, 11 )
	str = Ucase( str )
	if str <> "CSCRIPT.EXE" then
		str = WScript.ScriptFullName

		Set WshShell = CreateObject( "WScript.Shell" )

		strParam = " "
		For I = 0 to Wscript.Arguments.Count - 1
			if instr(Wscript.Arguments(I), " ") < 1 then
				strParam = strParam & Wscript.Arguments(I) & " "
			else
				strParam = strParam & Dd(Wscript.Arguments(I)) & " "
			end if
		Next
		Call WshShell.Run( "cmd.exe /c cscript.exe " & Dd(str) & strParam & " & pause", 1 )
		WScript.Quit
	end if

End Function
' **********************************************************
' 文字列を " で囲む関数
' **********************************************************
Function Dd( strValue )

	Dd = """" & strValue & """"

End function
※『プリンタの追加』以外のチェックは、Windows10 では必要ありませんでした



posted by at 21:08 | Shell.Application | このブログの読者になる | 更新情報をチェックする


2019年02月19日


VBScript : エクスプローラ ( explorer.exe ) の再起動

目的としては、システムへの変更を作業環境に反映させる為に行います。

例えば、ショートカットのファイルは拡張子 .lnk が付いているのですが、一般的に表示される事はありません。これを表示させるには簡単で、手動でレジストリの コンピューター\HKEY_CLASSES_ROOT\lnkfile の中のエントリである NeverShowExt をAllwaysShowExt に名称変更すると .lnk が表示されるようになります。但し、すぐには反映されないのでエクスプローラを再起動します。するとすぐに反映されようになっています。
右端のアイコンよりダウンロードできます
' **********************************************************
' エクスプローラ(explorer.exe) の再起動
' **********************************************************
strTarget = "explorer.exe"

' 起動用
Set WshShell = CreateObject( "WScript.Shell" )
' WMI用
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")

' いったん終了させます
Set colProcessList = objWMIService.ExecQuery _ 
	("Select * from Win32_Process Where Name = '"&strTarget&"'") 
For Each objProcess in colProcessList
	on error resume next
	' 通常はこれで終了されるはず
	objProcess.Terminate() 
	if Err.Number <> 0 then
		' もし終了できなかった場合の強制終了
		Call WshShell.Run("taskkill /F /PID " & objProcess.ProcessId, 0 ) 
	end if
	on error goto 0
Next 

' 少し待ちます
Wscript.Sleep(500)
' エクスプローラを起動
WshShell.Run( strTarget )






タグ:プロセス WMI
posted by at 20:26 | ツール | このブログの読者になる | 更新情報をチェックする


2019年01月02日


IE11で右クリックからソースの表示で外部エディタを起動する





ieSrcEditor.wsf をエクスプローラから実行すると、ファイルを参照するダイアログが開きます。内部のコードはソースコードのようになっています。(必要な関数等はインターネット上に保存して使用しています)

ここでは、ローカルのファイルを開いてパスを取得する為に、InternetExplorer.Application を使用しています。

アンインストールは、zip 内の uninstall.reg か 以下のテキストを uninstall.reg として shift_jis か Unicode で保存してエクスプローラから実行します。内部は、Microsoft の仕様によるレジストリエントリの削除記述となっています。ですから、実際削除を行うのは、regedit.exe です。
Windows Registry Editor Version 5.00

[-HKEY_CURRENT_USER\SOFTWARE\Microsoft\Internet Explorer\View Source Editor]


ieSrcEditor.wsf
<JOB>
<COMMENT>
************************************************************
 WEB WSH 実行スケルトン
************************************************************
</COMMENT>

<COMMENT>
************************************************************
 外部スクリプト定義
************************************************************
</COMMENT>
<SCRIPT
	language="VBScript"
	src="http://lightbox.in.coocan.jp/laylaClass.vbs">
</SCRIPT>

<SCRIPT language=VBScript>
' 管理者として実行を強制する
Set obj = Wscript.CreateObject("Shell.Application")
if Wscript.Arguments.Count = 0 then
	obj.ShellExecute "wscript.exe", WScript.ScriptFullName & " runas", "", "runas", 1
	Wscript.Quit
end if

' ***********************************************************
' 処理開始
' ***********************************************************
Call laylaFunctionTarget( "http://lightbox.in.coocan.jp/" )
Call laylaLoadFunction( "baseFunction.vbs" )
Call laylaLoadFunction( "wmiReg.vbs" )
Call laylaLoadFunction( "toolFunction.vbs" )

' **********************************************************
' エディタ選択
' **********************************************************
strValue = OpenLocalFileName
if strValue = "" then
	Wscript.Quit
end if

' **********************************************************
' レジストリ
' **********************************************************
strPath = "SOFTWARE\Microsoft\Internet Explorer\View Source Editor\Editor Name"
Call WMIRegCreateKey( HKEY_CURRENT_USER, strPath )
strValue = Dd( strValue )
Call WMIRegSetStringValue( HKEY_CURRENT_USER, strPath, Empty, strValue )

MsgOk( strValue & " を IE のソースエディタとして登録しました" )

Function OpenLocalFileName( )

	Call GetObj( "IEDocument", "InternetExplorer.Application" )
	IEDocument.Navigate( ScriptDir( ) & "\local.htm" )
	IEDocument.document.getElementsByTagName("BODY")(0).innerHTML = "<input id=FilePath type=file>"
	IEDocument.document.getElementById("FilePath").click
	if IEDocument.document.getElementById("FilePath").value = "" then
		OpenLocalFileName = ""
		IEDocument.Quit
		Set IEDocument = Nothing
		Exit Function
	end if

	OpenLocalFileName = IEDocument.document.getElementById("FilePath").value

	IEDocument.Quit
	Set IEDocument = Nothing

End Function
</SCRIPT>
</JOB>






posted by at 19:45 | ツール | このブログの読者になる | 更新情報をチェックする


2018年01月26日


指定したキーでレジストリエディタを開く



レジストリエディタは終了する時に直前に表示していた場所をレジストリに登録するので、事前にその値を変更しておいてから開くとその場所を意図的に開く事ができます。

Windows Vista より保存場所の名前が変わっているので、OS バージョンのチェックが必要となっています。

また、同時に二つのレジストリエディタは実行できないので、既に実行中の場合は終わらせる必要があります。その際表示位置やサイズも記録するには、一度アクティブにする必要があるようなので対応しています。
右端のアイコンよりダウンロードできます
if Wscript.Arguments.Count <> 0 then
	strParam = Wscript.Arguments(0)
else
	strParam = "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft"
end if

' レジストリ書き込み用
Set WshShell = CreateObject( "WScript.Shell" )
' WMI用
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")

' レジストリエディタが最後に開いていたキーの登録を行います
strPath = "Software\Microsoft\Windows\CurrentVersion\Applets\Regedit\LastKey"
if GetOSVersion() >= 6 then
	strRegPath = "コンピューター\" & strParam
else
	strRegPath = "マイ コンピュータ\" & strParam
end if

' 既に regedit が実行中の場合はいったん終了させます
Set colProcessList = objWMIService.ExecQuery _ 
	("Select * from Win32_Process Where Name = 'regedit.exe'") 
For Each objProcess in colProcessList
	' 最後のウインドウの位置とサイズを保存する為の終わらせ方
	WshShell.AppActivate("レジストリ エディタ")
	Wscript.Sleep(500)
	WshShell.SendKeys ("%{F4}")
	Wscript.Sleep(500)
	' 上記終わらせ方が失敗した時の強制終了
	on error resume next
	objProcess.Terminate() 
	on error goto 0
Next 

WshShell.RegWrite "HKCU\" & strPath, strRegPath, "REG_SZ"

' レジストリエディタを起動します
Call WshShell.Run( "regedit.exe" )
' レジストリエディタが終わるまで待つ場合は以下のようにします
' Call WshShell.Run( "regedit.exe", , True )

' **********************************************************
' OS バージョンの取得
' **********************************************************
Function GetOSVersion()

	Dim colTarget,str,aData,I,nTarget

	Set colTarget = objWMIService.ExecQuery( _
		 "select Version from Win32_OperatingSystem" _
	)
	For Each objRow in colTarget
		str = objRow.Version
	Next

	aData = Split( str, "." )
	For I = 0 to Ubound( aData )
		if I > 1 then
			Exit For
		end if
		if I > 0 then
			nTarget = nTarget & "."
		end if
		nTarget = nTarget & aData(I)
	Next

	GetOSVersion = CDbl( nTarget )

End Function


ファイル名を指定して実行から実行するのであれば、以下のように指定します( 最後は開きたいレジストリのパス )
wscript.exe c:\temp\open_reg.vbs HKEY_CURRENT_USER\Software\ODBC\ODBC.INI
※ 二つ目はスクリプトのフルパスです


posted by at 16:36 | ツール | このブログの読者になる | 更新情報をチェックする


2016年03月01日


テキストファイルの一括読み込み

Fso は事前に定義していてもいいですし、引数として渡して使用してもいいですが、このコードでは ErrorMessage と Fso がグローバル変数として関数内で定義されています。
Function GetTextFile( strPath )

	Dim ExecuteString
	Dim objHandle

	ExecuteGlobal "Dim ErrorMessage"

	ExecuteString = "Dim Fso : Set Fso = CreateObject( ""Scripting.FileSystemObject"" )"
	ExecuteGlobal ExecuteString

	ErrorMessage = ""
	on error resume next
	Set objHandle = Fso.OpenTextFile( strPath, 1 )
	if Err.Number <> 0 then
		ErrorMessage = Err.Description
		GetTextFile = ""
	else
		GetTextFile = objHandle.ReadAll
		objHandle.Close
	end if
	on error goto 0

End Function





posted by at 20:58 | 関数 | このブログの読者になる | 更新情報をチェックする


2015年02月16日


URLEncode ( UTF-8 の文字列として全ての文字をパーセントエンコーディングします )

VBScript の内部コードから意図的に UTF-8 のキャラクタセットでテキストを書き込んで、バイナリストリームにコピーして、UTF-8 としてのバイトデータを1バイトづつ読み込んで『パーセントエンコーディング』で表現した文字列に変換しています。

※ UTF-8 として処理した場合、先頭3バイトは BOM なので取り除いています。
REM ***********************************************
REM UTF-8 のバイナリデータを作成して URLエンコード
REM ※ 全ての文字をパーセントエンコーディングします
REM ***********************************************
Function URLEncode(s1,s2, str)

	s1.Open
	s1.Charset = "utf-8"
	REM shift_jis で入力文字を書き込む
	s1.WriteText str
	REM コピーの為にデータポインタを先頭にセット
	s1.Position = 0

	REM バイナリで開く
	s2.Open
 	s2.Type = 1

	REM テキストをバイナリに変換
	s1.CopyTo s2
	s1.Close

	REM 読み込みの為にデータポインタを先頭にセット
	s2.Position = 0

	Dim Buffer : Buffer = ""
	REM BOMを取り去る
	s2.Read(3)
	Do while not s2.EOS
		LineBuffer = s2.Read(16)
 
		For i = 1 to LenB( LineBuffer )
			CWork = MidB(LineBuffer,i,1)
			Cwork = AscB(Cwork)
			Cwork = Hex(Cwork)
			Cwork = Ucase(Cwork)
			if Len(Cwork) <> 1 then
				Buffer = Buffer & "%" & Cwork
			else
				Buffer = Buffer & "%0" & Cwork
			end if
		Next
 
	Loop

	s2.Close

	URLEncode = Buffer

End Function

▼ 呼び出しサンプル
<JOB>
<OBJECT id="s1" progid="ADODB.Stream" />
<OBJECT id="s2" progid="ADODB.Stream" />

<SCRIPT language="VBScript" src="http://winofsql.jp/VBScript/urlencode.vbs"></SCRIPT>

<SCRIPT language="VBScript">

str = "あいうえお"

Wscript.Echo URLEncode(s1,s2, str)

</SCRIPT>
</JOB>

REM を使ったり、条件式の = を使わずに、<> を使っているのは、ExecuteGlobal を使って動的に関数登録する為です。
VBScript では、x = y の解釈が 2 とおりあります。1 つ目は代入ステートメントとして解釈され、y の値が x に代入されます。2 つ目は x と y の値が等しいかどうかをテストする式として解釈されます。等しい場合、result は True です。それ以外の場合、result は False です。ExecuteGlobal ステートメントは常に 1 つ目の解釈を適用し、Eval メソッドは常に 2 つ目の解釈を適用します。
posted by at 17:47 | 関数 | このブログの読者になる | 更新情報をチェックする


2014年07月11日


VBScript で『管理者として実行を強制する』処理

freefont_logo_hkreikk.png
昨今の Windows では、管理者権限が無いと失敗する処理が増えました。これは、バッチで自動化する時には使用できませんが、PC の前に操作員が居るという前提で実行可能です。

この処理は、右クリックで表示されるメニューの中の『管理者として実行』という項目に該当し、本来の英語表示は『runas』であると思われ、スクリプトの Operation"runas" を引き渡すと実現できます。

Shell.ShellExecute method

注意するのは、以下のコードでは VBScript に対して引数がある場合は利用できないと言う事です。引数がある場合はその引数の数に合わせてカスタマイズする必要があります。

ここでは、引数が無いという前提なので、次に実行する場合はダミーで "runas" という引数を渡しています。WScript.ScriptFullName & " runas"wscript.exe に対する引数で、runas が スクリプトに対する引数です。

こうする事によって、2回目の実行は、管理者権限で実行されている状態で、if Wscript.Arguments.Count = 0 then を通り抜ける事になります。

ShellExecute の3番目の引数が省略されていますが、これは作業ディレクトリの指定で、このパラメータを指定しない場合、現在の作業ディレクトリが使用されます。

ShellExecute の5番目引数は、ウインドウの表示方法で、1 は、ノーマル表示を意味します。
' 管理者として実行を強制する
Set obj = Wscript.CreateObject("Shell.Application")
if Wscript.Arguments.Count = 0 then
	obj.ShellExecute "wscript.exe", WScript.ScriptFullName & " runas", "", "runas", 1
	Wscript.Quit
end if

Wscript.Echo WScript.Arguments(0)





タグ:SHELL
posted by at 13:04 | Shell.Application | このブログの読者になる | 更新情報をチェックする


2014年05月29日


WMIのレジストリアクセスで、レジストリエントリの一覧を取得する VBScript クラス

freefont_logo_hkreikk.png
WMI : StdRegProv class
VBScript のクラス : Initialize イベント

Private Sub Class_Initialize は、コンストラクタのような働きをしますが、イベントなので引数を使うコンストラクタを実装する事ができません。また、そもそも同名のメソッドを作成できないので、注意が必要です。

ここでは、デフォルトのメソッドを定義して、メソッド名を指定せずに処理を実行しています。

Set Shell = CreateObject("Shell.Application")
if WScript.Arguments.Count = 0 then
	Shell.ShellExecute "cmd.exe", "/c Cscript.exe """ & Wscript.ScriptFullName & """ dummy & pause", "", "runas", 1
	Wscript.Quit
end if

Dim obj

' ************************************************
' インスタンス作成
' ************************************************
Set obj = new Wmireg

' ************************************************
' デフォルトメソッド実行
' ************************************************
Set list = obj(WMI_HKEY_LOCAL_MACHINE, "SOFTWARE\Microsoft\Windows\CurrentVersion\Run")

' ************************************************
' 一覧表示
' ************************************************
For Each data in list.Keys

	Wscript.Echo data & " : " & list(data)

Next

const WMI_HKEY_CLASSES_ROOT = &H80000000
const WMI_HKEY_CURRENT_USER = &H80000001
const WMI_HKEY_LOCAL_MACHINE = &H80000002
const WMI_HKEY_USERS = &H80000003
const WMI_HKEY_CURRENT_CONFIG = &H80000005

const WMI_REG_SZ = 1 
const WMI_REG_EXPAND_SZ = 2 
const WMI_REG_BINARY = 3 
const WMI_REG_DWORD = 4 
const WMI_REG_MULTI_SZ = 7 

Class Wmireg

	Public objReg 

	' ************************************************
	' Initialize イベント
	' ************************************************
	Private Sub Class_Initialize

		Set objReg = _
			GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & _
			".\root\default:StdRegProv") 

	End Sub

	' ************************************************
	' サブキーの配列を取得
	' ************************************************
	Public Function GetLSubKeyArray( defKey, strPath )

		Dim aSubKeys,str

		objReg.EnumKey defKey, strPath, aSubKeys
		GetLSubKeyArray = aSubKeys
	 
	end function

	' ************************************************
	' 値の一覧の連想配列を取得( 規定のメソッド )
	' ************************************************
	Public Default Function GetLValueArray( defKey, strPath )

		Dim aValueNames, aValueTypes, strValue, aValue

		Set var = CreateObject( "Scripting.Dictionary" )

		objReg.EnumValues defKey, strPath,_ 
			aValueNames, aValueTypes 
		For i=0 To UBound(aValueNames)
			Select Case aValueTypes(i) 
				Case WMI_REG_SZ
					objReg.GetStringValue _
					defKey,strPath,aValueNames(i),strValue
					var(aValueNames(i)) = strValue
				Case WMI_REG_EXPAND_SZ
					objReg.GetExpandedStringValue _
					defKey,strPath,aValueNames(i),strValue
					var(aValueNames(i)) = strValue
				Case WMI_REG_DWORD
					objReg.GetDWORDValue _
					defKey,strPath,aValueNames(i),strValue
					var(aValueNames(i)) = strValue
				Case WMI_REG_MULTI_SZ
					objReg.GetMultiStringValue _
					defKey,strPath,aValueNames(i),aValue
					var(aValueNames(i)) = aValue
				Case WMI_REG_BINARY 
					objReg.GetBinaryValue _
					defKey,strPath,aValueNames(i),aValue
					var(aValueNames(i)) = aValue
			End Select 
		Next 

		Set GetLValueArray = var

	end function

	' ************************************************
	' 文字列セット
	' ************************************************
	Public Function SetLString( defKey, strPath, strName, strValue )

		objReg.SetStringValue _
			defKey,strPath,strName,strValue 

	end function

	' ************************************************
	' 整数セット
	' ************************************************
	Public Function SetLDword( defKey, strPath, strName, dwValue )

		objReg.SetDWORDValue _
			defKey,strPath,strName,dwValue

	end function

End Class



タグ:WMI クラス
posted by at 01:41 | WMI | このブログの読者になる | 更新情報をチェックする


2014年01月09日


BatchHelperオブジェクト(32bit)のインストール

BatchHelper オブジェクトのメソッド等使用方法


インストーラのダウンロード

解凍して、setup.wsf を実行します。
<JOB>
<OBJECT id="WshShell" progid="WScript.Shell" />
<OBJECT id="Fs" progid="Scripting.FileSystemObject" />
<OBJECT id="Shell" progid="Shell.Application" />
<SCRIPT language=VBScript>
' 管理者として実行を強制する
Set obj = Wscript.CreateObject("Shell.Application")
if Wscript.Arguments.Count = 0 then
	obj.ShellExecute "wscript.exe", WScript.ScriptFullName & " runas", "", "runas", 1
	Wscript.Quit
end if

Set obj = GetObject ("winmgmts:\\.\root\cimv2")
Set objTargets = obj.ExecQuery( "select AddressWidth from Win32_Processor" )
Dim str
For Each objTarget in objTargets
	str = objTarget.AddressWidth
Next

strCurPath = WScript.ScriptFullName
Set obj = Fs.GetFile( strCurPath )
Set obj = obj.ParentFolder
strCurPath = obj.Path

Dim Lbox,bLbox,strDir,objExec

Set objFolder = Shell.Namespace( &H25 )
Set objFolderItem = objFolder.Self
strDir = objFolderItem.Path

if str <> "32" then
	strDir = Replace(Ucase(strDir),"SYSTEM32", "SYSWOW64")
end if

Wscript.Echo "インストール先 : " & strDir

on error resume next
' インストールされているかどうか
strValue = WshShell.RegRead("HKCR\Lbox.BatchHelper\CLSID\")
if Err.Number = 0 then
	' 現在の情報でアンインストール
	strValue = "HKCR\CLSID\" & strValue
	strValue = strValue & "\InprocServer32\"
	strValue = WshShell.RegRead(strValue)
	strValue = strDir & "\regsvr32.exe /u /s """ & strValue & """"
	Call WshShell.Run( strValue,,true )
end if
on error goto 0

' カレントファイルをシステムディレクトリにコピー
Call Fs.CopyFile( strCurPath & "\lbox.dll", strDir & "\", True )
Call Fs.CopyFile( strCurPath & "\BatchWsc.wsc", strDir & "\", True )
Call Fs.CopyFile( strCurPath & "\imgctl.dll", strDir & "\", True )
Call Fs.CopyFile( strCurPath & "\SaveJPG.dll", strDir & "\", True )
Call Fs.CopyFile( strCurPath & "\TransG32.dll", strDir & "\", True )

' lbox.dll のインストール
strValue = strDir & "\regsvr32.exe """ & strDir & "\lbox.dll"""
Call WshShell.Run( strValue,,true )

on error resume next
strValue = WshShell.RegRead("HKCR\Lbox.BatchWsc\CLSID\")
if Err.Number = 0 then
	' 現在の情報でアンインストール
	strValue = "HKCR\CLSID\" & strValue
	strValue = strValue & "\ScriptletURL\"
	strValue = WshShell.RegRead(strValue)
	strValue = strDir & "\regsvr32.exe scrobj.dll /s /u /n /i:""" & strValue & """"
	Call WshShell.Run( strValue,,true )
end if
on error goto 0

' BatchWsc.wsc のインストール
strValue = strDir & "\regsvr32.exe scrobj.dll /n /i:file://""" & strDir & "\BatchWsc.wsc" & """"
Call WshShell.Run( strValue,,true )

</SCRIPT>
</JOB>

▼ 以下のようにファイルがシステムディレクトリにコピーされます
' カレントファイルをシステムディレクトリにコピー
Call Fs.CopyFile( strCurPath & "\lbox.dll", strDir & "\", True )
Call Fs.CopyFile( strCurPath & "\BatchWsc.wsc", strDir & "\", True )
Call Fs.CopyFile( strCurPath & "\imgctl.dll", strDir & "\", True )
Call Fs.CopyFile( strCurPath & "\SaveJPG.dll", strDir & "\", True )
Call Fs.CopyFile( strCurPath & "\TransG32.dll", strDir & "\", True )

アンインストールは、uninstall.wsf を実行して下さい。( レジストリの情報を削除します )

以下は、ファイルを開くダイアログの使用例です( 単一ファイルと複数選択 )
Set obj = GetObject ("winmgmts:\\.\root\cimv2")
Set objTargets = obj.ExecQuery( "select AddressWidth from Win32_Processor" )
Dim str
For Each objTarget in objTargets
	str = objTarget.AddressWidth
Next

if str <> "32" then
	str = WScript.FullName
	str = Right( str, 11 )
	str = Ucase( str )
	if str <> "CSCRIPT.EXE" then
		str = WScript.ScriptFullName
		Set WshShell = Wscript.CreateObject("WScript.Shell")
		strParam = " "
		For I = 0 to Wscript.Arguments.Count - 1
			if instr(Wscript.Arguments(I), " ") < 1 then
				strParam = strParam & Wscript.Arguments(I) & " "
			else
				strParam = strParam & """" & Wscript.Arguments(I) & """ "
			end if
		Next
		Call WshShell.Run( "c:\windows\SYSWOW64\cmd.exe /c c:\windows\SYSWOW64\cscript.exe """ & str & """" & strParam & " & pause", 3 )
		WScript.Quit
	end if
end if

Set BatchHelper = Wscript.CreateObject( "Lbox.BatchHelper" )

' 単一ファイルの選択
Path = BatchHelper.OpenFileName( _
	"ファイルを開く", _
	"テキスト,*.txt,ログ,*.log,全て,*.*", _
	"C:\Windows\Microsoft.NET\Framework" )

' キャンセルは、空文字が返されます
if Path <> "" then
	BatchHelper.MsgOk( "ファイルが選択されました : " & vbCrLf & Path )
end if

' 複数ファイルの選択
Path = BatchHelper.OpenFileNames( _
	"複数ファイルの選択", _
	"テキスト,*.txt,ログ,*.log,全て,*.*", _
	"C:\Windows\Microsoft.NET\Framework" )

' キャンセルは、空文字が返されます
if Path <> "" then
	BatchHelper.MsgOk( "ファイルが選択されました : " & vbCrLf & Path )

	' 複数のファイルのパスは、TABコードで分割されます
	aData = Split(Path, vbTab)
	BatchHelper.MsgOk("/" & aData(0) & "/")
end if




posted by at 18:18 | BatchHelper | このブログの読者になる | 更新情報をチェックする


2013年12月05日


VBScript で標準的に「ファイルを開く」ダイアログを利用する唯一の方法

フォーカス(アクティブ)の問題とか、一般にファイルの種類は指定できないので不完全ではありますが、自分でアプリケーションを作成せずに利用する事ができます。

元々、ファイルのアップロードのみに使われるものですからそのような目的でしか利用する事はできません( ファイルの保存用はありません )

' 管理者として実行を強制する
Set obj = Wscript.CreateObject("Shell.Application")
if Wscript.Arguments.Count = 0 then
	obj.ShellExecute "wscript.exe", WScript.ScriptFullName & " runas", "", "runas", 1
	Wscript.Quit
end if

Function OpenLocalFileName( )

	' ファイルシステムを操作するオブジェクト
	Set Fso = WScript.CreateObject( "Scripting.FileSystemObject" )
	' テンポラリフォルダ
	TempDir =  Fso.GetSpecialFolder(2)
	on error resume next
	' テンポラリフォルダに空の "local.htm" を作成
	Set objHandle = Fso.CreateTextFile( TempDir & "\local.htm", True, True )
	if Err.Number <> 0 then
		Exit Function
	end if
	objHandle.Close
	on error goto 0

	' IE を操作するオブジェクト
	Set IEDocument = WScript.CreateObject( "InternetExplorer.Application" )
	' テンポラリフォルダに作成したファイルを開く
	IEDocument.Navigate( TempDir & "\local.htm" )
	' 『ファイルを開く』為のコンテンツを作成
	IEDocument.document.getElementsByTagName("BODY")(0).innerHTML = "<input id=FilePath type=file>"
	' 『ファイルを開く』為に、ボタンをクリックする
	IEDocument.document.getElementById("FilePath").click
	' ファイルを選択していない場合は終了
	if IEDocument.document.getElementById("FilePath").value = "" then
		OpenLocalFileName = ""
		IEDocument.Quit
		Set IEDocument = Nothing
		Exit Function
	end if

	' 選択したファイルのパスを戻す
	OpenLocalFileName = IEDocument.document.getElementById("FilePath").value

	' IE を終了
	IEDocument.Quit
	Set IEDocument = Nothing

End Function


' 呼び出し
strValue = OpenLocalFileName
if strValue = "" then
	Wscript.Quit
end if

' 選択したファイルを表示
Wscript.Echo strValue

昔はセキュリティが甘かったので、ローカルファイルでは無く about:blank で処理できていたのですが、今はインターネットオプションの『サーバーにファイルをアップロードするときにローカル ディレクトリのパスを含める』を有効にしないと、fakepath というパスのみが返るようになっています。それを回避する為にローカルのファイルを使うようにしていますが、その際に管理者権限でないと動作しないので、『管理者として実行を強制』しています

※ UserAccounts.CommonDialog は、XPのみで利用できます


BatchHelper オブジェクト をインストールすると以下が使用できます

【 OpenFileName 】
Path = BatchHelper.OpenFileName( [Title], [Filter], [DefaultDir], [DefaultExt], [DefaultName] )

コモンダイアログでファイルのパスを取得します 

Title (省略可): ダイアログのタイトル
Filter (省略可): フィルターリスト ( 例: "CSV,*.csv,全て,*.*" )
DefaultDir (省略可): 初期ディレクトリ
DefaultExt (省略可): デフォルトの拡張子
DefaultName (省略可): デフォルトのファイル名 

キャンセル時、Path は "" (空文字列) になります

▼ 実行ソースコードサンプル
Set BatchHelper = Wscript.CreateObject("Lbox.BatchHelper")

Path = BatchHelper.OpenFileName( )

Wscript.Echo Path




posted by at 00:01 | その他 | このブログの読者になる | 更新情報をチェックする


2013年11月28日


文字列連結では無く、配列を利用した VBScript のクラス

そもそも、VBScript のクラスが珍しいですが、ExecuteGlobal や、ReDim Preserve は、VBScript のテクニックとしてとても重要なステートメントです。実際大量に文字列連結すると、大きくなるほどハフォーマンスが落ちます。しかし、ReDim では単純なメモリの増量のようなので( C++ レベルではそんなに単純でも無いでしょうけれど )かなり高速に動作するはずです。

もっと複雑な処理では、Dictionary オブジェクトを使用すればいいとおもいますが、文字列を作成して処理するだけなら( 例えば HTA における HTML 作成 )こちらのほうが便利です。
Set MyBuffer = CreateBuff

Wscript.Echo MyBuffer.Length

MyBuffer.SetData("001")

Wscript.Echo MyBuffer.Length

MyBuffer.SetData("日本語表示")
MyBuffer.SetData("XYZ")

Wscript.Echo MyBuffer.Length

' 内部配列の直接参照
Wscript.Echo MyBuffer.Buff(1)
MyBuffer.Buff(1) = "日本語"

' 改行コードで連結した内部配列
Wscript.Echo MyBuffer.GetData(vbCrLf)

' カンマで連結した内部配列
Wscript.Echo MyBuffer.GetData(",")


Class buffCon

	Public Buff()

	' ************************************************
	' コンストラクタ
	' ************************************************
	Public Default Function InitSetting()

		Redim Buff(0)

	end function

	' ************************************************
	' メソッド ( データセット )
	' ************************************************
	function Length()

		if IsEmpty( Buff(0) ) then
			Length = 0
		else
			Length =  Ubound(Buff)+1
		end if

	end function

	' ************************************************
	' メソッド ( データセット )
	' ************************************************
	function SetData( strRow )

		if IsEmpty( Buff(0) ) then
			Buff(0) = strRow
		else
			ReDim Preserve Buff(Ubound(Buff)+1)
			Buff(Ubound(Buff)) = strRow
		end if

	end function
	 
	' ************************************************
	' メソッド ( データ取得 )
	' ************************************************
	function GetData( strDelim )

		GetData = Join( Buff, strDelim )

	end function

End Class

' **********************************************************
' バッファ作成
' **********************************************************
Function CreateBuff( )

	ExecuteString = "Dim gblCreateBuff : "
	ExecuteString = ExecuteString & "Set gblCreateBuff = new buffCon"
	ExecuteGlobal ExecuteString
	Call gblCreateBuff

	Set CreateBuff = gblCreateBuff

End Function




posted by at 23:16 | サンプル | このブログの読者になる | 更新情報をチェックする


2013年11月27日


管理者として実行を強制し、ANHTTPD を実行し、MySQLサービスを起動し、 エクスプローラで ANHTTPD のディレクトリを開け、ブラウザで、ANHTTPD の仮想ディレクトリを開くスクリプト

昔、『開発始めますよスクリプト』と読んでいました。当時は、管理者で実行とか必要なかったですが、今はたぶんサービスの実行で権限を求められると思います。
' 管理者として実行を強制する
Set obj = Wscript.CreateObject("Shell.Application")
if Wscript.Arguments.Count = 0 then
	obj.ShellExecute "wscript.exe", WScript.ScriptFullName & " runas", "", "runas", 1
	Wscript.Quit
end if

' MySQL サービスの表示名(DisplayName)
Dim MySQL_Name : MySQL_Name = "MySQL56"
' ANHTTPD のインストールディレクトリ
Dim Httpd_Path : Httpd_Path = "c:\httpd142p"
' ANHTTPD の常に使う仮想パス
Dim Httpd_VPath : Httpd_VPath = "http://localhost"
' ブラウザのパス
Dim Browser_Path : Browser_Path = "C:\Program Files\Google\Chrome\Application\chrome.exe"


' **********************************************************
' アプリケーション起動用
' **********************************************************
Set WshShell = Wscript.CreateObject( "WScript.Shell" )

' **********************************************************
' プロセス( httpd.exe ) を開始
' **********************************************************
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colProcesses = objWMIService.ExecQuery("Select * from Win32_Process Where Name = 'httpd.exe'") 
flg = false
For Each objProcess in colProcesses 
	flg = true
Next
if Not flg then
	WshShell.CurrentDirectory = Httpd_Path
	WshShell.Run( "httpd.exe" )
end if

' **********************************************************
' サービス( MySQL )
' **********************************************************
Set colRunningServices = objWMIService.ExecQuery("Select * from Win32_Service Where DisplayName = '" & MySQL_Name & "'") 
For Each objService in colRunningServices 
	if objService.State = "Stopped" then
		objService.StartService()
	end if
Next 

' **********************************************************
' ANHTTPD のインストールディレクトリをエクスプローラで開く
' **********************************************************
str = "explorer.exe /e," & Httpd_Path
WshShell.Run( str )


' **********************************************************
' ANHTTPD の常に使う仮想パス Google Chrome 
' **********************************************************
str = """" & Browser_Path & """"  & Httpd_VPath
WshShell.Run( str )



posted by at 05:36 | ツール | このブログの読者になる | 更新情報をチェックする


2013年11月21日


IE拡張 : テキストエリア入力拡張





テキストエリアの内容を転送して、簡単な拡張編集ができます。( 簡易的なプレビューも可能です )

▼ IE に登録された画面を伴うコード部分
<meta http-equiv="content-type" content="text/html; charset=SHIFT_JIS">
<SCRIPT language="VBScript">
	Dim WshShell,RegName,strLocation,obj,doc,Fs
	Dim nFirstLen,objFirstTextRange,BakPath,bMax

	bMax = False

	Set WshShell = CreateObject("WScript.Shell")
	Set Fs = CreateObject( "Scripting.FileSystemObject" )

	RegName = "−【テキストエリア入力拡張】"

	BakPath = "C:\laylaClass\menuex"

	' *************************************************
	' ウインドウサイズ
	' *************************************************
	window.dialogWidth = "900px"
	window.dialogHeight = "610px"

'	window.dialogTop = "100px"
'	window.dialogLeft = (window.screen.width/2)&"px"

	on error resume next
	ExecuteGlobal "function dummy(): end function"
	on error goto 0

Function setObj( src )
	Set obj = src
End Function
</SCRIPT>

<SCRIPT language="JavaScript">
setObj(external.menuArguments.event.srcElement);
var shift_key;
var ctrl_key;

function easyPreview() {

	document.getElementById("preview").style.display = '';
	document.getElementById("text").style.height = '330px';
	document.getElementById("preclose").style.display = '';

	if ( bMax ) {
		
		document.getElementById("preview").style.height = (window.screen.height - 450) + "px";
	}

	var target = document.getElementById("preview").contentWindow.document;
	target.open;

	var str="";
str+="<style type=\"text/css\"> \n";
str+="* { \n";
str+="	font-size:12px; \n";
str+="} \n";
str+="</style> ";
	target.write(str);
str="";
str+="<"+"script type=\"text/javascript\"> \n";
str+="window.onerror = function() { \n";
str+="	return true; \n";
str+="} \n";
str+="</"+"script> ";
	target.write(str);

	if ( event.shiftKey ) {
		target.write("<pre>\n");
	}

	var cnvtext,cnvarr;

	if ( event.ctrlKey ) {
		cnvtext = document.getElementById("text").value;
		if ( event.shiftKey ) {
			cnvarr = cnvtext.match(/(https?|ftp)(:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]+)/g );
			cnvtext = "";
			for( i = 0; i < cnvarr.length; i++ ) {
				cnvtext += "<a href=" + cnvarr[i] + " target='_blank'>" + cnvarr[i] + "</a>\n";
			}
		}
		else {
			cnvtext = cnvtext.replace(/&/g, "&amp;" );
			cnvtext = cnvtext.replace(/</g, "&lt;" );
			cnvtext = cnvtext.replace(/>/g, "&gt;" );
			cnvtext = cnvtext.replace(/(https?|ftp)(:\/\/[-_.!~*\'()a-zA-Z0-9;\/?:\@&=+\$,%#]+)/g, "<a href='$1$2' target='_blank'>$1$2</a>" );
		}
	}
	else {
		cnvtext = document.getElementById("text").value;
	}

	target.write(cnvtext);

	if ( event.shiftKey ) {
		target.write("</pre>\n");
	}

	target.close();

}

function closePreview() {

	document.getElementById("preview").style.display="none";
	document.getElementById("preclose").style.display="none";
	document.getElementById("text").style.height = '550px';

	if ( bMax ) {
		document.getElementById("text").style.height = (window.screen.height - 120) + "px"
	}

}


function createURLLink() {

	var txt = "";
	var strUrl = "";
	var strTarget = "";

	var shift_key_local = event.shiftKey;

	var objSelectedText = document.selection
	var objTextRange = objSelectedText.createRange( )

	if (objTextRange.text.length == 0 ) {
		return;
	}
	try {
		if ( shift_key_local ) {
			strTarget = "_self"
		}
		else {
			strTarget = "_blank"
		}
		strUrl = external.menuArguments.prompt("URLリンク作成( " + strTarget + " )","http://");
		if ( strUrl != "" && strUrl != "http://" && strUrl+"" != "null" ) {
			txt = objTextRange.text
			txt = "<a href=\""+strUrl+"\" target=\"" + strTarget + "\">"+txt+"</a>"
			objTextRange.text = txt;
		}
	}catch( e ){}

}

function createIFrame() {

	document.getElementById("text").focus();
	setTimeout("createIFrameCore()", 100 );
}
function createIFrameCore() {

	var txt = "";
	var strUrl = "";
	var str;

	var objSelectedText = document.selection
	var objTextRange = objSelectedText.createRange( )

	if (objTextRange.text.length == 0 ) {
		try {
			strUrl = external.menuArguments.prompt("IFRAME作成","http://");
			if ( strUrl != "" && strUrl != "http://" && strUrl+"" != "null" ) {
				str="";
				str+="<"+"iframe \n";
				str+="	src=\""+strUrl+"\" \n";
				str+="	name=\"myframe\" \n";
				str+="	frameborder=\"no\" \n";
				str+="	scrolling=\"no\" \n";
				str+="	width=\"600\" \n";
				str+="	height=\"480\" \n";
				str+="></"+"iframe> \n";
				objTextRange.text = str;
			}
		}catch( e ){ }
	}
}

function createBold() {

	document.getElementById("text").focus();
	setTimeout("createBoldCore()", 100 );
}
function createBoldCore() {

	var txt = "";
	var strUrl = "";

	var objSelectedText = document.selection
	var objTextRange = objSelectedText.createRange( )

	if (objTextRange.text.length == 0 ) {
		try {
			objTextRange.text = "<b></b>";
		}catch( e ){}
		return;
	}
	try {
		txt = objTextRange.text;
		txt = "<b>"+txt+"</b>";
		objTextRange.text = txt;
	}catch( e ){}

}
function createTable() {

	document.getElementById("text").focus();
	setTimeout("createTableCore()", 100 );
}
function createTableCore() {

	var txt = "";
	var strUrl = "";

	var str1,str2;
str1="";
str1+="<table>\n";
str1+="<tr>\n";
str1+="<td>\n";
str1+="<!-- (left) -->\n";
str2="";
str2+=" \n";
str2+="</td> \n";
str2+="<td>\n";
str2+="<!-- (right) -->\n";
str2+="</td>\n";
str2+="</tr>\n";
str2+="</table>\n";

	var objSelectedText = document.selection
	var objTextRange = objSelectedText.createRange( )

	if (objTextRange.text.length == 0 ) {
		try {
			objTextRange.text = str1+str2;
		}catch( e ){}
		return;
	}
	try {
		txt = objTextRange.text;
		txt = str1+txt+str2;
		objTextRange.text = txt;
	}catch( e ){}

}
function convertHtml() {

	var txt = "";
	var strUrl = "";

	var objSelectedText = document.selection
	var objTextRange = objSelectedText.createRange( )

	if (objTextRange.text.length == 0 ) {
		return;
	}
	try {
		txt = objTextRange.text
		txt = txt.replace(/&/g, "&amp;" );
		txt = txt.replace(/</g, "&lt;" );
		txt = txt.replace(/>/g, "&gt;" );
		objTextRange.text = txt;
	}catch( e ){}

}
function decodeHtml() {

	var txt = "";
	var strUrl = "";

	var objSelectedText = document.selection
	var objTextRange = objSelectedText.createRange( )

	if (objTextRange.text.length == 0 ) {
		return;
	}
	try {
		txt = objTextRange.text
		txt = txt.replace(/&lt;/g, "<" );
		txt = txt.replace(/&gt;/g, ">" );
		txt = txt.replace(/&amp;/g,'&')
		objTextRange.text = txt;
	}catch( e ){}

}

function removeSpace() {

	var txt = "";
	var strUrl = "";

	var objSelectedText = document.selection
	var objTextRange = objSelectedText.createRange( )

	if (objTextRange.text.length == 0 ) {
		return;
	}
	try {
		txt = objTextRange.text
		txt = txt.replace(/\s+/g, " " );
		objTextRange.text = txt;
	}catch( e ){}

}


function insertPre() {


	shift_key = false
	if ( event.shiftKey ) {
		shift_key = true
	}
	document.getElementById("text").focus();
	setTimeout("insertPreCore()", 100 );
}
function insertPreCore() {

	var txt = "";

	var objSelectedText = document.selection
	var objTextRange = objSelectedText.createRange( )

	if (objTextRange.text.length == 0 ) {
		try {
			if ( shift_key ) {
				objTextRange.text = "<"+"script type=\"text/javascript\">\n\n\n</"+"script>\n";
			}
			else {
				objTextRange.text = "<pre>\n\n\n</pre>\n";
			}
		}catch( e ){}
	}
	else {
		try {
			txt = objTextRange.text
			if ( shift_key ) {
				txt = "<"+"script type=\"text/javascript\">\n"+txt+"\n</"+"script>\n"
			}
			else {
				txt = "<pre>\n"+txt+"\n</pre>"
			}
			objTextRange.text = txt;
		}catch( e ){}
	}

}

function insertBr() {

	document.getElementById("text").focus();
	setTimeout("insertBrCore()", 100 );
}
function insertBrCore() {

	var objSelectedText = document.selection
	var objTextRange = objSelectedText.createRange( )

	if (objTextRange.text.length == 0 ) {
		try {
			objTextRange.text = "<br />\n";
		}catch( e ){}
	}

}

function insertStyle() {

	shift_key = false;
	ctrl_key = false;
	if ( event.shiftKey ) {
		shift_key = true;
	}
	if ( event.ctrlKey ) {
		ctrl_key = true;
	}
	document.getElementById("text").focus();
	setTimeout("insertStyleCore()", 100 );
}
function insertStyleCore() {

	var objSelectedText = document.selection
	var objTextRange = objSelectedText.createRange( )

	if (objTextRange.text.length == 0 ) {
		try {
			if ( shift_key ) {
				objTextRange.text = " style='color:#0000ff'";
			}
			else {
				if ( ctrl_key ) {
					objTextRange.text = " style='color:#228b22'";
				}
				else {
					objTextRange.text = " style='color:#ff0000'";
				}
			}
		}catch( e ){}
	}

}

</SCRIPT>
<html>
<head>
<title>−【テキストエリア入力拡張】</title>
<meta http-equiv="content-type" content="text/html; charset=SHIFT_JIS">
<STYLE type="text/css">
* {
	font-size:12px;
}
body {
	margin:0;
	background-color:#C5D1A5;
}
</STYLE>

<SCRIPT language="VBScript">

' 関数定義用
Function ReturnText()

	if Not confirm( "データを転送しますか?   " ) then
		Exit Function
	end if

	if UCase( obj.tagName ) = "TEXTAREA" then
		if nFirstLen <> 0 then
			objFirstTextRange.text = document.getElementById("text").value
		else
			obj.value = document.getElementById("text").value
		end if
	end if

	if UCase( obj.tagName ) = "INPUT" then
		if UCase( obj.type ) = "TEXT" then
			if nFirstLen <> 0 then
				objFirstTextRange.text = document.getElementById("text").value
			else
				obj.value = document.getElementById("text").value
			end if
		end if
	end if

	on error resume next
	Set OutObj = Fs.OpenTextFile( BakPath & "\TextareaEx.bak", 2, True )
	OutObj.Write document.getElementById("text").value & ""
	OutObj.Close
	on error goto 0

	window.close()

End Function

function SetTab( )

	if window.event.keyCode <> 9 then
		exit function
	end if

	window.event.returnValue = false

	Dim objTextArea,objTextRange,nLen,nChars,strData

	set objTextArea = document.selection
	set objTextRange = objTextArea.createRange( )
	on error resume next
	strData = objTextRange.text
	nLen = Len( strData )
	if window.event.shiftKey then
		strData = Replace( strData, vbLf & vbTab, vbLf )
		if Left( strData, 1 ) = vbTab then
			strData = Right( strData, Len( strData ) - 1 )
		end if
	else
		strData = Replace( strData, vbLf, vbLf & vbTab )
		strData = vbTab & strData
	end if

	if nLen = 0 then
		objTextRange.text = strData
	else
		objTextRange.text = strData & vbLf
	end if

	on error goto 0

end function 

Function CursorTop()

	document.getElementById("text").focus()
	Set objFocus = document.getElementById("text").createTextRange()
	Call objFocus.collapse(True)

End Function


Dim objFocus
' **********************************************************
' サーチ
' **********************************************************
function TextSearch()

	if Trim(document.getElementById("search").value&"") = "" then
		Exit Function
	end if

	Dim objTextArea,objTextRange
	Set objTextArea = document.selection
	Set objTextRange = objTextArea.createRange( )

	if objTextRange.text = "" then
		Set objFocus = document.getElementById("text").createTextRange()
		if objFocus.findText( document.getElementById("search").value ) then
			objFocus.select()
		end if
	else
		objFocus.collapse( false )
		if objFocus.findText( document.getElementById("search").value ) then
			objFocus.select()
		end if
	end if

End Function

Function keyCheck(  )
	if window.event.keyCode = 27 then
		Call closePreview()
	end if

End Function

Function maxWindow()

	window.dialogLeft = "0"
	window.dialogTop = "0"
	window.dialogWidth = (window.screen.width-5) & "px"
	window.dialogHeight = (window.screen.height - 70) & "px"
	bMax = True
	document.getElementById("text").style.height = (window.screen.height - 120) & "px"
	document.getElementById("maxw").style.display = "none"

End Function
</SCRIPT>
<base target="_self">
</head>
<BODY onKeydown='keyCheck()'>
<INPUT
	id="retbutton"
	type="button"
	value="戻す"
	onClick="Call ReturnText()"
>
<INPUT
	id="search"
	type="text"
>
<INPUT
	type="button"
	value="検索"
	onClick="Call TextSearch()"
>
折り返さない <input
	type="checkbox"
	onClick='if me.checked then document.getElementById("text").wrap="off" else document.getElementById("text").wrap="soft" end if'
>
&nbsp;&nbsp;&nbsp;&nbsp;
<input type=button value="リンク" language="javascript" onClick='createURLLink()'
	onMouseover='document.getElementById("message").value = "選択部分に対してURLを入力してリンクを作成します ( そのままクリックすると _blank で作成。SHIFTキーを押しながら開くと _self で作成)"'
	onMouseout='document.getElementById("message").value = ""'
>
<input type=button value="pre" language="javascript" onClick='insertPre()'>
<input type=button value="bold" language="javascript" onClick='createBold()'>
<input type=button value="table" language="javascript" onClick='createTable()'>
 / <input type=button value="色" language="javascript" onClick='insertStyle()'
	onMouseover='document.getElementById("message").value = "通常 : 赤、SHIFTキー : 青、CTRLキー : 緑"'
	onMouseout='document.getElementById("message").value = ""'
>
<input type=button value="br" language="javascript" onClick='insertBr()'>
<input type=button value="iframe" language="javascript" onClick='createIFrame()'
	onMouseover='document.getElementById("message").value = "IFRAME を挿入します"'
	onMouseout='document.getElementById("message").value = ""'
>
 / <input type=button value="&amp;lt;" language="javascript" onClick='convertHtml()'>
<input type=button value="HTML" language="javascript" onClick='decodeHtml()'>
<input type=button value="改行削除" language="javascript" onClick='removeSpace()'
	onMouseover='document.getElementById("message").value = "選択した文字列を、replace(/\s+/g, \" \" ) で置き換えます"'
	onMouseout='document.getElementById("message").value = ""'
>
 / <input type=button value="プレビュー" language="javascript" onClick='easyPreview()'
	onMouseover='document.getElementById("message").value = "SHIFT : PRE 要素内にセット、CTRL : URL 部分のみリンク変換、CTRL+SHIFT : URL部分のみ取り出してリンク変換"'
	onMouseout='document.getElementById("message").value = ""'
>

&nbsp;&nbsp;&nbsp;&nbsp;<INPUT style='' type="button" id="maxw" value="最大化" onClick='maxWindow()' >

<br>
<TEXTAREA
	id="text"
	name="text"
	style='width:100%;height:550px;'
	onKeydown='Call SetTab()'
></TEXTAREA>
<IFRAME
	id="preview"
	frameborder="yes"
	scrolling="yes"
	width="100%"
	height="205"
	style='display:none'
></IFRAME>
<INPUT style='display:none;float:right;' type="button" id="preclose" value="プレビュー結果を閉じる" onClick='closePreview()' >
<INPUT id="message" type=text style='border:none 0px #000000;width:700px;background-color:#C5D1A5' />

</BODY>
</html>
<SCRIPT for=window event=onload language="VBScript">

' onload 処理
Set doc = obj.document

set objTextArea = doc.selection
set objFirstTextRange = objTextArea.createRange( )
on error resume next
strData = objFirstTextRange.text
nFirstLen = Len( strData )
on error goto 0

if nFirstLen <> 0 then
	document.getElementById("text").value = strData
else
	strTag = obj.tagName
	if UCase( strTag ) = "A" then
		strWork = obj.innerText
		strWork = strWork & vbCrLf & obj.href
		document.getElementById("text").value = strWork
	else
		if UCase( obj.tagName ) = "TEXTAREA" then
			document.getElementById("text").value = obj.innerText
			strCommand = "document.getElementById(""text"").scrollTop = 0"
			Call window.setTimeout( strCommand, 100 )
			Call window.setTimeout( "Call CursorTop()", 500 )
		else
			if UCase( obj.tagName ) = "INPUT" then
				if UCase( obj.type ) = "TEXT" then
					document.getElementById("text").value = obj.value
				end if
			else
				document.getElementById("text").value = obj.innerHTML
			end if
		end if
	end if
end if

</SCRIPT>

関連する記事

Seesaa のカテゴリをソート(通常と逆順と記事が多い順)する VBScript で記述された IE 拡張


posted by at 21:07 | IE拡張 | このブログの読者になる | 更新情報をチェックする



Seesaa のカテゴリをソート(通常と逆順と記事が多い順)する VBScript で記述された IE 拡張





インストール場所は、通常 C:\laylaClass\menuex となります。 アンインストールは、アンインストール用のスクリプトを実行した後、C:\laylaClass\menuex\Seesaa_catsort.htm を削除して下さい。他のインストールされたファイルが無い場合は、C:\laylaClass\menuex も削除して下さい。

インストール









インストール用ソースコード
( ie_Seesaa_catsort_120417.wsf )
<JOB>
<COMMENT>
************************************************************
IE 拡張メニューインストーラ

■ Seesaa 用カテゴリソート

■著作権その他

このプログラムはフリーです。どうぞ自由に御使用ください。
著作権は作者である私(lightbox)が保有しています。
また、本ソフトを運用した結果については、作者は一切責任を
負えせんのでご了承ください。
************************************************************
</COMMENT>

<SCRIPT
	language="VBScript"
	src="http://lightbox.in.coocan.jp/laylaClass.vbs">
</SCRIPT>

<SCRIPT language=VBScript>
' ***********************************************************
' 処理開始
' ***********************************************************
Call laylaFunctionTarget( "http://lightbox.in.coocan.jp/" )
Call laylaLoadFunction( "baseFunction.vbs" )



' //////////////////////////////////////////////////////////
' インストール時の表示名
strProgName	= "Seesaa 用カテゴリソート"
' インストールファイル名( 拡張子は .htm となる )
strProgFile	= "Seesaa_catsort"
' メニューとウインドウのタイトルに表示する文字列
' レジストリに登録するのでユニークである必要があります
strRegName	= "Seesaa 用カテゴリソート"
' 対象となるコンンテンツ
nTargetType 	= &H4
' &H3F : UNKNOWNを除く全て
' &H1  : DEFAULT
' &H2  : IMAGE
' &H4  : CONTROL
' &H8  : TABLE
' &H10 : TEXTSELECT
' &H20 : ANCHOR
' &H40 : UNKNOWN

' 画面ありかどうか
bIsGUI = False
' //////////////////////////////////////////////////////////

print strProgName & " をインストールします"
if not OkCancel( "インストールしてもよろしいですか?" ) then
	Wscript.Quit
end if

' ファイルシステムオブジェクト作成
GetFso

strInstallPath1 = "c:\laylaClass"
strInstallPath2 = "c:\laylaClass\menuex"
strInstallPath3 = "c:\laylaClass\menuex\" & strProgFile & ".htm"
on error resume next
if not Fso.FolderExists( strInstallPath1 ) then
	Call Fso.CreateFolder( strInstallPath1 )
	if Err.Number <> 0 then
		ErrorFlg = True
	end if
end if
if not Fso.FolderExists( strInstallPath2 ) then
	Call Fso.CreateFolder( strInstallPath2 )
	if Err.Number <> 0 then
		ErrorFlg = True
	end if
end if
on error goto 0

Call PutTextFile( strInstallPath3, _
Replace(GetInline("MenuExt"),"$REGNAME", strRegName ) )

' レジストリ処理用オブジェクト作成
GetWshShell

on error resume next
WshShell.RegWrite _
	"HKCU\Software\Microsoft\Internet Explorer\MenuExt\"&strRegName&"\", _
	strInstallPath3, _
	"REG_SZ"
WshShell.RegWrite _
	"HKCU\Software\Microsoft\Internet Explorer\MenuExt\"&strRegName&"\Contexts", _
	nTargetType, _
	"REG_DWORD"

if bIsGUI then
	' この定義があると、画面あり
	WshShell.RegWrite _
	"HKCU\Software\Microsoft\Internet Explorer\MenuExt\"&strRegName&"\Flags", _
	&H1, _
	"REG_DWORD"
end if
on error goto 0

print "処理が終了しました"

Wscript.Quit

</SCRIPT>

<COMMENT>
******** ここからがコード ********
</COMMENT>
<RESOURCE id="MenuExt">
<![CDATA[
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=SHIFT_JIS">
<title>$REGNAME</title>
<script language="VBScript">

	Dim RegName,obj,doc,win

	RegName = "Seesaa 用カテゴリソート"

	' SHIFTとCTRL用変数
	Dim keyflg1,keyflg2
	keyflg1 = False
	keyflg2 = False

Function setObj( src )
	Set obj = src
End Function
</script>
<script language="JavaScript">
setObj(external.menuArguments.event.srcElement);
</script>
<base target="_self">
</head>
<body>
<input id="btn" type=button onClick='keyflg1=window.event.shiftKey:keyflg2=window.event.ctrlKey'>
<script language="VBScript">

	' ボタンの呼び出し
	document.getElementById("btn").click()

	' ADO 用の定数
	Const adVarChar = 130	' Null で終了する Unicode 文字列
	Const adInteger = 3	' 4 バイトの符号付き整数

	' IEが表示しているページの document オブジェクト
	Set doc = external.menuArguments.document
	' IEが表示しているページの window オブジェクト
	Set win = external.menuArguments

	Dim colTable,objTable
	Dim colInput,colNum

	Set colInput = Nothing

	' テーブル要素の一覧
	Set colTable = doc.getElementsByTagName("TABLE")
	For Each objTable In colTable
		' カテゴリ一覧テーブルの選択
		if objTable.className = "entrytable" then
			Set colInput = objTable.getElementsByTagName("A")
			Set colINum = objTable.getElementsByTagName("INPUT")
			Exit For
		end if
	Next

	Dim Rs,nCount,nMax,I,aData()

	' colInput は、対象テーブル内の A オブジェクト
	if Not colInput is Nothing then

		' A の数
		nCount = colInput.length
		' 仕様上2つで一行
		nMax = nCount / 2

		' ソート用レコードセット作成
		Set Rs = CreateObject("ADODB.Recordset")
		' メモリテーブルを作成
		' CTRL( 数値ソート )
		if keyflg2 then
			Rs.Fields.Append "ソートキー", adInteger
		' それ以外はカテゴリ名による文字列ソート
		else
			Rs.Fields.Append "ソートキー", adVarChar,255
		end if
		Rs.Fields.Append "順序", adInteger
		Rs.Open

		' データ保存
		For I = 0 to nMax - 1
			' 行追加
			Rs.AddNew
			' CTRL
			if keyflg2 then
				Rs.Fields("ソートキー").Value = Cint(colInput(I*2+1).firstChild.nodeValue)
			' カテゴリ名による文字列ソート
			else
				Rs.Fields("ソートキー").Value = colInput(I*2).firstChild.nodeValue
			end if
			Rs.Fields("順序").Value = I
			Rs.Update

		Next

		' ソート指定
		if keyflg1 or keyflg2 then
			' 逆ソート
			Rs.Sort = "ソートキー desc"
		else
			Rs.Sort = "ソートキー"
		end if

		' ポインタを先頭に移動
		Rs.MoveFirst

		' 配列を現在必要な数で動的作成
		ReDim aData(nMax)

		' 元の順序に現在の 順序x10+100 を設定
		I = 0
		Do while not Rs.EOF

			aData(Rs.Fields("順序").Value) = I*10 + 100

			Rs.MoveNext
			I = I + 1

		Loop

		' レコードセットを閉じる
		Rs.Close

		' 現在のフィールドにソート順序を設定
		For I = 0 to Ubound(aData) - 1

			colINum(I).Value = aData(I)

		Next

	end if

</script>
</body>
</html>
]]>
</RESOURCE>

</JOB>

インストール後は、一旦 IE を終了させて下さい。

関連する記事

ADO を使ったメモリソート



posted by at 19:40 | IE拡張 | このブログの読者になる | 更新情報をチェックする


2013年11月17日


runas 使ってコマンドプロンプトを VBScript で管理者として実行

元々、Shell としての機能にある、右クリックメニューの『管理者として実行』をスクリプトで処理する方法です。(『runas』がそれに該当します )

コマンドプロンプトは、管理者として実行すると、タイトルにその旨が表示されるので確認して下さい。



Shell.ShellExecute method
Set obj = Wscript.CreateObject("Shell.Application")
obj.ShellExecute "cmd.exe", "/k", "", "runas", 1



posted by at 01:49 | Shell.Application | このブログの読者になる | 更新情報をチェックする


2013年11月16日


ODBC ドライバの列挙

レジストリアクセスは一覧取得なので WMI が必要です。
ソートには ADO を使用します。
表示を コマンドプロンプトに表示する為に、CSCRIPT.EXE での実行を強制しています。
Set WshShell = WScript.CreateObject("WScript.Shell")

Crun

' ***********************************************************
' 処理開始
' ***********************************************************
Const HKEY_LOCAL_MACHINE = &H80000002
Const adVarChar = 200

Dim ErrorMessage

Set objRegistry = GetObject("Winmgmts:root\default:StdRegProv")

strPath = "SOFTWARE\ODBC\ODBCINST.INI\ODBC Drivers"
bRet = WMIRegEnumValues( HKEY_LOCAL_MACHINE, strPath, aNames, aTypes )

if not bRet then
	Wscript.Echo ErrorMessage
	Wscript.Quit
end if

Set Rs = CreateObject("ADODB.Recordset")
Rs.Fields.Append "ソートキー", adVarChar,255
Rs.Open

For Each data In aNames
	Rs.AddNew
	Rs.Fields("ソートキー").value = data
Next

Rs.Sort = "ソートキー"
Rs.MoveFirst

Do while not Rs.EOF
	Wscript.Echo Rs.Fields("ソートキー").value & ""
	Rs.MoveNext
Loop

Rs.Close

' **********************************************************
' 列挙
' **********************************************************
Function WMIRegEnumValues ( nType, strPath, aNames, aTypes )
	WMIRegEnumValues = False

	on error resume next
	WMIRet = objRegistry.EnumValues( nType, strPath, aNames, aTypes )
	if Err.Number <> 0 then
		ErrorMessage = Err.Description
		Exit Function
	end if
	if WMIRet <> 0 then
		ErrorMessage = Hex( WMIRet )
		Exit Function
	end if
	on error goto 0

	WMIRegEnumValues = True
End Function

' ***********************************************************
' Cscript.exe で強制実行
' ***********************************************************
Function Crun( )

	Dim str

	str = WScript.FullName
	str = Right( str, 11 )
	str = Ucase( str )
	if str <> "CSCRIPT.EXE" then
		str = WScript.ScriptFullName
		strParam = " "
		For I = 0 to Wscript.Arguments.Count - 1
			if instr(Wscript.Arguments(I), " ") < 1 then
				strParam = strParam & Wscript.Arguments(I) & " "
			else
				strParam = strParam & Dd(Wscript.Arguments(I)) & " "
			end if
		Next
		Call WshShell.Run( "cmd.exe /c cscript.exe " & Dd(str) & strParam & " & pause", 3 )
		WScript.Quit
	end if

End Function

' ***********************************************************
' ダブルクォート
' ***********************************************************
Function Dd( strValue )

	Dd = """" & strValue & """"

End function

関連する記事

ADO を使ったメモリソート


posted by at 03:01 | サンプル | このブログの読者になる | 更新情報をチェックする


2013年08月07日


Yahoo!メールで簡単メール送信( CDO.Message+VBScript関数 )

ポートが 465 なのは、SSL を使う場合のポートで、587 でも別の仕様で暗号化が可能ですが、Cdo が使えるのは 465 の標準の SSLのみです。

フリーメールで安心して使えそうなのは、Yahoo!メールとGmail です。Gmail でも同様に使えるはずです。
( hotmail は、Cdo で利用できませんが、587 の使えるソフトならば可能です )

Cdo で、587 番を使ったサブミッションポートの利用は可能ですが、その場合は認証部分が暗号化されないので内部的なメール送信で使う事をお勧めします。( 他のソフトならば認証部分だけの暗号化は可能です )
Dim ErrorMessage
' **********************************************************
' Yahoo!メール送信
' **********************************************************
YahooMail = "???????@yahoo.co.jp"
strName = "日本語で自分の名前"
strPass = "パスワード"
strTo = "宛先 <宛先のメールアドレス>"
strSubject = "Yahoo!メール+CDO.Message"
strBody = "本文" & vbCrLf + "です"

if YahooSend( YahooMail, strName, strPass, strTo, strSubject ,strBody ) then
	MsgBox("メールを送信しました")
else
	MsgBox( ErrorMessage )
end if

' **********************************************************
' Yahoo!メールで単純メール送信
' **********************************************************
Function YahooSend( _
	mailaddr, _
	jname, _
	pass, _
	mailto, _
	subj, _
	body _
)

	Dim Cdo

	Set Cdo = WScript.CreateObject("CDO.Message")

	Dim aAuth

	aAuth = Split( mailaddr, "@" )
	Cdo.Configuration.Fields.Item _
	 ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1
	Cdo.Configuration.Fields.Item _
	 ("http://schemas.microsoft.com/cdo/configuration/sendusername") = aAuth(0)
	Cdo.Configuration.Fields.Item _ 
	 ("http://schemas.microsoft.com/cdo/configuration/sendpassword") = pass

	if jname <> "" then
		Cdo.From = jname & " <" & mailaddr & ">"
	else
		Cdo.From = mailaddr
	end if
	Cdo.To = mailto
	Cdo.Subject	= subj
	Cdo.Textbody = body

	Cdo.Configuration.Fields.Item _
	 ("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2
	Cdo.Configuration.Fields.Item _
	 ("http://schemas.microsoft.com/cdo/configuration/smtpusessl") = true
	Cdo.Configuration.Fields.Item _
	 ("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.mail.yahoo.co.jp"
	Cdo.Configuration.Fields.Item _
	 ("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 465

	Cdo.Configuration.Fields.Update

	YahooSend = true

	on error resume next
	Cdo.Send
	if Err.Number <> 0 then
		ErrorMessage = Err.Description
		YahooSend = false
	end if
	on error goto 0

End Function

Gmail は、サーバーが smtp.gmail.com です。


タグ:通信
posted by at 16:38 | ツール | このブログの読者になる | 更新情報をチェックする



ServerXMLHTTP を使用してバイナリデータのダウンロードを行うスクリプト

殆どがServerXMLHTTPオブジェクトにまかされていて、イベントも存在しないのであまり巨大なファイルはダウンロードしてはいけません。

ですが、10メガ以内のファイル( 単純なフリーソフト等 ) ならば、特に問題は出ないと思います。( これに関してはかなり長い間運用して来ました )
Dim ErrorMessage
' **********************************************************
' ファイルをダウンロード
' **********************************************************
strUrl = "http://www5f.biglobe.ne.jp/~t-susumu/dl/tpad/tpad109.zip"
strPath = "C:\Users\lightbox\Documents\Downloads\tpad109.zip"
if HTTPDownload( strUrl, strPath ) then
	MsgBox("ダウンロードが成功しました")
else
	MsgBox( ErrorMessage )
end if


' **********************************************************
' ダウンロード
' 1) ダウンロードする URL
' 2) 保存するPC内のパス
' **********************************************************
Function HTTPDownload( strUrl, strPath )

	Dim objHTTP

	Set objHTTP = WScript.CreateObject("Msxml2.ServerXMLHTTP")

	HTTPDownload = True

	on error resume next
	Call objHTTP.Open("GET", strUrl, False )
	if Err.Number <> 0 then
		ErrorMessage = Err.Description
		HTTPDownload = False
		Exit Function
	end if
	on error goto 0

	on error resume next
	objHTTP.Send
	if Err.Number <> 0 then
		ErrorMessage = Err.Description
		HTTPDownload = False
		Exit Function
	end if
	on error goto 0

	Dim Stream

	Set Stream = WScript.CreateObject("ADODB.Stream")

	Stream.Open
	Stream.Type = 1	' バイナリ
	Stream.Write objHTTP.responseBody
	Stream.SaveToFile strPath, 2 ' 上書き
	Stream.Close

End Function






タグ:通信
posted by at 15:41 | ツール | このブログの読者になる | 更新情報をチェックする



VBScript で、グローバルな変数を関数内で定義する方法

グローバルな変数を作成して各関数から参照させるには、ソースコードの先頭で Dim で宣言するのが通常ですが、関数内から ExecuteGlobal ステートメントを呼び出す事によって同じ結果を得る事ができます。但し、この際変数名は文字列で指定する必要があるので、ソース全体(実行単位)で『定義済変数』という位置付けで申し合わせる必要があります
' **********************************************************
' グローバルな変数を関数内で定義する方法
' ( 文字列を作って、グローバル名前空間で実行 )
' **********************************************************

Call MyObject( "WshShell", "WScript.Shell" )

' 実行デスト
Call WshShell.Run( "notepad" )

' **********************************************************
' 関数内よりグローバル変数にオブジェクトをセットする
' **********************************************************
Function MyObject( strName, strObjName )

	Dim ExecuteString

	Call DimGlobal( strName )	' この部分は無くても動作します

	ExecuteString = "Set " & strName & " = WScript.CreateObject(""" & strObjName & """)"

	ExecuteGlobal ExecuteString

End Function

' **********************************************************
' 関数内よりグローバル変数を作成する
' **********************************************************
Function DimGlobal( strName )

	Dim ExecuteString

	ExecuteString = "Dim " & strName

	ExecuteGlobal ExecuteString

End Function




posted by at 14:58 | 基本事項 | このブログの読者になる | 更新情報をチェックする



XCOPY.EXE を使用した、『新しいファイルのみのバックアップ』を行うスクリプト

バックアップ先は、例えばリムーバルの保存用のハードディスクとすると、そこにこのスクリプトを置いてフォルダ名を決定して実行すると、そのフォルダの中にバックアップされます。

2回目以降は、新しいファイルしかバックアップされないので、新しいファイルが無い場合は『0 個のファイルをコピーしました』と表示されます

バックアップするフォルダのパスは、フルパスで設定しますが、ネットワークドライブが対象である事を想定しています。ですから、事前に仮想ドライブを設定する処理を追加する事もありますし、\\PC名\共有 という書き方でもかまいません。
Set WshShell = WScript.CreateObject("WScript.Shell")

Dim strCommand,strMessage
Dim strFrom,strTo

' コピー元
strFrom = "バックアップするフォルダのパス"
' コピー先
strTo = "バックアップ先"

' **********************************************
' 実行確認ダイアログ
' **********************************************
strMessage = strFrom & " の内容を   " & vbCrLf
strMessage = strMessage & strTo & " へ   " & vbCrLf
strMessage = strMessage & "新しいファイルのみコピーします" & vbCrLf & vbCrLf
strMessage = strMessage & "よろしいですか?"
if vbCancel = MsgBox( strMessage, vbOKCancel, "実行確認") then
	Wscript.Quit
end if

' **********************************************
' XCOPY
' **********************************************
strCommand = "cmd.exe /c XCOPY """ & strFrom & """ """ & strTo & """"
strCommand = strCommand & " /D /E /C /S /Y & echo 処理が終了しました & pause"
Call WshShell.Run( strCommand,, True )




posted by at 10:56 | ツール | このブログの読者になる | 更新情報をチェックする


2013年01月19日


VBScript の既定のスクリプトホストの変更

『スクリプトホスト』は、.vbs と .wsf という拡張子に関係付けられた、VBScript のソースコードを読み込んで実行するアプリケーションの事です。

VBScript では、cscript.exewscript.exe という二つのスクリプトホストがあり、前者はコマンドプロンプト用で、後者は Windows アプリケーション用で、実際どのような違いが出るかというと、Wscript.echo という処理が、前者では標準出力に出力されるのに対して、後者ではメッセージボックスに出力されるというところです。

当然、コマンドプロンプトを前提にして作成されたスクリプトで Wscript.echo が使われていると、Windows アプリケーションでは、メッセージボックスが表示されつづけるという問題が出てしまいます。ですから、どちらのスクリプトホストで実行されるかは良く考えて運用する必要があるわけです。

そもそも、デフォルトのスクリプトホストは、Windows アプリケーションとして起動されるので、エクスプローラから開いた場合は Windows アプリケーションとして実行されてしまいます。これらの問題を避けるには、いずれかのスクリプトホストを //H:CScript 引数を付けて実行するとデフォルトのスクリプトホストが変更されます( 戻す場合は //H:WScript で実行 )

さらに、これらの設定の大元はレジストリの記述なので、そこを変更してしまうと前述の切り替えを行わなくても同じ効果を得る事ができてしまいますが、元に戻すには直接レジストリを書き換える必要があります。
( 以下は、.vbs 用で、.wsf は WSFFile というエントリが別にあって管理されています )
HKEY_CLASSES_ROOT\VBSFile\Shell\Open\Command
HKEY_CLASSES_ROOT\VBSFile\Shell\Open2\Command

または

HKEY_LOCAL_MACHINE\SOFTWARE\Classes\VBSFile\Shell\Open\Command
HKEY_LOCAL_MACHINE\SOFTWARE\Classes\VBSFile\Shell\Open2\Command
>reg query HKEY_CLASSES_ROOT\VBSFile\Shell\Open\Command

HKEY_CLASSES_ROOT\VBSFile\Shell\Open\Command
    (既定)    REG_EXPAND_SZ    "%SystemRoot%\System32\WScript.exe" "%1" %*


>reg query HKEY_CLASSES_ROOT\VBSFile\Shell\Open2\Command

HKEY_CLASSES_ROOT\VBSFile\Shell\Open2\Command
    (既定)    REG_EXPAND_SZ    "%SystemRoot%\System32\CScript.exe" "%1" %*
>cscript /?
Microsoft (R) Windows Script Host Version 5.8
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.

使い方 : CScript scriptname.extension [オプション...] [引数...]

オプション :
 //B         バッチ モード : スクリプトのエラーおよびプロンプトを非表示にする
 //D         アクティブ デバッグを使用可能にする
 //E:engine  スクリプト実行時にエンジンを使用する
 //H:CScript 既定のスクリプト ホストを CScript.exe に変更する
 //H:WScript 既定のスクリプト ホストを WScript.exe に変更する (既定値)
 //I         対話モード (既定値、//B と逆の動作)
 //Job:xxxx  WSF ジョブを実行する
 //Logo      ロゴを表示する (既定値)
 //Nologo    ロゴを表示しない : 実行時に見出しを表示しない
 //S         このユーザーの現在のコマンド ライン オプションを保存する
 //T:nn      秒単位のタイムアウト時間 :  スクリプトを実行できる時間の最大値
 //X         デバッガでスクリプトを実行する
 //U         コンソールからリダイレクトされた I/O に Unicode を使用する



タグ:WScript cscript
posted by at 02:30 | 基本事項 | このブログの読者になる | 更新情報をチェックする


2011年12月16日


ユーザー環境変数の設定

PC名とユーザ名が必要です
' **********************************************************
' PC 名と ユーザ名を取得
' **********************************************************
Dim WshNetwork : Set WshNetwork = CreateObject( "WScript.Network" )
Dim strUser : strUser = WshNetwork.UserName
Dim strMachine : strMachine = WshNetwork.ComputerName

Dim strComputer : strComputer = "."
Dim obj : Set obj = GetObject("winmgmts:\\"&strComputer&"\root\cimv2")


' **********************************************************
' ユーザ環境変数を登録
' **********************************************************
Dim objEnv : Set objEnv = obj.Get("Win32_Environment").SpawnInstance_

objEnv.Name = "MyENV"
objEnv.UserName = strMachine & "\" & strUser
objEnv.VariableValue = "設定しました"
objEnv.Put_



posted by at 09:10 | WMI | このブログの読者になる | 更新情報をチェックする



システム環境変数とユーザー環境変数の列挙

select * from Win32_Environment where SystemVariable = True and Name = 'PATH'
というクエリで、SystemVariable を True にするとシステム変数です
Dim strValue : strValue = ""

Dim strComputer : strComputer = "."
Dim obj : Set obj = GetObject("winmgmts:\\"&strComputer&"\root\cimv2")

' **********************************************************
' システム環境変数
' **********************************************************
Dim objItems : Set objItems = obj.ExecQuery _
   ("select * from Win32_Environment where SystemVariable = True and Name = 'PATH'")

Dim objItem
For Each objItem in objItems
	strValue = objItem.VariableValue
Next

Dim I,aData
if strValue <> "" then
	aData = Split( strValue, ";" )

	strValue = ""
	For I = 0 to Ubound( aData )
		strValue = strValue & aData(I) & vbCrLf
	Next

	Wscript.Echo strValue
end if

' **********************************************************
' ユーザー環境変数
' **********************************************************
Set objItems = obj.ExecQuery _
   ("select * from Win32_Environment where SystemVariable = False and Name = 'PATH'")

For Each objItem in objItems
	strValue = objItem.VariableValue
Next

if strValue <> "" then
	aData = Split( strValue, ";" )

	strValue = ""
	For I = 0 to Ubound( aData )
		strValue = strValue & aData(I) & vbCrLf
	Next

	Wscript.Echo strValue
end if




posted by at 09:01 | WMI | このブログの読者になる | 更新情報をチェックする



PC 名と ユーザ名を取得

VBScript では、Dim で変数を定義した時に初期値をセットできないので、:(コロン) を使って横書きにして、同じような記述にしています
' **********************************************************
' PC 名と ユーザ名を取得
' **********************************************************
Dim WshNetwork : Set WshNetwork = CreateObject( "WScript.Network" )
Dim strUser : strUser = WshNetwork.UserName
Dim strMachine : strMachine = WshNetwork.ComputerName

Wscript.Echo strUser & " : " & strMachine




posted by at 08:44 | WSHのオブジェクト | このブログの読者になる | 更新情報をチェックする



ADO を使ったメモリソート

Microsoft のドキュメントでは、255 を越える場合に可変長となると書かれていましたが、どうも違うようです。
' Null で終了する Unicode 文字列を示します (DBTYPE_WSTR)。
Const adWChar = 130

Dim Rs

Set Rs = Wscript.CreateObject("ADODB.Recordset")
' 127 までは固定長として扱われました
' 128 以上は可変長のはずです
Rs.Fields.Append "ソートキー", adWChar,128
Rs.Fields.Append "ソートデータ", adWChar,128
Rs.Open

Rs.AddNew
Rs.Fields("ソートキー").value = "C"
Rs.Fields("ソートデータ").value = "山田"
'Rs.Update : メモリ上なので無くても良いようです

Rs.AddNew
Rs.Fields("ソートキー").value = "A"
Rs.Fields("ソートデータ").value = "田中"
'Rs.Update

Rs.AddNew
Rs.Fields("ソートキー").value = "B"
Rs.Fields("ソートデータ").value = "鈴木"
'Rs.Update

Rs.Sort = "ソートキー"

Rs.MoveFirst

Dim strResult : strResult = ""
Do while not Rs.EOF

	strResult = strResult & Rs.Fields("ソートキー").Value & " : "
	strResult = strResult & Rs.Fields("ソートデータ").Value & vbCrLf

	Rs.MoveNext

Loop

Rs.Close

Wscript.Echo strResult


使用例

ODBC ドライバの列挙

Seesaa のカテゴリをソート(通常と逆順と記事が多い順)する VBScript で記述された IE 拡張



タグ:ADO
posted by at 01:23 | ADO | このブログの読者になる | 更新情報をチェックする



XMLファイルの更新

このような XML を読み込んでデータを追加した後、
新しいファイルとして保存します
<?xml version="1.0" encoding="UTF-8"?>
<channel>
	<item>
		<title>タイトル</title>
		<link>対象URL</link>
		<description>内容の説明</description>
		<date>2011-12-14</date>
	</item>
</channel>



※ 更新した結果を IE で表示すると以下のようになりました

' DOM Object 作成
Set dom = Wscript.CreateObject("Msxml2.DOMDocument")

' 既存 XML 入力
dom.load( "index.xml" )

' 既存のノード( channel ) を取得
Set nodeList = dom.getElementsByTagName("channel")

' 新規ノードを作成( createElement でも良い )
Set node = dom.createNode( 1, "item", "" )
' Set node = dom.createElement( "item" )

' **********************************************************
' title ノードを作成
' **********************************************************
Set nodeChild = dom.createElement("title")
nodeChild.appendChild( dom.createTextNode("これは") )
node.appendChild( nodeChild )

' **********************************************************
' link ノードを作成
' **********************************************************
Set nodeChild = dom.createElement("link")
nodeChild.appendChild( dom.createTextNode("SHIFT_JIS ですが") )
node.appendChild( nodeChild )

' **********************************************************
' description ノードを作成
' **********************************************************
Set nodeChild = dom.createElement("description")
nodeChild.appendChild( dom.createTextNode("オブジェクトになると") )
node.appendChild( nodeChild )

' **********************************************************
' dc:date ノードを作成
' **********************************************************
Set nodeChild = dom.createElement("date")
nodeChild.appendChild( dom.createTextNode("内部コードに変換されます") )
node.appendChild( nodeChild )


' channel ノードは、一つしか無いので、nodeList(0) で参照
' channel ノードの下に item ノードを追加
nodeList(0).appendChild( node )

' 保存
dom.save( "index2.xml" )



タグ:xml
posted by at 00:25 | サンプル | このブログの読者になる | 更新情報をチェックする


2011年12月12日


実行されているスクリプトが存在するディレクトリのフルパスを取得する

strCurDir = WScript.ScriptFullName
strCurDir = Replace( strCurDir, "\" & WScript.ScriptName, "" )

でも動作しますが、以下のほうが正統派だとは思います
ソースツールバーの右端のダウンロードでダウンロードした場合は、キャラクタセットを SHIFT_JIS で保存しなおして、拡張子を .vbs に変更して下さい
Dim Fso,obj,strCurPath

' ファイルシステムオブジェクト
Set Fso = CreateObject( "Scripting.FileSystemObject" )

' 現在実行されているスクリプトのフルパス
strCurPath = WScript.ScriptFullName

' ファイルオブジェクトを作成
Set obj = Fso.GetFile( strCurPath )

' ファイルオブジェクトが存在するフォルダオブジェクト
Set obj = obj.ParentFolder

' そのフォルダのフルパス
strCurPath = obj.Path

Wscript.Echo strCurPath




posted by at 15:12 | サンプル | このブログの読者になる | 更新情報をチェックする


2011年10月16日


VBScript の整数の入った配列をJavaScriptを使ってソートする

一つのソースで VBScript と JavaScript を混在させる必要があるので、ソースは .wsf の形式で記述します。

JavaScript では、VBArray というオブジェクトがあるので、それを使って少なくとも JavaScript 側で VBScript の配列をソートする事は容易です。

ただ、それを戻す方法が直接には無いのでカンマ区切りの文字列にしてVBScript 側に返して、VBScript 側ではその文字列を分解してから整数に戻して使用します
ソースツールバーの右端のダウンロードでダウンロードした場合は、キャラクタセットを SHIFT_JIS で保存しなおして、拡張子を .wsf に変更して下さい
<job>
<script language="JavaScript">

// ***********************************************************
// VBの整数値の入った配列をソートして文字列で返す
// ***********************************************************
function js_sort(aData) {

	var vb_obj = new VBArray(aData);

	var js_array = vb_obj.toArray();

	js_array.sort(sortFunction);

	var str = ""

	var i

	for( i = 0; i <= vb_obj.ubound(); i++ ) {
		if ( i != 0 ) {
			str += ","
		}
		str += js_array[i];
	}

	return str

}
// ***********************************************************
// 数値用の比較関数
// ***********************************************************
function sortFunction(a,b) {

	if( parseInt((a+"")) < parseInt((b+"")) ) {
		return -1;
	}
	if( parseInt((a+"")) > parseInt((b+"")) ) {
		return 1;
	}
	return 0;
}

</script>
<script language="VBScript">
' ***********************************************************
' 処理開始
' ***********************************************************

' 配列の準備
Dim aData(10)

' 単純に値をセット
aData(0) = 5
aData(1) = 1
aData(2) = 2
aData(3) = 6
aData(4) = 3
aData(5) = 4
aData(6) = 7
aData(7) = 10
aData(8) = 9
aData(9) = 8
aData(10) = 11

' ソートされた文字列を取得
str = js_sort( aData )

' 文字列として一旦分解
aData2 = Split(str,",")

' 正数値として入れ直す
For I = 0 to Ubound(aData2)
	aData2(I) = CLng(aData2(I))
Next

' 確認
For I = 0 to Ubound(aData2)
	Wscript.Echo aData2(I) * 10
Next

</script>

</job>





タグ:ソート
posted by at 21:54 | JavaScript利用 | このブログの読者になる | 更新情報をチェックする