win7运行脚本求故事

发布时间:2020-06-28 来源:脚本之家 点击:



  当类名属性修改后,我们或许不必担心前三项的属性'

SetDoc=CreateObject("Microsoft.XMLDOM")
Doc.async=False
Doc.load("")
Setroot=Doc.documentElement
Setnode=root.childNodes.nextNode()
Wscript.Echo"共"&node.text&"条签名信息"

SetDoc=CreateObject("Microsoft.XMLDOM")
Doc.async=False
Doc.load("")
Setroot=Doc.documentElement
Wscript.Echo"XML根结点名字是:"&root.nodeName
Setnode=root.childNodes.nextNode()

Fornodei=0Tonode.childNodes.Length-1
SetNowNode=node.childNodes(nodei)
msg=msg&vbCrLf&"id"&":"&NowNode.Attributes.getNamedItem("id").text
'msg=msg&vbCrLf&"id"&":"&NowNode.getAttribute("id")
msg=msg&vbCrLf&"title"&":"&NowNode.selectSingleNode("title").text
msg=msg&vbCrLf&"pubDate"&":"&NowNode.selectSingleNode("pubDate").text
'msg=msg&vbCrLf&NowNode.childNodes(0).nodeName&":"&NowNode.childNodes(0).text
'msg=msg&vbCrLf&NowNode.childNodes(1).nodeName&":"&NowNode.childNodes(1).text
Next
Wscript.Echomsg

脚本精灵怎么录制脚本
Helpfile:help文件的有效路径
声明:
DeclareFunctionSetComputerNameLib"kernel32"Alias"SetComputerNameA"(ByVallpComputerNameAsString)AsLong
使用:
NewName="HelloWorld"
SetComputerNameNewName->

重要事项

    注意要以编程方式设置数据源,工程中必须要有指向MicrosoftActiveXDataObjects的引用:在“工程”菜单中,选择“引用”,然后选择“MicrosoftActiveXDataObjects2.0Library”

换句话说:
my-script.vbs"c:\documentsandsettings\kmyer"
这就是命令解释程序的工作方式OptionExplicit
PrivateDeclareFunctionOSGetLongPathNameLib"VB5STKIT.DLL"Alias"GetLongPathName"(ByVallpszLongPathAsString,ByVallpszShortPathAsString,ByValcchBufferAsLong)AsLong
PublicDeclareFunctionOSGetShortPathNameLib"kernel32"Alias"GetShortPathNameA"(ByVallpszLongPathAsString,ByVallpszShortPathAsString,ByValcchBufferAsLong)AsLong
FunctionGetLongPathName(ByValstrShortPathAsString)AsString
ConstcchBuffer=300
DimstrLongPathAsString
DimlResultAsLong
OnErrorGoTo0
strLongPath=String(cchBuffer,Chr$(0))
lResult=OSGetLongPathName(strShortPath,strLongPath,cchBuffer)
IflResult=0Then
GetShortPathName=""
Else
GetLongPathName=StripTerminator(strLongPath)
EndIf
EndFunction
PublicFunctionGetShortPathName(ByValstrLongPathAsString)AsString
ConstcchBuffer=300
DimstrShortPathAsString
DimlResultAsLong
OnErrorGoTo0
strShortPath=String(cchBuffer,Chr$(0))
lResult=OSGetShortPathName(strLongPath,strShortPath,cchBuffer)
IflResult=0Then
GetShortPathName=""
Else
GetShortPathName=StripTerminator(strShortPath)
EndIf
EndFunction
'-----------------------------------------------------------
'函数:StripTerminator
'
'返回非零结尾的字符串


'********************************************************************
'*
'*File:Restart.vbs
'*Created:March1999
'*Version:1.0
'*
'*MainFunction:Shutsdown,PowerOff,LogOff,Restartsamachine.
'*
'*Restart.vbs/S<server>[/U<username>][/W<password>]
'*[/O<outputfile>][/L}[/P][/R][/Q][/F][/T<timeinseconds>]
'*
'*Copyright(C)1999MicrosoftCorporation
'*
'********************************************************************

OPTIONEXPLICIT

'Defineconstants
CONSTCONST_ERROR=0
CONSTCONST_WSCRIPT=1
CONSTCONST_CSCRIPT=2
CONSTCONST_SHOW_USAGE=3
CONSTCONST_PROCEED=4

'ShutdownMethodConstants
CONSTCONST_SHUTDOWN=1
CONSTCONST_LOGOFF=0
CONSTCONST_POWEROFF=8
CONSTCONST_REBOOT=2
CONSTCONST_FORCE_REBOOT=6
CONSTCONST_FORCE_POWEROFF=12
CONSTCONST_FORCE_LOGOFF=4
CONSTCONST_FORCE_SHUTDOWN=5

'Declarevariables
DimintOpMode,i
DimstrServer,strUserName,strPassword,strOutputFile
DimblnLogoff,blnPowerOff,blnReBoot,blnShutDown
DimblnForce
DimintTimer
DimUserArray(3)
DimMyCount

'Makesurethehostiscsript,ifnotthenabort
VerifyHostIsCscript()

'Parsethecommandline
intOpMode=intParseCmdLine(strServer,_
strUserName,_
strPassword,_
strOutputFile,_
blnLogoff,_
blnPowerOff,_
blnReBoot,_
blnShutdown,_
blnForce,_
intTimer)

SelectCaseintOpMode

CaseCONST_SHOW_USAGE
CallShowUsage()

