Shell.Application技术资料

本文详细介绍如何使用Shell对象进行文件夹浏览、文件操作等任务。涵盖了Shell对象的基本使用方法,包括打开文件夹、运行控制面板项目等功能,以及如何利用Folder对象进行文件系统的遍历和文件属性的获取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、创建 Shell 对象
 var Shell = new ActiveXObject("Shell.Application");
 
2、使用 Shell 属性及方法

 Shell.Application
 Shell.Parent

 Shell.CascadeWindows()
 Shell.TileHorizontally()
 Shell.TileVertically()
 Shell.ControlPanelItem(sDir) /* 比如:sysdm.cpl */
 Shell.EjectPC()
 Shell.Explore(vDir)
 Shell.Open(vDir)
 Shell.FileRun()
 Shell.FindComputer()
 Shell.FindFiles()
 Shell.Help()
 Shell.MinimizeAll()
 Shell.UndoMinimizeALL()
 Shell.RefreshMenu()
 Shell.SetTime()
 Shell.TrayProperties()
 Shell.ShutdownWindows()
 Shell.Suspend()
 oWindows = Shell.Windows() /* 返回ShellWindows对象 */
 fFolder = Shell.NameSpace(vDir) /* 返回所打开的vDir的Folder对象 */
 oFolder = Shell.BrowseForFolder(Hwnd, sTitle, iOptions [, vRootFolder]) /* 选择文件夹对话框 */
  /*示例:
  function BrowseFolder()
  {
   var Message = "请选择文件夹";

   var Shell  = new ActiveXObject( "Shell.Application" );
   var Folder = Shell.BrowseForFolder(0,Message,0x0040,0x11);
   if(Folder != null)
   {
    Folder = Folder.items(); // 返回 FolderItems 对象
    Folder = Folder.item();  // 返回 Folderitem 对象
    Folder = Folder.Path;  // 返回路径
    if(Folder.charAt(varFolder.length-1) != "//"){
     Folder = varFolder + "//";
    }
    return Folder;
   }
  }
  */

  /*示例:
  var Folder = Shell.NameSpace("C://");  // 返回 Folder对象
  */
 
3、使用 Folder 对象
 
 [ oApplication = ] Folder.Application   // Contains the Application object.
 [ oParentFolder= ] Folder.ParentFolder   // Contains the parent Folder object.
 [    oTitle    = ] Folder.Title    // Contains the title of the folder.

 Folder.CopyHere(vItem [, vOptions])   // Copies an item or items to a folder.
 Folder.MoveHere(vItem [, vOptions])   // Moves an item or items to this folder.
  /*
  vItem:  Required. Specifies the item or items to move. This can be a string that represents a file name, a FolderItem object, or a FolderItems object.
    vOptions Optional. Specifies options for the move operation. This value can be zero or a combination of the following values. These values are based upon flags defined for use with the fFlags member of the C++ SHFILEOPSTRUCT structure. These flags are not defined as such for Microsoft? Visual Basic?, Visual Basic Scripting Edition (VBScript), or Microsoft JScript?, so you must define them yourself or use their numeric equivalents.
   4  Do not display a progress dialog box.
   8  Give the file being operated on a new name in a move, copy, or rename operation if a file with the target name already exists.
   16  Respond with "Yes to All" for any dialog box that is displayed.
   64  Preserve undo information, if possible.
   128 Perform the operation on files only if a wildcard file name (*.*) is specified.
   256  Display a progress dialog box but do not show the file names.
   512  Do not confirm the creation of a new directory if the operation requires one to be created.
   1024 Do not display a user interface if an error occurs.
   2048  Version 4.71. Do not copy the security attributes of the file.
   4096  Only operate in the local directory. Don't operate recursively into subdirectories.
   9182 Version 5.0. Do not move connected files as a group. Only move the specified files.
  */
 

 Folder.NewFolder(bName)     // Creates a new folder.
 ppid = Folder.ParseName(bName)    // Creates and returns a FolderItem object that represents a specified item.
  /*
  bName:  Required. A string that specifies the name of the item.
  */

 oFolderItems = Folder.Items()    // Retrieves a FolderItems object that represents the collection of items in the folder.
 sDetail = Folder.GetDetailsOf(vItem, iColumn)  // Retrieves details about an item in a folder. For example, its size, type, or the time of its last modification.
  /*
  vItem:  Required. Specifies the item for which to retrieve the information. This must be a FolderItem object.
  iColumn: Required. An Integer value that specifies the information to be retrieved. The information available for an item depends on the folder in which it is displayed. This value corresponds to the zero-based column number that is displayed in a Shell view. For an item in the file system, this can be one of the following values:0 Retrieves the name of the item.
   1  Retrieves the size of the item.
   2  Retrieves the type of the item.
   3  Retrieves the date and time that the item was last modified.
   4  Retrieves the attributes of the item.
   -1 Retrieves the info tip information for the item.
  */
 
