Script經(jīng)典文章
發(fā)表時(shí)間:2023-08-21 來源:明輝站整理相關(guān)軟件相關(guān)文章人氣:
[摘要]開篇:讀取環(huán)境變量 讓我們以一個(gè)在許多環(huán)境中都非常實(shí)用的示例腳本作為開篇。當(dāng)您使用登錄腳本或批處理文件時(shí),讀取環(huán)境變量是一項(xiàng)非常普遍的操作。您可以通過諸如%COMPUTERNAME%和%WINDIR...
開篇:讀取環(huán)境變量
讓我們以一個(gè)在許多環(huán)境中都非常實(shí)用的示例腳本作為開篇。當(dāng)您使用登錄腳本或批處理文件時(shí),讀取環(huán)境變量是一項(xiàng)非常普遍的操作。您可以通過諸如%COMPUTERNAME%和%WINDIR%之類的腳本來映射網(wǎng)絡(luò)驅(qū)動(dòng)器,連接打印機(jī)或執(zhí)行其它希望在登錄/注銷腳本中完成的相關(guān)操作。有關(guān)如何通過編程方式從腳本中訪問這些變量的示例之一是使用Wscript.Shell對(duì)象。
如果希望在本地運(yùn)行一個(gè)應(yīng)用程序、對(duì)注冊(cè)表內(nèi)容進(jìn)行操作、創(chuàng)建一個(gè)快捷方式或訪問某個(gè)系統(tǒng)文件夾,您可以隨時(shí)創(chuàng)建一個(gè)Wscript.Shell(WshShell)對(duì)象。WshShell對(duì)象能夠提供一個(gè)環(huán)境集合,這個(gè)集合允許您對(duì)各種環(huán)境變量(如WINDIR、PATH或PROMPT)進(jìn)行處理。
例如(說明:如需對(duì)這個(gè)腳本進(jìn)行測(cè)試,請(qǐng)根據(jù)您所處域環(huán)境中的服務(wù)器配置情況對(duì)腳本中的DC名稱進(jìn)行修改):
' –Start
Dim wshShell
' Create a new Windows Scripting Host Shell object
Set wshShell = CreateObject("Wscript.Shell")
' Set it to read the environment variables
Set EnvVar = wshShell.Environment("PROCESS")
' Re-direct LPT1: to the appropriate printer according to the authenticating DC name
If EnvVar.Item("LogonServer") = "DC1" then
wshShell.Run "net use lpt1: \\DC1\Printer1"
Else
wshShell.Run "net use lpt1: \\DC2\Printer2"
End If
' -End
這個(gè)腳本將使用net use命令根據(jù)LogonServer變量取值將LPT1:端口連接到適當(dāng)?shù)拇蛴C(jī)上。當(dāng)負(fù)責(zé)執(zhí)行身份驗(yàn)證的DC為\\DC1時(shí),LPT1:將被映射到printer1上,對(duì)于其它DC,LPT1:將被映射到printer2上。只需將包含EnvVar.Item的一行信息替換為您所希望的變量,您便可以通過這個(gè)腳本獲取任意一種環(huán)境變量(如Computername、TEMP、WinDir等)。舉例來說:如欲讀取TEMP目錄位置,您只需使用EnvVar.Item("TEMP")。
注冊(cè)表操作
注冊(cè)表操作是一項(xiàng)常見的工作,系統(tǒng)經(jīng)常需要在注冊(cè)表中保存相關(guān)信息并根據(jù)需要對(duì)其進(jìn)行讀取。從注冊(cè)表中刪除與寫入信息的操作可以通過Wscript.Shell對(duì)象所提供的RegWrite和RegDelete方法在.vbs文件中完成。讀取注冊(cè)表數(shù)據(jù)的操作則可通過RegRead方法實(shí)現(xiàn)。
在訪問注冊(cè)表時(shí),您還可以使用WMI。乍看起來,使用WMI似乎不如使用Wscript.Shell對(duì)象那樣直觀,然而,這種方式能夠提供更加強(qiáng)大的功能特性與控制能力(例如對(duì)各種注冊(cè)表鍵及其取值進(jìn)行列舉的能力)。
TechNet腳本中心為您提供了許多用以演示如何通過WSH和WMI對(duì)注冊(cè)表數(shù)據(jù)進(jìn)行訪問與操作的實(shí)用腳本示例。如需獲取這些示例,請(qǐng)查看 http://www.microsoft.com/technet/scriptcenter/registry/default.asp。
利用WMI讀取操作系統(tǒng)信息
在前面列出的示例代碼中,我們看到了如何從環(huán)境變量中讀取信息,然而,您所需操作并使用的許多信息位于其它存儲(chǔ)機(jī)制或接口中。您可以通過WMI來獲取您所能想到的各種系統(tǒng)信息,這些信息包括磁盤與分區(qū)情況、事件查看器數(shù)據(jù)、服務(wù)項(xiàng)目、共享資源以及與操作系統(tǒng)環(huán)境和應(yīng)用程序相關(guān)的其它任意內(nèi)容。
如需了解更多關(guān)于WMI的信息,請(qǐng)查看 http://msdn.microsoft.com/library/en-us/dnclinic/html/scripting06112002.asp。
以下示例腳本將顯示從其所在計(jì)算機(jī)上獲取的各種不同信息。此腳本應(yīng)在運(yùn)行Windows 2000或更高版本操作系統(tǒng)的系統(tǒng)上執(zhí)行:
' –Start
' Using WMI to read Win32_OperatingSystem information
For Each os in GetObject("winmgmts:").InstancesOf("Win32_OperatingSystem")
' Display the OS information in "chunks": each VBCRLF line
' means go down one line to the next one, and each WScript.Echo statement means
' display a new message box.
WScript.Echo "Version Info:" & VBCRLF & _
"============" & VBCRLF & _
" Version: ", os.Caption, os.Version & VBCRLF & _
" Build: ", os.BuildNumber, os.BuildType & VBCRLF & _
" CSD Version: ", os.CSDVersion & VBCRLF & _
" Serial Number: ", os.SerialNumber & VBCRLF & _
" Manufacturer: ", os.Manufacturer
WScript.Echo "Memory Info:" & VBCRLF & _
"===========" & VBCRLF & _
" Free Physical Memory: ", os.FreePhysicalMemory & VBCRLF & _
" Free Space in Paging Files: ", os.FreeSpaceInPagingFiles & VBCRLF & _
" Size Stored in Paging Files: ", os.SizeStoredInPagingFiles & VBCRLF & _
" Free Virtual Memory: ", os.FreeVirtualMemory & VBCRLF & _
" Total Virtual Memory Size: ", os.TotalVirtualMemorySize & VBCRLF & _
" Total Visible Memory Size", os.TotalVisibleMemorySize
WScript.Echo "Time Info:" & VBCRLF & _
"=========" & VBCRLF & _
" Current Time Zone: ", os.CurrentTimeZone & VBCRLF & _
" Install Date: ", os.InstallDate & VBCRLF & _
" Last Bootup Time: ", os.LastBootUpTime & VBCRLF & _
" Local Date & Time: ", os.LocalDateTime
WScript.Echo "Process Info:" & VBCRLF & _
"============" & VBCRLF & _
" Foreground App Boost: ", os.ForegroundApplicationBoost & VBCRLF & _
" Maximum #Processes: ", os.MaxNumberOfProcesses & VBCRLF & _
" Maximum Memory Size for Processes: ", os.MaxProcessMemorySize & VBCRLF & _
" #Processes: ", os.NumberOfProcesses
WScript.Echo "User Info:" & VBCRLF & _
"=========" & VBCRLF & _
"#Users: ", os.NumberOfUsers & VBCRLF & _
"Registered User: ", os.RegisteredUser
WScript.Echo "Locale Info:" & VBCRLF & _
"===========" & VBCRLF & _
"Code Set: ", os.CodeSet & VBCRLF & _
"Country Code: ", os.CountryCode & VBCRLF & _
"Locale: ", os.Locale
WScript.Echo "System Info:" & VBCRLF & _
"===========" & VBCRLF & _
"Boot Device: ", os.BootDevice & VBCRLF & _
"Name: ", os.CSName & VBCRLF & _
"Status: ", os.Status & VBCRLF & _
"System Device: ", os.SystemDevice & VBCRLF & _
"System Directory: ", os.SystemDirectory & VBCRLF & _
"Windows Directory: ", os.WindowsDirectory
Next
' –End
針對(duì)多個(gè)對(duì)象設(shè)置相關(guān)信息
最具利用價(jià)值的腳本操作之一是針對(duì)同一域中的多個(gè)對(duì)象設(shè)置相關(guān)信息。讓我們來考慮一下下面這個(gè)示例:當(dāng)我們?cè)贜T中打開用戶管理器時(shí),我們可以輕松提取一份用戶列表并統(tǒng)一對(duì)其屬性進(jìn)行編輯,F(xiàn)在,與NT環(huán)境相比,Active Directory提供的許多改進(jìn)功能,其在各個(gè)方面均遠(yuǎn)遠(yuǎn)勝過原有的管理工具。盡管如此,上述這種簡(jiǎn)單操作卻需要由許多管理員來協(xié)同完成。令人振奮的消息是,多項(xiàng)選擇與編輯功能已經(jīng)被添加到Windows XP/.NET Active Directory用戶與計(jì)算機(jī)MMC嵌入式單元中。下面,讓我們來看一看如何通過腳本方式完成這項(xiàng)操作。在以下示例中,我們將通過一個(gè)腳本為Windows 2000 Active Directory域中某一特定組織單元內(nèi)的多個(gè)用戶復(fù)制主目錄和主驅(qū)動(dòng)器盤符。
這個(gè)示例在整個(gè)腳本范圍內(nèi)使用了ADSI。如需了解更多關(guān)于ADSI的信息,請(qǐng)查看 http://msdn.microsoft.com/library/en-us/netdir/adsi/adsi_scripting_tutorial.asp。
以下為示例腳本代碼:
' -Start
' Setting Home Directory for multiple users in a specific OU
Dim oContainer
' Bind to the destination Organizational Unit or container (modify this line according to
' your own domain tree information)
Set oContainer=GetObject("LDAP://OU=MyUsers,DC=yosdom,DC=com")
' Running the ModifyUsers Subroutine on the container
ModifyUsers(oContainer)
' Clean up
Set oContainer = Nothing
' Display a message box upon operation complete
MsgBox "Finished :O)"
' Close
WScript.Quit
Sub ModifyUsers(oTopLevelContainer) ' oTopLevelContainer is the oContainer object
Dim oObj
' Go into a loop for every object in the container
For Each oObj in oTopLevelContainer
' We use "Select Case" to apply different code/actions to different values of an item. In
' this case, we check every object's Class to apply the actions according to the Object's
' class, e.g. If it's a user object, it goes into the 'Case "user"' section.
Select Case oObj.Class
' if it's a user object, then set it's home directory and
' home drive properties (modify the Server name and home drive
' letter according to your needs.)
Case "user"
oObj.Put "HomeDirectory", "\\server1\users\" + oUser.SamAccountName
oObj.Put "HomeDrive", "m:"
' Save changes to the user object
oObj.Setinfo
' If it's a container/OU, go into the ModifyUsers loop for every object there
Case "organizationalUnit" , "container"
ModifyUsers(oObj)
End select
' Goes into the next available child object under the container
Next
End Sub
' –End
通過執(zhí)行上述腳本,yosdom.com域中名為MyUsers的組織單元內(nèi)的所有用戶都將被設(shè)置相應(yīng)的主目錄與主驅(qū)動(dòng)器盤符。其中,主驅(qū)動(dòng)器為M:,主目錄則取決于用戶登錄名稱,例如\\Server1\users\YossiS。
在仔細(xì)閱讀這個(gè)腳本時(shí),請(qǐng)注意,ModifyUsers子程序通過一個(gè)Select Case循環(huán)語句依次檢查對(duì)象類別并根據(jù)情況執(zhí)行適當(dāng)?shù)牟僮。舉例來說,如果在MyUsers之下發(fā)現(xiàn)一個(gè)更低級(jí)別的容器或另一個(gè)OU,那么,它將進(jìn)入到這個(gè)容器/OU中,并針對(duì)這一級(jí)別內(nèi)的所有用戶執(zhí)行相同的腳本代碼。如果當(dāng)前元素是一個(gè)對(duì)象,那么,它將根據(jù)上面描述的方式為其設(shè)置適當(dāng)?shù)男畔ⅰD梢詫?duì)下面這行信息進(jìn)行修改并觀察腳本執(zhí)行過程中會(huì)出現(xiàn)何種變化:
Set oContainer=GetObject("LDAP://DC=yosdom,DC=com")
修改后的腳本將在整個(gè)域樹上運(yùn)行并為發(fā)現(xiàn)的所有用戶設(shè)置適當(dāng)?shù)闹黩?qū)動(dòng)器與主目錄。
您還可以在如何利用ADSI為域中所有用戶創(chuàng)建用戶共享資源(234746)一文中找到一個(gè)與此類似且更加高級(jí)的腳本示例,這個(gè)腳本示例將通過同種類型的子程序自動(dòng)創(chuàng)建用戶共享資源。
向日志文件中追加信息
在運(yùn)行一個(gè)較長(zhǎng)的腳本程序時(shí),維護(hù)一個(gè)文本日志文件對(duì)于后期分析非常重要,它不僅能夠幫助您了解腳本運(yùn)行方式,同時(shí)還是一種用以確定腳本故障位置的調(diào)試機(jī)制。您可以使用Scripting.FileSystemObject對(duì)象創(chuàng)建自定義日志文件并向其中添加信息。
如需添加、移動(dòng)、修改、創(chuàng)建、刪除文件夾(目錄)或文件,您可以使用FileSystemObject(FSO)對(duì)象模型,以下鏈接所對(duì)應(yīng)的頁面對(duì)其進(jìn)行了詳細(xì)解釋 http://msdn.microsoft.com/library/en-us/script56/html/FSOoriFileSystemObject.asp。
舉例來說,讓我們繼續(xù)使用前面那個(gè)讀取環(huán)境變量并執(zhí)行‘net use’命令的腳本,并向其中加入用以記錄日志信息的子程序。(說明:如需對(duì)這個(gè)腳本進(jìn)行測(cè)試,請(qǐng)根據(jù)您所處域環(huán)境中的服務(wù)器配置情況對(duì)腳本中的DC名稱進(jìn)行修改):
' –Start
Dim wshShell
' Create a new Windows Scripting Host Shell object
Set wshShell = CreateObject("Wscript.Shell")
' Set it to read the environment variables
Set EnvVar = wshShell.Environment("PROCESS")
' Log/Append an entry into a local text file stating which DC authenticated the user
' Note: Calling 'Now' outputs the exact time/date on this machine in real-time
Add2Log Now & ": User was authenticated by DC " & EnvVar.Item("LogonServer")
' Now back to the original script action: Re-direct LPT1 to the appropriate printer
' according to the authenticating DC name
If EnvVar.Item("LogonServer") = "DC1" then
' Map LPT1 to the printer \\DC1\Printer1 If the DC name is DC1
wshShell.Run "net use lpt1: \\DC1\Printer1"
Else
' If the DC name is not DC1, then Map LPT1 to the printer \\DC2\Printer2
wshShell.Run "net use lpt1: \\DC2\Printer2"
End If
' Log/Append another entry into the local text file stating the script is completed
Add2Log Now & ": Script completed running."
' Close
wscript.quit
' This is the Log Appending Subroutine
Sub Add2Log (txt) ' txt is the text we send into the subroutine
' Declare the log file name
Const Myfile = "C:\MyLog.txt" ' Log file name
' Open it for Append
Const ForAppending = 8 ' Append mode
' Declare the FileSystemObject and File variables
Dim fso, file
' Create a new FileSystemObject object
Set fso = CreateObject("Scripting.FileSystemObject")
' Open the file and force creation, if it doesn't exist already
Set file = fso.OpenTextFile(MyFile, ForAppending, TRUE)
file.WriteLine (txt) ' append log
' Clean up
Set file = Nothing
End Sub
' –End
前往C:\目錄下并打開MyLog.txt文件。您將看到類似于以下記錄的信息:
7/16/2002 6:43:35 PM: User was authenticated by DC \\DCName
7/16/2002 6:43:37 PM: Script completed running.
這個(gè)腳本程序由兩個(gè)主要部分組成:‘日志追加’子程序(Add2Log子程序)和開頭幾行用以觸發(fā)日志追加子程序的腳本代碼。當(dāng)您在腳本中運(yùn)行一行以‘Add2Log’開頭并在空格(“ ”)后緊跟文本信息的代碼時(shí),這些文本信息將被傳入到Add2Log子程序中。該子程序?qū)涯付ǖ奈谋拘畔⒆芳拥轿谋疚募ù朔N情況下為c:\MyLog.txt)的下一行中。
如果希望獲得更多示例腳本,我建議您訪問相關(guān)鏈接(特別是TechNet腳本中心)并查找那里所提供的示例腳本。祝您早日享受腳本編程所帶來的便利!