CaseCONST_PROCEED
CallReboot(strServer,_
strOutputFile,_
strUserName,_
strPassword,_
blnReboot,_
blnForce,_
intTimer)

CallLogOff(strServer,_
strOutputFile,_
strUserName,_
strPassword,_
blnLogoff,_
blnForce,_
intTimer)

CallPowerOff(strServer,_
strOutputFile,_
strUserName,_
strPassword,_
blnPowerOff,_
blnForce,_
intTimer)

CallShutDown(strServer,_
strOutputFile,_
strUserName,_
strPassword,_
blnShutDown,_
blnForce,_
intTimer)

CaseCONST_ERROR
'DoNothing

CaseElse'Default--shouldneverhappen
CallWscript.Echo("Erroroccurredinpassingparameters.")

EndSelect


'********************************************************************
'*
'*SubReboot()
'*
'*Purpose:Rebootsamachine.
'*
'*Input:strServeramachinename
'*strOutputFileanoutputfilename
'*strUserNamethecurrentuser'sname
'*strPasswordthecurrentuser'spassword
'*blnForcespecifieswhethertoforcethelogoff
'*intTimerspecifiestheamountoftimetoperformthefunction
'*
'*Output:ResultsareeitherprintedonscreenorsavedinstrOutputFile.
'*
'********************************************************************
PrivateSubReboot(strServer,strOutputFile,strUserName,strPassword,blnReboot,blnForce,intTimer)


ONERRORRESUMENEXT

DimobjFileSystem,objOutputFile,objService,objEnumerator,objInstance
DimstrQuery,strMessage
DimintStatus
ReDimstrID(0),strName(0)

ifblnreboot=falsethen
ExitSub
Endif

ifintTimer>0then
wscript.echo"Rebootingmachine"&strServer&"in"&intTimer&"seconds..."
wscript.sleep(intTimer*1000)
Endif

'Openatextfileforoutputifthefileisrequested
IfNotIsEmpty(strOutputFile)Then
If(NOTblnOpenFile(strOutputFile,objOutputFile))Then
CallWscript.Echo("Couldnotopenanoutputfile.")
ExitSub
EndIf
EndIf

'Establishaconnectionwiththeserver.
IfblnConnect("root\cimv2",_
strUserName,_
strPassword,_
strServer,_
objService)Then
CallWscript.Echo("")
CallWscript.Echo("Pleasechecktheservername,"_
&"credentialsandWBEMCore.")
ExitSub
EndIf

strID(0)=""
strName(0)=""
strMessage=""
strQuery="Select*FromWin32_OperatingSystem"

SetobjEnumerator=objService.ExecQuery(strQuery,,0)
IfErr.NumberThen
Print"Error0x"&CStr(Hex(Err.Number))&"occurredduringthequery."
IfErr.Description<>""Then
Print"Errordescription:"&Err.Description&"."
EndIf
Err.Clear
ExitSub
EndIf

i=0
ForEachobjInstanceinobjEnumerator
IfblnForceThen
intStatus=objInstance.Win32ShutDown(CONST_FORCE_REBOOT)
Else
intStatus=objInstance.Win32ShutDown(CONST_REBOOT)
EndIf

IFintStatus=0Then
strMessage="Rebootamachine"&strServer&"."
Else
strMessage="Failedtorebootamachine"&strServer&"."
EndIf
CallWriteLine(strMessage,objOutputFile)
Next

IfIsObject(objOutputFile)Then
objOutputFile.Close
CallWscript.Echo("Resultsaresavedinfile"&strOutputFile&".")
EndIf
EndSub


'********************************************************************
'*
'*SubLogOff()
'*
'*Purpose:Logsofftheusercurrentlyloggedontoamachine.
'*
'*Input:strServeramachinename
'*strOutputFileanoutputfilename
'*strUserNamethecurrentuser'sname
'*strPasswordthecurrentuser'spassword
'*blnForcespecifieswhethertoforcethelogoff
'*intTimerspecifiestheamountoftimetopreformthefunction
'*
'*Output:ResultsareeitherprintedonscreenorsavedinstrOutputFile.
'*
'********************************************************************
PrivateSubLogOff(strServer,strOutputFile,strUserName,strPassword,blnLogoff,blnForce,intTimer)


ONERRORRESUMENEXT

DimobjFileSystem,objOutputFile,objService,objEnumerator,objInstance
DimstrQuery,strMessage
DimintStatus
ReDimstrID(0),strName(0)

Ifblnlogoff=falsethen
ExitSub
Endif

ifintTimer>1then
wscript.echo"Loggingoffmachine"&strServer&"in"&intTimer&"seconds..."
wscript.sleep(intTimer*1000)
Endif

'Openatextfileforoutputifthefileisrequested
IfNotIsEmpty(strOutputFile)Then
If(NOTblnOpenFile(strOutputFile,objOutputFile))Then
CallWscript.Echo("Couldnotopenanoutputfile.")
ExitSub
EndIf
EndIf

'Establishaconnectionwiththeserver.
IfblnConnect("root\cimv2",_
strUserName,_
strPassword,_
strServer,_
objService)Then
CallWscript.Echo("")
CallWscript.Echo("Pleasechecktheservername,"_
&"credentialsandWBEMCore.")
ExitSub
EndIf

strID(0)=""
strName(0)=""
strMessage=""
strQuery="Select*FromWin32_OperatingSystem"