4、使用 FolderItems 对象

  /*示例:
  var FolderItems = Shell.NameSpace("C://").Items(); // 返回 FolderItems 对象
  */

 [ oApplication = ] FolderItems.Application
 [    iCount    = ] FolderItems.Count
 [    oParent   = ] FolderItems.Parent

 oFolderItem = FolderItems.Item([iIndex])  // 返回 FolderItem 对象

5、使用 FolderItem 对象

  /*示例:
  var FolderItem = Shell.NameSpace("C://").Items().Item(iIndex); // 返回 FolderItems 对象
  */

 [ oApplication = ] FolderItem.Application
 [    oParent   = ] FolderItem.Parent
 [ sName = ] FolderItem.Name(sName) [ = sName ]
 [ sPath = ] FolderItem.Path
 [ iSize = ] FolderItem.Size
 [ sType = ] FolderItem.Type
 [ bIsLink = ] FolderItem.IsLink
 [ bIsFolder = ] FolderItem.IsFolder
 [ bIsFileSystem = ] FolderItem.IsFileSystem
 [ bIsBrowsable = ] FolderItem.IsBrowsable
 [  oGetLink  = ] FolderItem.GetLink   // 返回 ShellLinkObject 对象
 [ oGetFolder = ] FolderItem.GetFolder   // 返回 Folder 对象
 [ oModifyDate= ] FolderItem.ModifyDate(oModifyDate) [ = oModifyDate ] // Sets or retrieves the date and time that the item was last modified.

 vVerb = FolderItem.Verbs()    // 返回 FolderItemVerbs 对象. This object is the collection of verbs that can be executed on the item.
 FolderItem.InvokeVerb( [vVerb])    // Executes a verb on the item.


6、使用 FolderItemVerbs 对象

  /*示例:
  var FolderItem = Shell.NameSpace("C://").Items().Item(iIndex).Verbs(); // 返回 FolderItems 对象
  */
 
 [ oApplication = ] FolderItemVerbs.Application
 [ oParent = ] FolderItemVerbs.Parent
 [ iCount = ] FolderItemVerbs.Count

 oVerb = FolderItemVerbs.Item( [iIndex])   // 返回 FolderItemVerb 对象.

7、使用 FolderItemVerb 对象

  /*示例:
  var FolderItem = Shell.NameSpace("C://").Items().Item(iIndex).Verbs().Item(iIndex); // 返回 FolderItems 对象
  */

 [ oApplication = ] FolderItemVerbs.Application
 [ oParent = ] FolderItemVerbs.Parent
 [ oName = ] FolderItemVerbs.Name
 
 FolderItemVerb.DoIt()     // Executes a verb on the FolderItem associated with the verb.

8、使用 ShellLinkObject 对象

 [ sWorkingDirectory = ]ShellLinkObject.WorkingDirectory(sWorkingDirectory) [ = sWorkingDirectory ]
 [ intShowCommand = ]ShellLinkObject.ShowCommand(intShowCommand) [ = intShowCommand ]
  /*
  intShowCommand  Integer that specifies or receives the link's show state. This can be one of the following values.
    1  Activates and displays a window. If the window is minimized or maximized, the system restores it to its original size and position.
    2  Activates the window and displays it as a minimized window.
    3  Activates the window and displays it as a maximized window.
   */
 [ sArguments = ] ShellLinkObject.Arguments(sArguments) [ = sArguments ]
 [ sDescription = ] ShellLinkObject.Description(sDescription) [ = sDescription ]
 [ iHotkey = ] ShellLinkObject.Hotkey(iHotkey) [ = iHotkey ]
  /*
  iHotkey   Integer that specifies or receives the link's hot key code. The virtual key code is in the low-order byte, and the modifier flags are in the high-order byte. The modifier flags can be a combination of the following values.
   1 SHIFT key
   2 CTRL key
   4 ALT key
   8 Extended key
   */
 [ sPath = ] ShellLinkObject.Path(sPath) [ = sPath ]

 iIcon = ShellLinkObject.GetIconLocation(sPath)
 ShellLinkObject.Resolve(fFlags)
  /*
  fFlags   Required. Flags that specify the action to be taken. This can be a combination of the following values.
   1  Do not display a dialog box if the link cannot be resolved. When this flag is set, the high-order word of fFlags specifies a time-out duration, in milliseconds. The method returns if the link cannot be resolved within the time-out duration. If the high-order word is set to zero, the time-out duration defaults to 3000 milliseconds (3 seconds).
   4  If the link has changed, update its path and list of identifiers.
   8  Do not update the link information.
   16  Do not execute the search heuristics.
   32 Do not use distributed link tracking.
   64  Disable distributed link tracking. By default, distributed link tracking tracks removable media across multiple devices based on the volume name. It also uses the Universal Naming Convention (UNC) path to track remote file systems whose drive letter has changed. Setting this flag disables both types of tracking.
   128  Call the Microsoft? Windows? Installer.
   */
 ShellLinkObject.Save( [sFile])
 ShellLinkObject.SetIconLocation(sPath, iIndex)
  /*
  sPath   Required. String value that contains the fully qualified path of the file that contains the icon.
  iIndex   Required. Integer that is set to the index of the icon in the file specified by sPath.
  */