SetobjEnumerator=objService.ExecQuery(strQuery,,0)
IfErr.NumberThen
Print"Error0x"&CStr(Hex(Err.Number))&"occurredduringthequery."
IfErr.Description<>""Then
Print"Errordescription:"&Err.Description&"."
EndIf
Err.Clear
ExitSub
EndIf

i=0
ForEachobjInstanceinobjEnumerator
IfblnForceThen
intStatus=objInstance.Win32ShutDown(CONST_FORCE_LOGOFF)
Else
intStatus=objInstance.Win32ShutDown(CONST_LOGOFF)
EndIf

IFintStatus=0Then
strMessage="Loggingoffthecurrentuseronmachine"&_
strServer&"..."
Else
strMessage="Failedtologoffthecurrentuserfrommachine"_
&strServer&"."
EndIf
CallWriteLine(strMessage,objOutputFile)
Next

IfIsObject(objOutputFile)Then
objOutputFile.Close
CallWscript.Echo("Resultsaresavedinfile"&strOutputFile&".")
EndIf
EndSub


'********************************************************************
'*
'*SubPowerOff()
'*
'*Purpose:Powersoffamachine.
'*
'*Input:strServeramachinename
'*strOutputFileanoutputfilename
'*strUserNamethecurrentuser'sname
'*strPasswordthecurrentuser'spassword
'*blnForcespecifieswhethertoforcethelogoff
'*intTimerspecifiestheamountoftimetoperformthefunction
'*
'*Output:ResultsareeitherprintedonscreenorsavedinstrOutputFile.
'*
'********************************************************************
PrivateSubPowerOff(strServer,strOutputFile,strUserName,strPassword,blnPowerOff,blnForce,intTimer)


ONERRORRESUMENEXT

DimobjFileSystem,objOutputFile,objService,objEnumerator,objInstance
DimstrQuery,strMessage
DimintStatus
ReDimstrID(0),strName(0)

ifblnPoweroff=falsethen
Exitsub
Endif

IfintTimer>0then
wscript.echo"Poweringoffmachine"&strServer&"in"&intTimer&"seconds..."
wscript.sleep(intTimer*1000)
Endif

'Openatextfileforoutputifthefileisrequested
IfNotIsEmpty(strOutputFile)Then
If(NOTblnOpenFile(strOutputFile,objOutputFile))Then
CallWscript.Echo("Couldnotopenanoutputfile.")
ExitSub
EndIf
EndIf

'Establishaconnectionwiththeserver.
IfblnConnect("root\cimv2",_
strUserName,_
strPassword,_
strServer,_
objService)Then
CallWscript.Echo("")
CallWscript.Echo("Pleasechecktheservername,"_
&"credentialsandWBEMCore.")
ExitSub
EndIf

strID(0)=""
strName(0)=""
strMessage=""
strQuery="Select*FromWin32_OperatingSystem"

SetobjEnumerator=objService.ExecQuery(strQuery,,0)
IfErr.NumberThen
Print"Error0x"&CStr(Hex(Err.Number))&"occurredduringthequery."
IfErr.Description<>""Then
Print"Errordescription:"&Err.Description&"."
EndIf
Err.Clear
ExitSub
EndIf

i=0
ForEachobjInstanceinobjEnumerator
IfblnForceThen
intStatus=objInstance.Win32ShutDown(CONST_FORCE_POWEROFF)
Else
intStatus=objInstance.Win32ShutDown(CONST_POWEROFF)
EndIf

IFintStatus=0Then
strMessage="Poweroffmachine"&strServer&"."
Else
strMessage="Failedtopoweroffmachine"&strServer&"."
EndIf
CallWriteLine(strMessage,objOutputFile)
Next

IfIsObject(objOutputFile)Then
objOutputFile.Close
CallWscript.Echo("Resultsaresavedinfile"&strOutputFile&".")
EndIf
EndSub


'********************************************************************
'*
'*SubShutdown()
'*
'*Purpose:Shutsdownamachine.
'*
'*Input:strServeramachinename
'*strOutputFileanoutputfilename
'*strUserNamethecurrentuser'sname
'*strPasswordthecurrentuser'spassword
'*blnForcespecifieswhethertoforcethelogoff
'*intTimerspecifiestheamountoftimetoperformthefunction
'*
'*Output:ResultsareeitherprintedonscreenorsavedinstrOutputFile.
'*
'********************************************************************
PrivateSubShutdown(strServer,strOutputFile,strUserName,strPassword,blnShutDown,blnForce,intTimer)


ONERRORRESUMENEXT

DimobjFileSystem,objOutputFile,objService,objEnumerator,objInstance
DimstrQuery,strMessage
DimintStatus
ReDimstrID(0),strName(0)

IfblnShutdown=Falsethen
ExitSub
Endif

ifintTimer>0then
wscript.echo"Shuttingdowncomputer"&strServer&"in"&intTimer&"seconds..."
wscript.sleep(intTimer*1000)
Endif


'Openatextfileforoutputifthefileisrequested
IfNotIsEmpty(strOutputFile)Then
If(NOTblnOpenFile(strOutputFile,objOutputFile))Then
CallWscript.Echo("Couldnotopenanoutputfile.")
ExitSub
EndIf
EndIf

'Establishaconnectionwiththeserver.
IfblnConnect("root\cimv2",_
strUserName,_
strPassword,_
strServer,_
objService)Then
CallWscript.Echo("")
CallWscript.Echo("Pleasechecktheservername,"_
&"credentialsandWBEMCore.")
ExitSub
EndIf

strID(0)=""
strName(0)=""
strMessage=""
strQuery="Select*FromWin32_OperatingSystem"

SetobjEnumerator=objService.ExecQuery(strQuery,,0)
IfErr.NumberThen
Print"Error0x"&CStr(Hex(Err.Number))&"occurredduringthequery."
IfErr.Description<>""Then
Print"Errordescription:"&Err.Description&"."
EndIf
Err.Clear
ExitSub
EndIf

i=0
ForEachobjInstanceinobjEnumerator
IfblnForceThen
intStatus=objInstance.Win32ShutDown(CONST_FORCE_SHUTDOWN)
Else
intStatus=objInstance.Win32ShutDown(CONST_SHUTDOWN)
EndIf

IFintStatus=0Then
strMessage="Shutsdownmachine"&strServer&"."
Else
strMessage="Failedtoshutdownmachine"&strServer&"."
EndIf
CallWriteLine(strMessage,objOutputFile)
Next

IfIsObject(objOutputFile)Then
objOutputFile.Close
CallWscript.Echo("Resultsaresavedinfile"&strOutputFile&".")
EndIf
EndSub



'********************************************************************
'*
'*FunctionintParseCmdLine()
'*
'*Purpose:Parsesthecommandline.
'*Input:
'*
'*Output:strServeraremoteserver(""=localserver")
'*strUserNamethecurrentuser'sname
'*strPasswordthecurrentuser'spassword
'*strOutputFileanoutputfilename
'*intTimeramountoftimeinseconds
'*
'********************************************************************
PrivateFunctionintParseCmdLine(ByRefstrServer,_
ByRefstrUserName,_
ByRefstrPassword,_
ByRefstrOutputFile,_
ByRefblnLogoff,_
ByRefblnShutdown,_
ByRefblnReboot,_
ByRefblnPowerOff,_
ByRefblnForce,_
ByRefintTimer)


ONERRORRESUMENEXT

DimstrFlag
DimintState,intArgIter
DimobjFileSystem

IfWscript.Arguments.Count>0Then
strFlag=Wscript.arguments.Item(0)
EndIf

IfIsEmpty(strFlag)Then'Noargumentshavebeenreceived
Wscript.Echo("ArgumentsareRequired.")
intParseCmdLine=CONST_ERROR
ExitFunction
EndIf

'Checkiftheuserisaskingforhelporisjustconfused
If(strFlag="help")OR(strFlag="/h")OR(strFlag="\h")OR(strFlag="-h")_
OR(strFlag="\?")OR(strFlag="/?")OR(strFlag="?")_
OR(strFlag="h")Then
intParseCmdLine=CONST_SHOW_USAGE
ExitFunction
EndIf

'Retrievethecommandlineandsetappropriatevariables
intArgIter=0
DoWhileintArgIter<=Wscript.arguments.Count-1
SelectCaseLeft(LCase(Wscript.arguments.Item(intArgIter)),2)

Case"/s"
intParseCmdLine=CONST_PROCEED
IfNotblnGetArg("Server",strServer,intArgIter)Then
intParseCmdLine=CONST_ERROR
ExitFunction
EndIf
intArgIter=intArgIter+1

Case"/o"
IfNotblnGetArg("OutputFile",strOutputFile,intArgIter)Then
intParseCmdLine=CONST_ERROR
ExitFunction
EndIf
intArgIter=intArgIter+1

Case"/u"
IfNotblnGetArg("UserName",strUserName,intArgIter)Then
intParseCmdLine=CONST_ERROR
ExitFunction
EndIf
intArgIter=intArgIter+1

Case"/w"
IfNotblnGetArg("UserPassword",strPassword,intArgIter)Then
intParseCmdLine=CONST_ERROR
ExitFunction
EndIf
intArgIter=intArgIter+1

Case"/f"
blnForce=True
intArgIter=intArgIter+1

Case"/r"
blnReBoot=True
userarray(0)=blnReBoot
intArgIter=intArgIter+1

Case"/q"
blnPowerOff=True
userarray(1)=blnPowerOff
intArgIter=intArgIter+1

Case"/l"
blnLogOff=True
userarray(2)=blnLogoff
intArgIter=intArgIter+1

Case"/p"
blnShutDown=True
userarray(3)=blnShutDown
intArgIter=intArgIter+1

Case"/t"
IfNotblnGetArg("Timer",intTimer,intArgIter)Then
intParseCmdLine=CONST_ERROR
ExitFunction
EndIf
intArgIter=intArgIter+1

CaseElse'Weshouldn'tgethere
CallWscript.Echo("Invalidormisplacedparameter:"_
&Wscript.arguments.Item(intArgIter)&vbCRLF_
&"Pleasechecktheinputandtryagain,"&vbCRLF_
&"orinvokewith'/?'forhelpwiththesyntax.")
Wscript.Quit

EndSelect

Loop'**intArgIter<=Wscript.arguments.Count-1

MyCount=0

fori=0to3
ifuserarray(i)=Truethen
MyCount=Mycount+1
Endif
Next

ifMycount>1then
intParseCmdLine=CONST_SHOW_USAGE
Endif

IfIsEmpty(intParseCmdLine)Then
intParseCmdLine=CONST_ERROR
Wscript.Echo("ArgumentsareRequired.")
EndIf

EndFunction

'********************************************************************
'*
'*SubShowUsage()
'*
'*Purpose:Showsthecorrectusagetotheuser.
'*
'*Input:None
'*
'*Output:Helpmessagesaredisplayedonscreen.
'*
'********************************************************************
PrivateSubShowUsage()