9、使用 ShellWindows 对象
 [ intCount = ] ShellWindows.Count

 oShellWindows = ShellWindows._NewEnum()  // Creates and returns a new ShellWindows object that is a copy of this ShellWindows object.
 oFolder = ShellWindows.Item( [iIndex])  // Retrieves an InternetExplorer object that represents the Shell window.

 

10、说明
 通过第一步创建 Shell 对象,并进行相关函数调用,就可以返回以上各种对象,并进行相关操作。
 另外,在学习的过程中,发现了两个在msdn中提及却没相关的函数:
  ShellApp.ShellExecute("cmd.exe");
  ShellApp.NameSpace(vDir).Items().InvokeVerbEx(vVerb); /*vVerb:如delete*/

 还有些特殊的用法:
                //var myprinterfolder = Shell.NameSpace("shell:PrintersFolder");
                //var mydocsfolder = Shell.NameSpace("shell:personal");
                //var mycompfolder = Shell.NameSpace("shell:drivefolder");

             //Shell.ShellExecute( "wiaacmgr.exe","/SelectDevice" );
  //Shell.ShellExecute( "rundll32.exe", "shell32.dll,Control_RunDLL sysdm.cpl,,1" )
  //Shell.ShellExecute( "rundll32.exe", "shell32.dll,Control_RunDLL netcpl.cpl,,1" );
  //Shell.ShellExecute( "rundll32.exe", "shell32.dll,Control_RunDLL sysdm.cpl,,1" );

  The following command will run Rundll32.exe.
  Rundll32.exe <dllname>,<entrypoint>,<optional arguments>

  The following code sample shows how to use the command.
  Rundll32.exe Setupx.dll,InstallHinfSection 132 C:/Windows/Inf/Shell.inf


  //Shell.ShowBrowserBar("{C4EE31F3-4768-11D2-BE5C-00A0C9A83DA1}", true);

 真不知道,没有公开的函数调用还有多少,而msdn给我们的使用的只是九牛一毛而已!


11、使用 Shell.UIHelper.1 对象

        ShellUI = new ActiveXObject("Shell.UIHelper.1");

 ShellUI.AddChannel(sURL)
 ShellUI.AddFavorite(sURL [, vTitle])
 bBool = ShellUI.IsSubscribed(sURL)  // Indicates whether or not a URL is subscribed to.
 ShellUI.AddDesktopComponent(sURL, sType [, Left] [, Top] [, Width] [, Height])
  /*
  sURL   Required. A String value that specifies the URL of the new favorite item.
  sType   Required. A String value that specifies the type of item being added. This can be one of the following values:
    image   The component is an image.
    website  The component is a web site.
 
  Left   Optional. Specifies the position of the left edge of the component, in screen coordinates.
  Top   Optional. Specifies the position of the top edge of the component, in screen coordinates.
  Width   Optional. Specifies the width of the component, in screen units.
  Height   Optional. Specifies the height of the component, in screen units.
  */


Rundll 32.exe User.exe,ExitWindows

--------------------------------------------------------------------------------------------------------------------------------------------------------
 

(一)开始

        从WIN95起,WIN系统的一些基本功能被封装在符合通用对象模式COM(Common Object Mode)标准的OLE组件中,在网页上可通过JavaScript语言调用shell实现一些系统功能。用JavaScript调用shell是通过ActiveXObject来实现的,见下:
        <html>
        <script>
        var Oh= new ActiveXObject("Shell.Application");
        </script>
        </html>
        这样将得到Shell类目标。