Wscript.Echo""
Wscript.Echo"Logoffs,Reboots,PowersOff,orShutsDownamachine."
Wscript.Echo""
Wscript.Echo"SYNTAX:"
Wscript.Echo"Restart.vbs[/S<server>][/U<username>][/W<password>]"
Wscript.Echo"[/O<outputfile>]</L></R></P></Q></F>[/T<timeinseconds>]"
Wscript.Echo""
Wscript.Echo"PARAMETERSPECIFIERS:"
wscript.echo"/TAmountoftimetoperformthefunction."
Wscript.Echo"/QPerformShutdown."
Wscript.Echo"/PPerformPoweroff."
Wscript.Echo"/RPerformReboot."
Wscript.Echo"/LPerformLogoff."
Wscript.Echo"/FForceFunction."
Wscript.Echo"serverAmachinename."
Wscript.Echo"usernameThecurrentuser'sname."
Wscript.Echo"passwordPasswordofthecurrentuser."
Wscript.Echo"outputfileTheoutputfilename."
Wscript.Echo""
Wscript.Echo"EXAMPLE:"
Wscript.Echo"1.cscriptRestart.vbs/SMyMachine2/R"
Wscript.Echo"RebootsthecurrentmachineMyMachine2."
Wscript.Echo"2.cscriptRestart.vbs/SMyMachine2/R/F"
Wscript.Echo"ForcesMyMachine2toreboot."
Wscript.Echo"3.cscriptRestart.vbs/SMyMachine2/R/T30"
Wscript.Echo"RebootsthecurrentmachineMyMachine2in30seconds."
Wscript.Echo"NOTE:"
Wscript.Echo"Theforceoptionwillmakethemachineperformthefunctioneven"_
&"ifthereare"
Wscript.Echo"openandunsaveddocuementsonthescreen."

EndSub

'********************************************************************
'*GeneralRoutines
'********************************************************************

'********************************************************************
'*
'*FunctionstrPackString()
'*
'*Purpose:AttachesspacestoastringtoincreasethelengthtointWidth.
'*
'*Input:strStringastring
'*intWidththeintendedlengthofthestring
'*blnAfterShouldspacesbeaddedafterthestring?
'*blnTruncatespecifieswhethertotruncatethestringornotif
'*thestringlengthislongerthanintWidth
'*
'*Output:strPackStringisreturnedasthepackedstring.
'*
'********************************************************************
PrivateFunctionstrPackString(ByValstrString,_
ByValintWidth,_
ByValblnAfter,_
ByValblnTruncate)

ONERRORRESUMENEXT

intWidth=CInt(intWidth)
blnAfter=CBool(blnAfter)
blnTruncate=CBool(blnTruncate)

IfErr.NumberThen
CallWscript.Echo("Argumenttypeisincorrect!")
Err.Clear
Wscript.Quit
EndIf

IfIsNull(strString)Then
strPackString="null"&Space(intWidth-4)
ExitFunction
EndIf

strString=CStr(strString)
IfErr.NumberThen
CallWscript.Echo("Argumenttypeisincorrect!")
Err.Clear
Wscript.Quit
EndIf

IfintWidth>Len(strString)Then
IfblnAfterThen
strPackString=strString&Space(intWidth-Len(strString))
Else
strPackString=Space(intWidth-Len(strString))&strString&""
EndIf
Else
IfblnTruncateThen
strPackString=Left(strString,intWidth-1)&""
Else
strPackString=strString&""
EndIf
EndIf

EndFunction

'********************************************************************
'*
'*FunctionblnGetArg()
'*
'*Purpose:HelpertointParseCmdLine()
'*
'*Usage:
'*
'*Case"/s"
'*blnGetArg("servername",strServer,intArgIter)
'*
'********************************************************************
PrivateFunctionblnGetArg(ByValStrVarName,_
ByRefstrVar,_
ByRefintArgIter)

blnGetArg=False'failure,changedtoTrueuponsuccessfulcompletion

IfLen(Wscript.Arguments(intArgIter))>2then
IfMid(Wscript.Arguments(intArgIter),3,1)=":"then
IfLen(Wscript.Arguments(intArgIter))>3then
strVar=Right(Wscript.Arguments(intArgIter),_
Len(Wscript.Arguments(intArgIter))-3)
blnGetArg=True
ExitFunction
Else
intArgIter=intArgIter+1
IfintArgIter>(Wscript.Arguments.Count-1)Then
CallWscript.Echo("Invalid"&StrVarName&".")
CallWscript.Echo("Pleasechecktheinputandtryagain.")
ExitFunction
EndIf

strVar=Wscript.Arguments.Item(intArgIter)
IfErr.NumberThen
CallWscript.Echo("Invalid"&StrVarName&".")
CallWscript.Echo("Pleasechecktheinputandtryagain.")
ExitFunction
EndIf

IfInStr(strVar,"/")Then
CallWscript.Echo("Invalid"&StrVarName)
CallWscript.Echo("Pleasechecktheinputandtryagain.")
ExitFunction
EndIf

blnGetArg=True'success
EndIf
Else
strVar=Right(Wscript.Arguments(intArgIter),_
Len(Wscript.Arguments(intArgIter))-2)
blnGetArg=True'success
ExitFunction
EndIf
Else
intArgIter=intArgIter+1
IfintArgIter>(Wscript.Arguments.Count-1)Then
CallWscript.Echo("Invalid"&StrVarName&".")
CallWscript.Echo("Pleasechecktheinputandtryagain.")
ExitFunction
EndIf