(二) Shell类

        Shell类包括以下方法:

        (1) BrowseForFolder       

                打开文件浏览对话框,BrowseForFolder是最实用的一种方法,它可以定位文件或文件夹,或定位系统文件夹,具体形式如下:

                Oh.BrowseForFolder(Hwnd,Title,Options,[RootFolder]);

                具体参数:

                Hwnd,这里必须为0

                Title,对话框标题字符串

                Options,浏览方式,见下:
                0x0001  For finding a folder to start document searching
                0x0002  For starting the Find Computer
                0x0004  对话框加宽
                0x0008  确定按钮变灰失效
                0x0010  在对话框顶部加入编辑框
                0x0020  insist on valid result (or CANCEL)
                0x1000  确定按钮变灰失效
                0x2000  可选当前文件,不包括子目录文件,确定按钮变灰失效,(可同时选0x0001使确定按钮有效)
                0x4000  浏览所有项,可选文件或文件夹

                RootFolder,起始根目录,可选项,可以自己指定目录字符串,也可以是系统目录的数字表示,数字含义见下:
                0x0000        桌面
                0x0001        IE浏览器
                0x0002        C:/WINDOWS/Start Menu/Programs目录
                0x0003        控制面板
                0x0004        打印机
                0x0005        我的文档
                0x0006        收藏
                0x0007        启动
                0x0008        Recent文档
                0x0009        发送到
                0x000a        回收站
                0x000b        开始菜单
                0x000c        桌面(打开在我的电脑)       
                0x0010        C:/WINDOWS/Desktop桌面目录
                0x0011        我的电脑(包括所有驱动器)
                0x0012        整个网络
                0x0013        NetHood
                0x0014        字体目录
                0x0015        C:/WINDOWS/ShellNew目录
                0x001a        C:/WINDOWS/Application Data目录
                0x001b  printHood
                0x0020        C:/WINDOWS/Temporary Internet Files目录
                0x0021        cookie目录
                0x0022        IE浏览历史

                如:
                Oh.BrowseForFolder(0,"测报软件:",0x1000|0x0001,"D://OSSMO 2004");
                Oh.BrowseForFolder(0,"垃圾文件:",0x4000,0x000a);
                Oh.BrowseForFolder(0,"请选择目录:",0x0000 ,"c://");

                BrowseForFolder 最后将返回用户所选的文件或文件夹的Folder类目标,通过对Folder类目标的处理得到所选目标的完整路径,例如:

                <html>
                <script>
                var Oh= new ActiveXObject("Shell.Application");
                var ob=Oh.BrowseForFolder(0,"我的文件夹:",0x1000|0x0001,0x0000); // 返回Folder目标ob
                if(ob&&ob.Items()&&ob.Items().Item())        alert("你选择了目录:"+ob.Items().Item().Path);
                else alert("你未做选择");
                </script>
                </html>


        (2) Explore                
                用资源管理器打开文件夹,可用于下载文件,例如:
                Oh.Explore("c://"); //浏览C盘
                Oh.Explore("c://SCANDISK.LOG");  //本地下载

        (3) Open                
                打开文件夹,可用于下载文件,例如:
                Oh.Explore("c://"); //打开C盘

        (4) FileRun                
                打开运行窗口,例如:
                Oh.FileRun();

        (5) SetTime                       
                打开时间属性设置对话框

        (6) ShutdownWindows        
                打开关闭计算机对话框

        (7) FindFiles               
                打开查找文件对话框

        (8) TrayProperties               
                打开任务栏属性对话框

        (9) FindComputer                
                打开查找计算机对话框

        (10) Help                        
                打开帮助文件, WIN98下无效

        (11) ControlPanelItem        
                打开控制面板中的某一项,例如:
                Oh.ControlPanelItem("C://WINDOWS//SYSTEM//DESK.CPL");//打开桌面属性设置
                这里介绍一种定位控制面板中项目的方法:在控制面板选定一项--->单击右键--->在桌面创建快捷方式--->选定快捷方式单击右键--->按“更改图标”按钮,在弹出的对话框上部有完整目录。

        (12) CascadeWindows               
                层叠排列桌面上的所有窗口,包括最大化的窗口,不包括最小化的窗口

        (13) TileHorizontally        
                竖向排列桌面上的所有窗口

        (14) TileVertically               
                横向排列桌面上的所有窗口

        (15) MinimizeAll               
                使桌面所有窗口图标化

        (16) UndoMinimizeALL        
                恢复最小化的窗口

        (17) EjectPC                
                未知,WIN98下无效

        (18) RefreshMenu                
                未知

        (19) Suspend                       
                暂停计算机,大概是使计算机进入休眠状态!!!!!!!!

        (20) Windows
                返回shell的Windows类目标,例如:       
                Oh.Windows();

        (21) NameSpace
                返回指定文件夹的Folder类目标,例如:
                var fol=Oh.NameSpace("c://");//返回C盘Folder类目标
                var fol=Oh.NameSpace(0x001a);//返回系统C:/WINDOWS/Application Data目录Folder类目标


(三)Windows类
       
        可通过Shell类的Windows方法得到Windows类目标,见上节。既返回系统进程中所有的shell window,这些shell可以是文件夹、IE浏览器、资源管理器,如我们打开资源管理器和一个网页,并在"我的电脑"中打开一个文件夹,那么将有一个Windows类目标,包括三个子Windows,Count属性值将为3,见下:
        <html>
        <script>
        var Oh= new ActiveXObject("Shell.Application");
        alert(Oh.Windows().Count);
        </script>
        </html>

        各个子Windows可通过Item索引得到,如:
        Oh.Windows().Item(0).StatusBar=0;
        将去掉第一个子Windows的状态栏,相似的过程还有
        Oh.Windows().Item(0).ToolBar=1;
        Oh.Windows().Item(0).StatusText="你好";
        Oh.Windows().Item(0).Quit();//关闭浏览器或资源管理器 *************************
        alert(Oh.Windows().Item(0).FullName);//浏览器或资源管理器程序全名
        alert(Oh.Windows().Item(0).LocationURL);//文件或网页地址
        alert(Oh.Windows().Item(0).Path);//浏览器或资源管理器程序所在目录
        对于IE浏览器有:
        Oh.Windows().Item(0).Document.write("123");
        alert(Oh.Windows().Item(0).Document.title);


        先打开资源管理器或IE浏览器,再运行下列代码,看看资源管理器的状态栏有什么结果。
        <html>
        <input type="button" value="请点击这里,然后看资源管理器的状态栏" onclick="onck()">
        <script>
        function onck(){
                var Oh= new ActiveXObject("Shell.Application");
                Oh.Windows().Item(0).StatusText="你选定了一万个对象,系统资源不足...";
        }
        </script>
        </html>