strVar=Wscript.Arguments.Item(intArgIter)
IfErr.NumberThen
CallWscript.Echo("Invalid"&StrVarName&".")
CallWscript.Echo("Pleasechecktheinputandtryagain.")
ExitFunction
EndIf

IfInStr(strVar,"/")Then
CallWscript.Echo("Invalid"&StrVarName)
CallWscript.Echo("Pleasechecktheinputandtryagain.")
ExitFunction
EndIf
blnGetArg=True'success
EndIf
EndFunction

'********************************************************************
'*
'*FunctionblnConnect()
'*
'*Purpose:ConnectstomachinestrServer.
'*
'*Input:strServeramachinename
'*strNameSpaceanamespace
'*strUserNamenameofthecurrentuser
'*strPasswordpasswordofthecurrentuser
'*
'*Output:objServiceisreturnedasaserviceobject.
'*strServerissettolocalhostifleftunspecified
'*
'********************************************************************
PrivateFunctionblnConnect(ByValstrNameSpace,_
ByValstrUserName,_
ByValstrPassword,_
ByRefstrServer,_
ByRefobjService)

ONERRORRESUMENEXT

DimobjLocator,objWshNet

blnConnect=False'Thereisnoerror.

'CreateLocatorobjecttoconnecttoremoteCIMobjectmanager
SetobjLocator=CreateObject("WbemScripting.SWbemLocator")
IfErr.Numberthen
CallWscript.Echo("Error0x"&CStr(Hex(Err.Number))&_
"occurredincreatingalocatorobject.")
IfErr.Description<>""Then
CallWscript.Echo("Errordescription:"&Err.Description&".")
EndIf
Err.Clear
blnConnect=True'Anerroroccurred
ExitFunction
EndIf

'Connecttothenamespacewhichiseitherlocalorremote
SetobjService=objLocator.ConnectServer(strServer,strNameSpace,_
strUserName,strPassword)
ObjService.Security_.impersonationlevel=3
IfErr.Numberthen
CallWscript.Echo("Error0x"&CStr(Hex(Err.Number))&_
"occurredinconnectingtoserver"_
&strServer&".")
IfErr.Description<>""Then
CallWscript.Echo("Errordescription:"&Err.Description&".")
EndIf
Err.Clear
blnConnect=True'Anerroroccurred
EndIf

'Getthecurrentserver'snameifleftunspecified
IfIsEmpty(strServer)Then
SetobjWshNet=CreateObject("Wscript.Network")
strServer=objWshNet.ComputerName
EndIf

EndFunction

'********************************************************************
'*
'*SubVerifyHostIsCscript()
'*
'*Purpose:Determineswhichprogramisusedtorunthisscript.
'*
'*Input:None
'*
'*Output:Ifhostisnotcscript,thenanerrormessageisprinted
'*andthescriptisaborted.
'*
'********************************************************************
SubVerifyHostIsCscript()

ONERRORRESUMENEXT

DimstrFullName,strCommand,i,j,intStatus

strFullName=WScript.FullName

IfErr.Numberthen
CallWscript.Echo("Error0x"&CStr(Hex(Err.Number))&"occurred.")
IfErr.Description<>""Then
CallWscript.Echo("Errordescription:"&Err.Description&".")
EndIf
intStatus=CONST_ERROR
EndIf

i=InStr(1,strFullName,".exe",1)
Ifi=0Then
intStatus=CONST_ERROR
Else
j=InStrRev(strFullName,"",i,1)
Ifj=0Then
intStatus=CONST_ERROR
Else
strCommand=Mid(strFullName,j+1,i-j-1)
SelectCaseLCase(strCommand)
Case"cscript"
intStatus=CONST_CSCRIPT
Case"wscript"
intStatus=CONST_WSCRIPT
CaseElse'shouldneverhappen
CallWscript.Echo("Anunexpectedprogramwasusedto"_
&"runthisscript.")
CallWscript.Echo("OnlyCScript.ExeorWScript.Execan"_
&"beusedtorunthisscript.")
intStatus=CONST_ERROR
EndSelect
EndIf
EndIf