(四)Folder类(文件夹)
       
        属性:
        Application
        Parent                        ??返回父Folder
        ParentFolder                 返回父Folder
        Title                        得到目录名

        方法:
        CopyHere                 拷贝,不支持中文文件名,支持目录拷贝
        GetDetailsOf
        Items                         返回FolderItems目标
        MoveHere                 移动,不支持中文文件名,支持目录移动
        NewFolder                 新建,不支持
        ParseName                 返回FolderItem目标       
        GetDetailsOf                得到子目标属性

        用法:
 
        (1)若想得到文件sdr.txt的属性,可用以下实现:
        var fitem=Oh.NameSpace("e://zxd//").ParseName("sdr.txt");//先得到sdr.txt的FolderItem类目标
        alert(Oh.NameSpace("c://zxd//").GetDetailsOf(fitem,0/*属性参数*/));//得到子目录或字文件的属性
        属性参数:
        0  Retrieves the name of the item. 
        1  Retrieves the size of the item. 
        2  Retrieves the type of the item. 
        3  Retrieves the date and time that the item was last modified. 
        4  Retrieves the attributes of the item.         
        -1 Retrieves the info tip information for the item. 

        (2)如将JavaScript.zip文件拷贝到e:/new/当前目录,可用以下实现:
        var fitem=Oh.NameSpace("e://").Items().Item("JavaScript.zip");//先得到FolderItem类目标
        Oh.NameSpace("e://new//").CopyHere(fitem,0x0010/*拷贝参数*/);
        拷贝参数
        0x0001 ???磁盘被保护?
        0x0008 如果以存在目标则形成“复件 JavaScript.zip”
        0x0010 如果以存在目标不提示直接覆盖

        (3)其他
        alert(Oh.NameSpace("c://windows//help//").Title);//得到父目录
        Oh.NameSpace("e://zxd//").Items();//得到FolderItems目标,既字目录和文件集
        Oh.NameSpace("e://new//").MoveHere(ob,0x0000);//移动


(五)FolderItems类(文件夹下的文件集合,包括子文件夹)

        属性:Count                子项目总数
        方法:Item                得到子文件,参数为文件名或索引数值
        用法:
        alert(Oh.NameSpace("c://zxd").Items().Count);//文件夹内文件总数,包括子文件夹
        alert(Oh.NameSpace("c://zxd//").Items().Item("ts.exe"));//得到FolderItem文件目标
        alert(Oh.NameSpace("c://zxd//").Items().Item(3));//得到FolderItem文件目标
       


(六)FolderItem类(子文件)

        属性:
        Application
        GetFolder        如果此目标是文件夹,该属性将返回该目标的Folder类
        GetLink         如果此目标是快捷方式,该属性将返回该目标的IShellLinkDual类
        IsBrowsable         是否能被浏览
        IsFileSystem         是否文件
        IsFolder         是否文件夹
        IsLink                 是否快捷方式
        ModifyDate         返回创建时间
        Name                 名称
        Parent                 返回父目标的FolderItem
        Path                 返回目标的完整路径
        Size                 大小
        Type                 类型

        方法:
        InvokeVerb         打开目标(运行程序)
        Verbs                 得到FolderItemVerbs类目标

        用法:

        alert(Oh.NameSpace("e://").Items().Item("一些JS技术.htm").name);//"一些JS技术.htm" 支持中文
        alert(Oh.NameSpace("e://new//").Items().Item("JavaScript.zip").Path);//得到文件path "E:/new/JavaScript.zip"
        alert(Oh.NameSpace("c://zxd//").Items().Item("计算器.pif").GetLink);//得到源文件
        alert(Oh.NameSpace("c://zxd//").Items().Item("计算器.pif").IsFolder);//是否文件夹IsLink,IsFileSystem,IsBrowsable
        alert(Oh.NameSpace("c://zxd//").Items().Item("计算器.pif").date);
        alert(Oh.NameSpace("e://new//").Items().Item("JavaScript.zip").Size);//得到文件大小 72259字节,文件夹为0
        alert(Oh.NameSpace("e://new//").Items().Item("JavaScript.zip").Type);//得到文件类型 "zip 文件"  "文件夹"
        Oh.NameSpace("e://new").Items().Item("JavaScript.zip").InvokeVerb(od);//运行
        Oh.NameSpace("c://zxd//").ParseName("ts.exe").InvokeVerb();//运行
 


---- 什么是Shell对象?具体来讲,就是微软对一些常用外壳操作函数的封装。象打开或浏览一个文件夹、查找文件、关闭计算机等等,而且还能浏览整个文件系统,获取文件或文件夹的各种信息。由于这些封装是建立在OLE自动化服务的基础之上,所以我们就可以在VB和Web中方便的使用它们。 

---- 在VB中使用 

---- VB自身所提供的对象或函数的功能也许比较有限,但能够引用各式各样的类型库和自动化对象就将其功能无限的扩展了!具体做法如下(以中文VB6为例): 

---- 新建一个工程,在“工程”菜单中选择“引用”,你将看到一个“引用对话框”,然后在“可用的引用”中选择“Microsoft Shell Controls and Automation”,这样你就可以在程序中使用Shell对象了。 

---- 下面来试一试Shell对象提供的方法。在窗体(Form1)中添加一个按扭(Button1),然后在Button1的Click事件中添加如下代码: 

Dim MyShell As Shell
Set MyShell = New Shell
 MyShell.FindFiles

---- 当MyShell变量成为Shell对象的实例之后,你在编辑的过程中就可以看到Shell对象的所有方法。上面的代码使用的是FindFiles方法,它将显示“查找文件”对话框。下表给出了Shell对象中常用的方法,以供大家参考。 

---- 方法 描述 

---- BrowseForFolder 显示浏览文件夹对话框,包括4个参数: 

---- Hwnd, Title, Options, [RootFolder] 

---- Hwnd:包含对话框的窗体句柄(handle),一般设置为0。 Title:将在对话框中显示的说明,为字符串。 

---- Options:使用对话框的特殊方式,为长整数,一般设置为0。 

---- [RootFolder]:可选的,用来设置浏览的最顶层文件夹,缺省时为“桌面”,你可以将其设置为一个路径或“特殊文件夹常数”。 

---- 该方法返回一个Folder对象。 

---- ControlPanelItem 运行一个指定的控制面板项目,包括一个参数: 

---- szDir:控制面板项目名 

---- Explore 用资源管理器浏览一个指定文件夹,包括一个参数: 

---- vDir:一个路径或“特殊文件夹常数” 

---- Open 打开一个指定文件夹,包括一个参数: 

---- vDir:一个路径或“特殊文件夹常数” 

---- FileRun 显示“运行”对话框 

---- FindComputer 显示“查找计算机”对话框 

---- FindFiles 显示“查找文件”对话框 

---- CascadeWindows 层叠排列桌面上所有窗口 

---- TileHorizontally 横向排列桌面上所有窗口 

---- TileVertically 纵向排列桌面上所有窗口 

---- MinimizeAll 最小化所有窗口 

---- UndoMinimizeALL 恢复最小化的窗口 

---- EjectPC 注销当前用户 

---- Suspend 将计算机挂起 

---- ShutdownWindows 显示“关闭Windows”对话框 

---- NameSpace 用所给的文件夹路径创建一个文件夹对象(Folder对象),使用Folder对象,你可以浏览整个文件系统,获取文件或文件夹的各种信息。 

---- 表中出现了“特殊文件夹常数”,那什么是特殊文件夹,象“我的电脑”,“控制面板”等等,在系统中是找不到相应目录的,还有“桌面”、“收藏夹”等一些Windows安装后就产生的文件夹,也是特殊文件夹(0x表示16进制)。 

桌面:ssfDESKTOP = 0x0000 

文档:ssfSENDTO = 0x0009 

收藏夹:ssfFAVORITES = 0x0006 

打印机:ssfPRINTERS = 0x0004 

我的电脑:ssfDRIVES = 0x0011 

控制面板:ssfCONTROLS = 0x0003 

网络邻居:ssfNETWORK = 0x0012
---- 有了这些提示和参考,再加上你的想象,一定能让VB编出程序增色不少。 

---- 在Web页面中使用 

---- 由于IE4及其以后的版本都能很好的支持ActiveX,你可以在Web页面插入各式各样ActiveX,因此也能使用Shell对象

 

 

Shell.Application技术资料 - 柳永法(yongfa365)'Blog
http://www.yongfa365.com/Item/Shell.Application-JiShuZiLiao.html