IfintStatus<>CONST_CSCRIPTThen
CallWScript.Echo("PleaserunthisscriptusingCScript."&vbCRLF&_
"Thiscanbeachievedby"&vbCRLF&_
"1.Using""CScriptRestart.vbsarguments""forWindows95/98or"_
&vbCRLF&"2.ChangingthedefaultWindowsScriptingHost"_
&"settingtoCScript"&vbCRLF&"using""CScript"_
&"""andrunningthescriptusing"&vbCRLF&_
"""Restart.vbsarguments""forWindowsNT/2000.")
WScript.Quit
EndIf

EndSub

'********************************************************************
'*
'*SubWriteLine()
'*Purpose:Writesatextlineeithertoafileoronscreen.
'*Input:strMessagethestringtoprint
'*objFileanoutputfileobject
'*Output:strMessageiseitherdisplayedonscreenorwrittentoafile.
'*
'********************************************************************
SubWriteLine(ByValstrMessage,ByValobjFile)

OnErrorResumeNext
IfIsObject(objFile)then'objFileshouldbeafileobject
objFile.WriteLinestrMessage
Else
CallWscript.Echo(strMessage)
EndIf

EndSub

'********************************************************************
'*
'*FunctionblnErrorOccurred()
'*
'*Purpose:Reportserrorwithastringsayingwhattheerroroccurredin.
'*
'*Input:strInstringsayingwhattheerroroccurredin.
'*
'*Output:displayedonscreen
'*
'********************************************************************
PrivateFunctionblnErrorOccurred(ByValstrIn)

IfErr.NumberThen
CallWscript.Echo("Error0x"&CStr(Hex(Err.Number))&":"&strIn)
IfErr.Description<>""Then
CallWscript.Echo("Errordescription:"&Err.Description)
EndIf
Err.Clear
blnErrorOccurred=True
Else
blnErrorOccurred=False
EndIf

EndFunction

'********************************************************************
'*
'*FunctionblnOpenFile
'*
'*Purpose:Opensafile.
'*
'*Input:strFileNameAstringwiththenameofthefile.
'*
'*Output:SetsobjOpenFiletoaFileSystemObjectandsetisitto
'*NothinguponFailure.
'*
'********************************************************************
PrivateFunctionblnOpenFile(ByValstrFileName,ByRefobjOpenFile)

ONERRORRESUMENEXT

DimobjFileSystem

SetobjFileSystem=Nothing

IfIsEmpty(strFileName)ORstrFileName=""Then
blnOpenFile=False
SetobjOpenFile=Nothing
ExitFunction
EndIf

'Createafileobject
SetobjFileSystem=CreateObject("Scripting.FileSystemObject")
IfblnErrorOccurred("Couldnotcreatefilesystemobject.")Then
blnOpenFile=False
SetobjOpenFile=Nothing
ExitFunction
EndIf

'Openthefileforoutput
SetobjOpenFile=objFileSystem.OpenTextFile(strFileName,8,True)
IfblnErrorOccurred("Couldnotopen")Then
blnOpenFile=False
SetobjOpenFile=Nothing
ExitFunction
EndIf
blnOpenFile=True

EndFunction

'********************************************************************
'**
'*EndofFile*
'**
'********************************************************************
淘闻下载。

Setcomponents=packages.GetCollection("ComponentsInPackage",_package.Key)
调用SaveChanges方法将更改保存到目录第五篇(共六篇):

请允许我县描述一下我现在的环境:气温高达37摄氏度,而我忘记了图书馆开门的时间,还要在这里站上一个小时,在热带植物的包裹下,各种奇怪的小飞虫围着我转来转去.不过令我欣慰的是,终于写到五了,还有两课我们的"基础篇"就要结束了.

今天我们来了解语言本身的最后一个论题:数组.

  要理解"数组",这个概念我觉得另一种翻译对学习来说更加容易:"阵列",没错,数组就是一个阵列,一个数据的阵列.最简单的例子是数据库系统,假设你要储存20名学生的英语成绩,如果不是用数组,你则要创建20个不同的变量,累死.数组就是类型相同(重要!)的一组数据(或者n组),用来储存相关的量,最简单的数组是一维数组,我们就先来学习它吧.

  什么是一维数组呢?在3维以下,你可以利用几何知识来理解"维"的概念,一维相当于一条线,二维则是一个矩形,三维是一个长方体.我知道这么讲是很抽象的,我们先举个一维数组的例子就比较容易了解了.

dima(9)'从零开始
fori=0to9
a(i)=i'填充每一个数组元素
msgbox(a(i))'输出数组元素
next

  我们可以看到,定义一个数组的方法和定义一个变量没有什么不同,同样是使用dim语句.定义一维数组的方法如下:

dim数组名(元素数量),这里大家要注意一点,这里定义的元素数量总是比你要的要少一个,因为一个数组的起点是0号数据而不是1,所以大家一定要小心:你需要10个数据,就定义"9",需要100个就定义99,依此类推.数组的元素可以看成一个个独立的变量,你可以像独立的变量那样使用他们.数组元素的量可能是毫无关系的,比如第一个数组元素储存你的年龄,第二个储存今年西瓜的销售量,但这种做法是不鼓励的,甚至是不被接受的,不要这么干,这样的情况请定义独立的变量.for语句在数组中可算是大显身手,还记得for吗?它累加一个变量,我们可以把这个变量应用在数组中正好用来读取或者填充按照顺序排列的数组元素,上面就是这样一个例子.数组其实是很简单的东西(再BASIC语言里面),数组难的是怎么捣弄这些循环,让他们按照你的要求运转.这个等到二维数组再说,我们先看看如何手工填充数组.

  如果你这个都想不到的话,那你真是白学了:

dimname(7),str'一共八个学生,str变量是用来把他们储存成一个字符串以便输出
fori=0to7
name(i)=inputbox("请输入第"&i+1&"个学生的名字")
str=str&""&name(i)
next
msgbox(str)

  这样我们就有了一个小小的数据库,它们的数据排列可以看成这样:

  name(0),name(1),name(2).....name(7)

  看到了吧,所以我说我们可以把它看成是"一条线",等到我们学到了文件操作,就可以把他们输出到文件中去了.一维数组有很多用处,我们来看一下一个复杂的例子.我们要储存3各学生的名字,身高,成绩这三种数据,由于名字是字符串,而身高可能是浮点数(带小数点的数),成绩则可能是整数,所以我们不能把他们储存在一个数组里面(不要忘记,数组织只能存储同类的数据),所以我们要建3个数组,以下是例程:

dimname(2),high(2),mark(2)'定义三个数组分别储存3个人的名字,身高和得分
dimctr'计数器
forctr=0to2
name(ctr)=inputbox("请输入第"&ctr+1&"个学生的姓名")
high(ctr)=inputbox("请输入第"&ctr+1&"个学生的身高")
mark(ctr)=inputbox("请输入第"&ctr+1&"个学生的得分")
next

  OK,我们已经填充好了数据,现在我们的小小数据库只能按顺序输入,我们要让它看起来像点样子,我们来给他设计查询功能:

'接着上面的程序
dimcname,temp'要查询的名字,和一个临时变量,用来储存数据的位置
cname=inputbox("请输入你要查询的名字:")
forctr=0to2'遍历所有name数组的成员,寻找要查询的名字
ifname(ctr)=cnamethen
temp=ctr'记录数据位置
exitfor'退出循环,和exitdo的用法一样
endif'不要忘了endif
next
msgbox("姓名:"&name(temp)&""&"身高:"&high(temp)&""&"得分:"&mark(temp))

  嘿嘿,有意思吧,其实在这个程序里面,那个temp变量完全没有必要,只是为了更清楚地说明问题.因为当exitfor以后ctr变量的值就不会改变,储存的正好是对应数据在数组中的位置,写这个temp变量是为了照顾到以后要学C++的朋友(C++可以在for语句里声明新变量,只在这个for结构中有效,所以到了外部就不能访问了).也就是说可以简化成如下:

dimcname
cname=inputbox("请输入你要查询的名字:")
forctr=0to2
ifname(ctr)=cnamethenexitfor'因为只有exitfor就不需要块if了
next
msgbox("姓名:"&name(ctr)&""&"身高:"&high(ctr)&""&"得分:"&mark(ctr))

  这是最直接的路子.好好重读一下上面所有的源代码,然后自己写几个程序,完全搞清楚一维数组及其应用以后再看后面的二位数组.二维数组好像是一个一维数组的集合,就好像"线积成面"一样,由n各一维数组组成二维数组,这是初学者比较好理解的办法(比较精确的是用"编号"的概念去理解,因为4维以上的数组就比较难以用欧几里德几何概念去解释了).二维数组是很好解释的,我们来看一下:

dima(2,2)'从零开始,一共有3X3=9个数据
dimi,j'需要两个计数器
fori=0to2
forj=0to2'使用嵌套循环
a(i,j)="X"
next
next

  我们创建了一个这样的二维数组(那些","是我用来分割元素的,并不存在),了解二维数组的了吗?不清楚我们再讲一下

编号012
0X,X,X
1X,X,X
2X,X,X

  二维数组的看起来是不是就是一个矩形呢?(你在内存中看不到这样的矩形,只是便于你理解),每个数据都有编号,由两个数来定位,这个很像(非常像)你在国际象棋棋盘上寻找一个格,我们用类似"C6","A2"这样的"垂直坐标"进行定位,对,"垂直坐标",很确切.我们要使用一个二维数组元素的时候可以和普通变量一样使用,只要指定数组元素的"定位点"就可以了,例如

a(0)(1)=1,b(2)(1)="你好",诸如此类.要注意的是二维数组也只能储存类型相同的元素,而且上标(起点)也从0开始.计算一个二维数组的元素个数只要把两个下标+1(以得到实际的值)再乘起来就可以了,非常类似于求一个矩形的面积.

  假如需要储存的都是同一类型的数据,我们就可以用二维数组,比如要储存5个人的姓名,国籍,民族,就可以使用二维数据

diminfo(4,2)'一共五个人,要储存的数据类型有3项
dimi,j
fori=0to4
forj=0to2
dimopt'定义一个变量用于存储数据项提示
selectcasej'判断应该输入的是什么数据
case0
opt="姓名"
case1
opt="国籍"
case2
opt="民族"
endselect
info(i,j)=inputbox("请输入第"&i+1&"个人的"&opt)
next
next
'输出太麻烦了,我懒得动,你知道那么回事就行了

  这样就不需要定义3个一维数组了.

  多位数组(三维以上)的定义和使用方法与二维数组一样,但不太好在欧几里德几何空间里加以解释,幸好我们并不太常用那么多维的数组.定义一个三位数组:dima(1,2,3)'一共24各数组元素.

  今天因为要搬家(我喜欢Sengkang啊,可是MM嫌交通不便,谁不知道她只想去逛街),而GF要去和她的同学去参加什么试验半夜才回家,所以下午我只能自己去押车搬家了,5555~~好可怜,这次就请大家原谅我少写一点,我可是站在图书馆外写的啊,

现在腿都软了~~~本来还要讲"动态数组"的,但想了想还是放到"进阶部分"再说吧.

要点:

1)一维数组是"线",二维数组是"面",三维数组是"体"(多维数组就乱套)

2)数组的下标从0开始

3)for循环在数组的应用中起了很大作用,二维数组需要嵌套循环

作业:

  上次出的"百鸡问题",大家喜欢吗?以后我们就做这种需要动脑的题目,那些简单的实践,大家一定要多做!

1)定义一个数组,包含5个元素, 都是随机整数(随便输入),要求把他们按照从大到小的顺序排列起来

2)有两个二维数组a(4,4)和b(4,4)(元素值随便),交换两个数组(原来的a的所有元素值变成b的,b的所有元素值变成a的)


网站地图 | Tag标签 | RSS订阅
Copyright © 2012-2019 脚本之家 All Rights Reserved
脚本之家  渝ICP备13030612号