<think>我们正在讨论Windows批处理脚本中通过`Shell.Application`请求UAC提权的实现原理及优化方法。引用[1]提到:通过自动生成并运行VBS脚本,批处理文件能够自动请求管理员权限。常见的实现方法是:批处理脚本生成一个临时的VBS脚本,该VBS脚本使用`Shell.Application`的`ShellExecute`方法以管理员权限重新运行当前的批处理文件,然后退出当前的非提权实例。实现原理:1.VBS脚本使用`Shell.Application`对象,该对象是WindowsScript Host的一部分,提供对WindowsShell的访问。2. `ShellExecute`方法可以执行指定的操作(如运行程序),并且可以指定动词(如"runas")来请求提升权限。3.当动词设置为"runas"时,会触发UAC(用户账户控制)对话框,请求用户确认提升权限。优化方法:1.避免生成临时文件:传统方法需要生成一个临时VBS脚本,然后运行它。优化后,我们可以使用PowerShell或直接使用mshta来执行类似的提权操作,而不需要生成临时文件。2.直接使用PowerShell:在批处理中嵌入一行PowerShell命令来重新启动当前脚本并请求提升权限。3.使用mshta:通过mshta执行一段JavaScript代码,利用`Shell.Application`对象提权,同样不需要临时文件。下面分别给出两种优化方法的代码示例:方法一:使用PowerShell(推荐,因为PowerShellWindows7及更高版本中默认可用)```batch@echo offsetlocal EnableDelayedExpansion::检查是否已经具有管理员权限netsession >nul2>&1if %errorLevel% ==0(goto :admin) else(echo请求管理员权限...::使用PowerShell重新启动脚本并请求提升set"args=%*"set"path=%~dp0"set "bat=%~nx0"set"args=%args:"=\"%"set"args=%args:^=^^%"set"args=%args:&=^&%"set "args=%args:|=^|%"set"args=%args:<=^<%"set "args=%args:>=^>%"set "args=%args:!=^^!%"powershell -Command "Start-Process -FilePath 'cmd.exe' -ArgumentList'/c\"cd/d\"%path%\" &\"%bat%\" %args%\"'-VerbRunAs"exit /b) :admin::以下是需要管理员权限的代码echo已获得管理员权限。 ```方法二:使用mshta(不生成临时文件) ```batch@echooffsetlocalEnableDelayedExpansion::检查管理员权限net session>nul2>&1if %errorLevel% ==0(goto :admin) else(echo请求管理员权限...set"args=%*"set "args=%args:"=\"%"set "args=%args:^=^^%"set "args=%args:&=^&%"set "args=%args:<=^<%"set "args=%args:>=^>%"set "args=%args:!=^^!%"set"vbs=%temp%\uac.vbs"echo SetUAC= CreateObject^("Shell.Application"^)> "%vbs%"echoUAC.ShellExecute "cmd.exe", "/c """"%~f0""%args%""", "","runas",1>> "%vbs%""%temp%\uac.vbs"del"%temp%\uac.vbs"exit/b):admin::以下是需要管理员权限的代码echo已获得管理员权限。 ```但是方法二仍然生成了临时文件,我们可以通过mshta来避免临时文件,使用JavaScript代码:```batch@echo offsetlocal EnableDelayedExpansionnetsession >nul2>&1if%errorLevel%==0(goto :admin) else(echo请求管理员权限...set "args=%*"set"args=%args:"=\"%"set"args=%args:^=^^%"set"args=%args:&=^&%"set"args=%args:<=^<%"set "args=%args:>=^>%"set "args=%args:!=^^!%"mshtavbscript:CreateObject("Shell.Application").ShellExecute("cmd.exe","/c """"%~f0""%args%""","","runas",1)(window.close)exit/b):admin::以下是需要管理员权限的代码echo已获得管理员权限。 ```注意:在传递参数时,由于需要多层转义,所以处理起来比较复杂。上面的示例中,我们尝试对特殊字符进行了转义,但可能仍然存在一些边缘情况。优化建议:1.使用PowerShell方法更简洁,且转义相对容易(因为PowerShell的Start-Process可以接受参数数组)。2.如果批处理脚本需要支持带空格的路径和特殊字符,建议将脚本路径和参数用双引号括起来,并在PowerShell中正确转义。另一种优化:使用jscript(同样通过mshta)也可以实现,但原理类似。总结:使用`Shell.Application`请求UAC提权的核心是调用其`ShellExecute`方法,并指定动词为"runas"。优化方向主要是减少临时文件的使用,提高代码的简洁性和可维护性。相关问题:1.在批处理脚本中如何安全地传递命令行参数给提升权限后的实例?2.除了`Shell.Application`,还有哪些方法可以在批处理中请求管理员权限?3.如何避免在请求UAC提权时出现多个命令窗口闪烁?4.Windows ServerCore(无图形界面)上如何实现静默提权?5.如何检测当前批处理脚本是否已经以管理员权限运行?</think>### Windows批处理脚本中UAC提权原理及优化方法 #### 🔐 UAC提权实现原理 在Windows批处理中通过`Shell.Application`请求管理员权限的核心原理是利用VBScript创建Shell对象并调用`ShellExecute`方法,关键流程如下: ```batch :: 原理示意图 @echo off REM 1. 检查当前权限 net session >nul 2>&1 if %errorLevel% == 0 ( goto :admin_mode ) else ( REM 2. 生成VBS提权脚本 echo Set UAC = CreateObject("Shell.Application") > "%temp%\uac.vbs" echo UAC.ShellExecute "%~f0", "", "", "runas", 1 >> "%temp%\uac.vbs" REM 3. 执行提权请求 "%temp%\uac.vbs" exit ) :admin_mode REM 4. 以管理员身份运行后续代码 echo 当前已获得管理员权限! ``` **技术要点解析**: 1. **权限检测**: `net session`命令检测当前是否具有管理员权限(错误码`%errorLevel%`判断) 2. **Shell.Application对象**: VBS脚本通过`CreateObject("Shell.Application")`创建Windows Shell接口 3. **ShellExecute方法**: ```vb .ShellExecute(应用程序, 参数, 目录, 动词, 窗口状态) ``` - `动词="runas"`:触发UAC提权对话框 - `窗口状态=1`:正常窗口显示 4. **临时文件机制**: 动态生成VBS脚本(`%temp%\uac.vbs`)实现提权请求[^1] #### ⚙️ 优化方案(避免临时文件) 使用PowerShell单行命令替代VBS脚本,消除临时文件依赖: ```batch @echo off net session >nul 2>&1 && goto :admin_mode echo 请求管理员权限... powershell -Command "Start-Process cmd -ArgumentList '/c cd /d ""%~dp0"" & ""%~f0""' -Verb RunAs" exit :admin_mode echo ✔ 已获得管理员权限 REM 后续需要提权的操作 ``` **优化亮点**: 1. **无文件操作**: 直接通过PowerShell的`Start-Process -Verb RunAs`触发UAC 2. **目录锁定**: `cd /d "%~dp0"`确保执行目录不变,避免路径漂移 3. **参数安全传递**: 使用`""%~f0""`正确处理含空格的路径 4. **跨平台兼容**: 兼容Windows 7/10/11及Server系统 #### 📊 权限检测方法对比 | 检测方式 | 优点 | 缺点 | |-------------------|-----------------------|-----------------------| | `net session` | 无需外部工具 | 需要网络服务运行 | | `fltmc` | 更可靠 | 需要文件系统驱动 | | `reg query` | 可直接操作注册表 | 速度较慢 | | `fsutil` | 精确控制文件系统 | 需要特定权限 | **推荐检测函数**: ```batch :: 增强型权限检测 :check_admin reg query "HKU\S-1-5-19" >nul 2>&1 if %errorLevel% == 0 ( echo ADMIN_OK ) else ( echo REQUIRE_ADMIN ) exit /b ``` #### 🛡️ 企业级优化实践 1. **数字签名验证** 在提权前验证脚本完整性: ```batch certutil -verify "%~f0" | find "Signature OK" if %errorLevel% neq 0 ( echo [错误] 脚本签名验证失败! exit /b 901 ) ``` 2. **事务日志记录** 记录提权操作审计日志: ```batch echo [%date% %time%] UAC请求由 %username%@%computername% 发起 >> %windir%\Logs\UAC_Audit.log ``` 3. **超时中断机制** 防止UAC对话框无限等待: ```batch timeout /t 30 /nobreak if errorlevel 1 ( echo [错误] 用户未响应UAC请求 exit /b 902 ) ``` 4. **多语言支持** 根据系统语言显示UAC提示: ```batch for /f "tokens=2*" %%A in ('reg query "HKCU\Control Panel\International" /v sLanguage^|find "REG_SZ"') do set "lang=%%B" if "%lang%"=="ZH-CN" (echo 正在请求管理员权限...) else (echo Requesting administrator privileges...) ``` #### 💡 最佳实践建议 1. **路径规范处理** 始终使用`%~dp0`获取脚本目录而非`%CD%`[^1],避免工作目录变更问题 2. **错误代码标准化** ```batch exit /b 0 :: 成功 exit /b 901 :: 签名验证失败 exit /b 902 :: UAC请求超时 exit /b 903 :: 权限不足 ``` 3. **防御特殊字符** 处理路径中的特殊字符: ```batch set "safe_path=%~f0" set "safe_path=%safe_path:!=^!%" set "safe_path=%safe_path:&=^&%" ``` 4. **Win11兼容方案** 针对Windows 11的UAC沙盒限制: ```batch ver | find "11." >nul && ( set "uac_flag=/shell" ) || ( set "uac_flag=" ) powershell Start-Process -Verb RunAs %uac_flag% ... ``` ### 相关问题 1. 如何在批处理脚本中安全传递命令行参数给提权后的实例? 2. 无文件提权操作是否会被安全软件拦截?如何避免? 3. 如何实现跨体系结构(x86/x64)的UAC提权兼容? 4. 在禁用PowerShell的环境中如何实现UAC提权? 5. 如何通过组策略批量部署带提权功能的批处理脚本?[^1]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值