中国DOS联盟论坛

中国DOS联盟

-- 联合DOS 推动DOS 发展DOS --

联盟域名:www.cn-dos.net  论坛域名:www.cn-dos.net/forum
DOS,代表着自由开放与发展,我们努力起来,学习FreeDOS和Linux的自由开放与GNU精神,共同创造和发展美好的自由与GNU GPL世界吧!

游客:  注册 | 登录 | 命令行 | 搜索 | 上传 | 帮助 »
作者:
标题: 自己很乱的powershell学习笔记 上一主题 | 下一主题
tempuser
高级用户





积分 547
发帖 261
注册 2006-4-15
状态 离线
『楼 主』:  自己很乱的powershell学习笔记

迷迷糊呼的学了一些,还是不知所措,不知哪位朋友有入门的清晰感觉,共研之! 学习疑问: 1. 如何任意显示某个对象的method并使用它呢(已结)? 2. 获取可卸载程序的命令行字卸载符串该怎么在powershell中使用呢? 一. PowerShell常用快捷键 F7 :显示曾经输入的命令历史记录,用上下箭头可逐个选定再次执行。 ALT+F7 :清除命令历史记录。 ESC :清除当前输入的所有字符。 CTRL+END :清除从光标到行尾的内容。 CTRL+C / CTRL+BREAK :终止命令的执行。 ↑ :向上查询历史命令。 ↓ :向下查询历史命令。 二. 资源列表 1.www.powershell.com :可下载powershell plus工具,比微软提供powershell工具方便,后者没有联想功能。 2.forums.microsoft.com\china 3.PowerShell网志:vista.itech.net 4.安装PowerShell: www.microsoft.com/downloads 5. PowerShellPowerShell 开发组博克blogs.msdn.com/PowerShell/ 6. PowerShell新闻组Microsoft.Public.Windows.PowerShell 7. 脚本中心 www.microsoft.com/technet/scri ... 8. 三. 什么是PowerShell PowerShell是系统管理和脚本语言发展的未来。 它是微软提供的命令行界面的交互式Shell环境(新一代命令解析器)和脚本语言,使命令行用户和脚本编写者(通过对COM对象的编写来实现众多功能)都可以利用.NET FrameWork的强大功能(如.NET FrameWork的类库---FCL),帮助管理员完成弹性化和自动化的工作。 PowerShell是构建于.NET上的,所以安装需要.NET FrameWork v2.0的支持。 PowerShell是基于对象的,命令的输出即位对象。 PowerShell安装在%systemroot%\system32\下 四. PowerShell的变量与参数 Powershell中的变量应理解为对象,而非文本。 定义变量的符号:$ 。如定义变量var用$var。为变量赋值$var = 123 $var1 = abd。还可以将变量嵌入到变量中去,如$var2 = “$var $var1”,$var2的值是 123 abd,如果是$var2 = ‘$var $var1’,则$var $var1被当成字符串赋给了$var2。记住单引号和双引号的区别。 对于数据类型可以不定义和声明。 查看所有变量:get-variable 查看对变量可操作的命令集:get-command –noun varibale 常用系统变量:$pshome $home $profile 变量的四种模式:local script global private。 例:对环境变量的相应操作 Get-childitem env: 例:对环境变量的具体引用 $env:os #说明CMD.EXE中的系统环境变量仍然可在powershell中使用 - :参数引导符,比如有一参数Name,则书写时必须是 -Name 通用参数包括:WhatIf Confirm Verbose Debug Warn ErrorAction ErrorVariable OutVariable OutBuffer,它们都是由powershell引擎控制的,每次cmdlet 实现这些参数时,它们的行为始终相同。 -Syntax :获得cmdlet的语法,如get-process –syntax 重要参数说明 -noun 可以获得影响同一类型对象的一系列命令 -passthru 可以看到命令的执行过程 -whatif 可以预览命令可能导致的后果,该参数可以实现对prototype原型模式的引用,不是每个cmdlet都可以使用该参数的. -credential 指定用户帐户名称 -eq 等于运算符,加I –ieq表示不区分大小写比较;-ceq 区分大小写比较。 五.PowerShell的cmdlets与技巧 cmdlets命名规则:[动词-名词] 单个的cmdlets只能完成单任务,要完成复杂的任务必须通过管道 | 来完成。| 除了完成前1个cmdlets的执行结果到下1个cmdlets的传递作用,还起到命令的连接作用,即命令可以分行书写,便于阅读。 | :是并发执行的。 Aliases :别名。如gps=get-process sort=sort-object ft=format-table,可自定义命令的别名,命令为Get-Alias -Name gi -Value Get-Item,注意,系统自定义的别名如gi gcm scm等不能被更改。 命令缩写:为便于记忆,Set用S,Get用G,Item用I,Command用CM。如get-command=gcm;get-wmiobject=gwmi etc. Get-command :获得所有可用的cmdlets,注意不包括aliases function script等。 例:想获得alias/ function /script命令的详细信息 get-command –commandtype alias/function/externalscript get-aliases :获得所有命令的aliases。 get-help :获得帮助。 例:获得命令的帮助信息和它的语法 get-help –name get-command –full/-detail -syntax #-name :可以省略 get-process -? 例:help或man分屏显示命令的帮助信息 help get-service 或 man get-service 例:利用more函数来分屏显示 get-process | more #more也可以读取文件的内容分屏显示,如more c:\test.txt 例:显示概念性主题的帮助信息 get-help about_* #about_ :表示概念性主题的前缀 get-help about_where #显示特定概念主题 where 的帮助信息 例:get-command *_service #获得有关service操作的cmdlets #_可以去掉,写成*service,但不能去掉*,写成get-command service,会出错的! 例:获得影响同一对象类型的一系列命令 get-command –noun service #-noun :该参数可获得影响同一对象类型的一系列命令,类似get-command *service 例:get-service | get-member #如果要充分了解get-service的对象结构,可通过|将该命令输出到get-member上 例:获得某命令输出对象的某些 get-process –name powershell | format-table –property processname,fileversion,starttime,name,id,company,path –autosize -wrap –groupby company # -property 对于获取输出对象的信息很有用! # -autosize表示自动调整列宽 # -wrap表示显示不下的列自动换行 #-width 2147483647防止表格因宽大而被截断 # -groupby用于控制表格输出,基于指定的属性值分组,易于显示很大的难于显示的表 # -autosize和-wrap连用显示效果不错,但很消耗系统资源,建议将宽度比较小的#property如name放到最后比较好 #如果想显示所有property可用*表示 # 例:获得某服务/进程的具体信息 get-service –name alerter/get-process -name powershell 例:列出动词get的所有命令 get-command –verb get #verb :参数的意思 例:列出当前目录下的文件夹和文件 get-childitem #get-childitem c:\ 列出C盘下的目录和文件 #get-childitem c:\ | out-host 将C盘下的目录和文件输出到屏幕上,如果输出信息很多,该操作很消耗CPU和内存,可通过-paging参数来单屏输出。 #out-null 屏蔽输出;out-printer 打印输出 例:输出控制命令format-wide/format-list/format-table/format-custom 例:输出控制命令out-host/out-null/out-printer/out-file -Encoding ASCII –width 2147483647 get-process | format-table | out-file –filepath c:\test.txt #将get-process输出到c:\test.txt上 #注意out-file默认将创建unicode, -Encoding ASCII是将文件改为ASCII,便于使用 #ASCII文件的工具处理输出 #-width 2147483647防止表格因宽大而被截断 例:要查看get-process的对象结构 get-process | get-member | out-host –paging 例:要查看get-process的对象结构中某一类型信息 get-process | get-member –membertype property # MemberType 允许使用以下值:AliasProperty、CodeProperty、Property、NoteProperty、ScriptProperty、Properties、PropertySet、Method、CodeMethod、ScriptMethod、Methods、ParameterizedProperty、MemberSet 和 All。 探索发现 Get-Help, Get-Command Get-Member :查看“对象的结构”,很重要。 面向对象的小命令 Compare, Group, Measure, Select, Sort, Tee, Where 格式控制 Format-(Custom, List, Table, Wide) 面向任务的命令 进程:get/stop(-process) 系统服务:get/start/stop/suspend/resume/restart(-service) 事件日志:get-eventlog CLI(命令行接口)中的主要命令(????---不理解---??????) – Shell Functions (CLI 可用代码) – PowerShell Scripts (.PS1) – Native commands (.EXE, .BAT, etc.) 使用Whanif预览执行结果:比如关闭某进程会对系统产生影响,就用它先预览一下。 $? :测试命令的执行成功与否。 重点: 并不是所有符合“动词-名词”命令规范都是PowerShell的cmdlet,例如clear-host,它是power-shell的内部函数。可通过get-command –name clear-host来判定其commandtype是function还是cmdlet。 除了cmdlet是PowerShell内置命令外,aliases function scirip 可执行文件和已注册文件类型处理程序的外部文件都归于powershell的命令。 PowerShell中的命令没有联想功能,但可通过TAB来扩展,条件是输入“动词+连字符-”之后,按TAB键就会自动找第一个匹配的命令,如果不是需要的,可再通过TAB来完成”。 六.对文件系统操作的命令 get-location #获得当前目录 set-location –path c:\ #将当前目录更改为c:\,但没有任何过程提示 set-location -path c:\ -passthru ##将当前目录更改为c:\,有过程提示 set-locaiton \\server\共享目录 #server远程服务器 push-location -path “local settings” #将当前目录压入堆栈,并将目录转到local settings下 push-location -path temp #将当前目录压入堆栈,并将目录转到temp pop-location -passthru #恢复被压入堆栈的目录,可通过它弹出最近使用过的目录 cd –path hkcm:\software #将当前目录改为hkcm:\software powershell用名词 项 表示驱动器下的内容,如果上文件系统驱动器,则项可以是“文件夹 或 文件 或 powershell的驱动器”。 对项常用操作命令:new-item rename-item copy-item remove-item invoke-item invoke-item :执行项,它是有注册表中默认应用程序的处理程序(类似关联程序) 例:invoke-item c:\1.txt # 调用notepad.exe打开1.txt,因txt默认关联程序是notepad.exe invoke-item c:\windows # 等同于“双击打开windows目录”,关联资源管理器 invoke-item c:\test.bat # 执行bat 例:新建1.txt #new-item –path c:\1.txt –itemtype file/directory 例:将C盘下的1.txt重命名为D盘下的2.txt rename-item –path c:\1.txt d:\2.txt # 该命令错误,因为rename不能将目录移动,只能在本目录下重命名 # 正确:move-item –path c:\1.txt –destination d:\2.txt –passthru #可看具体移动过程 例:copy某目录 copy-item –path c:\new –destination c:\temp # 注意,如果new下有内容,则内容是无法拷贝到temp下,不加参数只复制容器 copy-item –path c:\new –destination c:\temp –recurse –force –passthru # -recurse表示将容器内的内容也拷贝过去 例:删除某目录 remove-item –path c:\temp –recurse # 如果没有-recurse,删除目录需要确认 # 在不同命令下,-recurse有不同含义 get-command –noun item #获得项的所有操作命令 get-childitem :用来枚举“文件夹/文件/注册表”的。 例:set-location [-path] c:\windows get-childitem [–name[ [-force[ get-childitem -recurse #将当前目录定位到c:\windows # 枚举当前目录下所有的文件(夹),但不包括子文件夹 # -name表示按名称筛选,即只显示文件名 # -force表示显示隐藏文件夹 # -recurse表示枚举目录下所有的文件(夹),包括所有子文件夹和子文件夹下的文件 如果需要更好的筛选,可以使用 –exclude -include 例:查找\system32下的WINDOWS时间服务的DLL,它是w开头,中间有32字样 get-children –path c:\windows\system32\w*32*.dll –recurse –exclude *[9516]*.dll # 使用-exclude *[9516]*.dll是为了排除与“win95或16位windows兼容的DLL # 但是我在自己的机器上没有使用-exclude也没有显示有关与“win95或16位windows # 兼容的DLL,我想这根windows的使用环境有关,设计语句毕竟要严谨和考虑全面 例:get-childitem –path c:\windows\*.dll –recurse –exclude [a-y]*.dll #该语句不会返回任何结果,因为[a-y]*.dll中的通配符会排除所有DLL #get-childitem –path c:\windows –include *.dll –recurse –exclude [a-y]*.dll 通配符 * ? 和[ ] 其中[ ] 表示阔住匹配的字符 例:get-childitem [-path] c:\windows\[xz]* #表示枚举出c:\windows目录下所有以x或z打头的文件 例:get-childitem [-path] c:\windows\?????.log #表示枚举出c:\windows下所有5个任意字符的log文件 七.WMI对象操作 WMI是系统管理的核心技术。WMI类描述可管理的资源,很多类有很多属性。 get-wmiobject –list [–computername name/ip] #获得本地或远程可用的WMI类资源 默认下get-wmiobject使用root/imv2命名空间,如果需要指定命名空间,必须使用-namespace 例:get-wmiobject –list –computernaem 192.168.1.1 –namespace root 例:具体使用某个WMI类win32_operatingsystem get-wmiobject –class win32_operatngsystem –namespace root –computername # 自己写的命令,错误在win32_operatngsystem少了i,root应root/cimv2 get-wmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 –ComputerName . # . 表示WMI的样式,代表计算机名称 # 如get-wmiobject没有参数,默认第一个参数是class;参数namespace默认命名空间 # 是root/cimv2;针对本地操作参数computername可以省略 #该命令行可简写get-wmiobject win32_operatingsystem 可查看类的更多属性 get-wmiobject win32_operatingsystem | get-member –membertype property 查看非默认属性 get-wmiobject win32_operatingsystem | Format-Table -Property TotalVirtualMemorySize,TotalVisibleMemorySize,FreePhysicalMemory,FreeVirtualMemory,FreeSpaceInPagingFiles 利用通配符缩写 get-wmiobject win32_operatingsystem | Format-table –Property total*,free* #将table改为list,增强结果可读性 利用where-object cmdlet管道筛选对象(利用比较运算符来进行) 在管道中,用 $_ 表示管道中的对象;用-表示比较运算符的前缀;用{}括住脚本块;用参数-filterscript进行过滤。 例:Get-WmiObject -Class Win32_SystemDriver | Where-Object -FilterScript {$_.State -eq "Running"} | Where-Object -FilterScript {$_.StartMode -eq "Manual"} | Format-Table -Property Name,DisplayName,pathname 该语句等同于 Get-WmiObject -Class Win32_SystemDriver | Where-Object -FilterScript { ($_.State -eq "Running") -and ($_.StartMode -eq "Manual") } | Format-Table -Property Name,DisplayName 使用foreach-object cmdlet 对多个对象实施重复操作 例:Get-WmiObject -Class Win32_LogicalDisk | ForEach-Object -Process {($_.FreeSpace)/1024.0/1024.0} 使用select-object对对象进行选择 例:get-wmiobject –class win32_logicaldisk | select-object –property name,freespace | get-member 使用sort-object排序 例:get-wmiobject –class win32_systemdriver | sort-object –property state,name | format-table –property name,state,started,displayname –autosize #对format-tabel中输出的state和name property排序 #descending倒序排序 五. .NET对象的操作 一些组件有.NET Framework和COM接口,powershell允许使用这些组件来扩展和增强系统管理工作 .NET Framework是一个类库,包含很多类,如System.Diagnostics.EventLog,该类可管理事件日志。 例:$applog=new-object –typename system.diagnostics.eventlog –argumentlist application,computername/ip #将对象存储在变量中,便于调用 #没有-argumentlist,能建日志,但为空,加上参数就能建立对特定日志的管理 #输入变量$applog就可以看到日志个数 #–argumentlist application将application作为参数传递给参数-argumentlist,起到构造函数 #作用 # computername/ip访问远程日志 get-eventlog :查看日志 例:获得对象的方法 / 属性 $application | get-member –membertype method/property #其中获得一个方法为 clear 清除日志信息 $application.clear() #()必须加,clear()表示method,为了区分同名的property 例:查看applicatio最新的三个日志 get-eventlog –logname application –newest 3 #日志类型还有system security 八..COM(组件对象模型)对象的操作 COM组件包括WSH包含的库和Active X应用程序,new-object可以操作这些组件 New-object –comobject wscript.shell #创建COM对象 # 还可创建WScript.Network、Scripting.Dictionary 和 Scripting.FileSystemObject 例:利用COM对象创建快捷方式 $shorcut=new-object –comobject wscript.shell #创建COM对象并将其保存到变量中 $shorcut | get-member #获得对象的操作方法,其中包括createshortcut $net=$shorcut.createshortcut(“c:\test.url”) #为建立的快捷方式建立 存放路径和名称 #注意,别落了后缀.url,还可以是.lnk,根据需要;另外记住()是紧跟着的 $net.targetpath=”10.*.*.*” #为建立的快捷方式建立内容映射,因为是.url,所以映射的是一个网址 $net.save() #存储快捷方式,不存是不会创建成功的 例:利用COM对象启动一个IE实例 单独运行的COM对象被称做Active X 可执行程序。 $ie=New-object –comobject internetexplorer.application #利用internetexplorer ProgID即internetexplorer.application建立一个IE实例 #该进程是独立运行的 Get-process #以上建立的IE实例不可见,但通过进程可以查看到iexplore $ie.visible=$true #使IE实例可见 $ie.navigate(“www.sohu.com”) #使用navigate导航到特定网址 $ie.document.body.innertext #网页中检索文本内容 $ie.quit() #关闭IE $ie | get-member #关闭IE后,该变量失效,可通过get-member检验 $ie=$null #清除剩余变量的引用 Remove-variable ie #彻底清除该变量 例:建立非标准的COM对象 New-object –comobject excel.application –strict # -strict创建非标准的COM对象 因为get-member有可选参数 –inputobject,所以$shorcut | get-member可改写为 get-member –inputobject $shorcut 注意,-inputobject会将参数视为单独项,所以如果有多个对象存储在变量中,则 -inputobject会把它们当成对象数组。 八.静态类 静态类:不是所有.NET FrameWork类都可以使用new-0bject的,静态类中的属 性和方法是固定的,只可以引用,被能被修改,如System.Environment和System.Math。 因此,new-object system.environment是错误的。 静态类的属性也是静态的,对静态类的静态属性是通过::来引用的。 例:如何查看system.environment的静态属性 [environment] | get-member –static #注意,有-static和没有-static显示内容是不同的 #有-static则显示system.environment的静态属性 #没有显示system.environment的runtimetype #[environment] | get-member –membertype property并不能显示静态属性 #之所以写[environment]没有写成[system.environment]是因为system是默认的可省略 例:静态属性的应用 [environment]::osversion 静态类system.math有一些method是相同的,可通过参数区分它们。 [math] | get-member –static –membertype method 例:[math]::sqrt(9) 八.powershell的提供程序和驱动器 提供程序将powershell和驱动器中间的访问数据层抽象化,从而使在统一的机制下与不 同的驱动器进行交互。但实际上,我们并不感觉到提供程序的存在。 Get-help –category provider #获得所有提供程序类型。 用名词PSDrive命名powershell驱动器的名称。 驱动器分四种: filesystem文件系统驱动器:如 C: D: registry注册表驱动器: 如 HKLM: HKLU: certificate证书驱动器:如 CER: Env驱动器(环境变量驱动器):Env: Variable驱动器(变量驱动器): 自定义驱动器:条件有三,1。驱动器的名称;2。Psprovider;3。Root既驱动器对应路 径。例 New-PSDRIVE -name zgktest –psprovider registry –root hklm\software\microsoft\windows\current。进入该驱动器命令 cd zgktest: 或set-location zgktest: -passthru,查看该驱动器下内容命令 dir 。 get-psdrive:获得所有驱动器列表 get-psdrive –psprovider certificate :获得指定的证书驱动器 # -psprovider :就是指定提供程序,记住别落了ps remove-psdriver –name drivername :删掉指定的驱动器 powershell的驱动器为powershell 自用,用“资源管理器和cmd.exe”是打不开powershell的驱动器的。 powershell退出,新定义的驱动器会消失。可通过export-console 命令将新定义的控制台导出,然后通过参数psconsolefile将其导入到新会话中。 六. PowerShell的脚本执行策率 powershell的执行策率分四种:Restricted,默认,禁止所有脚本执行;AllSigned,仅运行可信任脚本;RemoteSigned,所有本地脚本可执行,不管它们是否是可信任,如果是从Internet下载的脚本则必须是可信任的;UnRestricted,所有脚本都可以执行。 更改策率命令:set executionpolicy remotesigned,将默认策率由restricted改为remotesigned。 Makecert.exe :制作可信任的安全脚本(微软提供)。 利用makecert.exe制作可信任脚本步骤: 1.创建信任证书:makecert -n "CN=MyRoot" -a sha1 –eku1.3.6.1.5.5.7.3.3 -r -sv root.pvk root.cer –ss Root -sr localMachine 2.导出信任证书:makecert -pe -n "CN=MyCertificate" -ss MY –a sh1 -eku 1.3.6.1.5.5.7.3.3 –iv root.pvk –c root.cer 3.用信任证书对脚本进行信任签名:Set-AuthenticodeSignature D:\myscript.ps1 $cert 七. 语法与操作 get-member:获得属性与方法。例:$var1 | get-member 获得$var的属性和方法。$var.[TAB] 用TAB键选择变量的属性和方法。 定向输出:用 “ > ”表示。 注释 :用“ # ”表示。 引号 :注意“单 双”引号的区别。 八. PowerShell对IIS 的管理 需要iis powershell provider插件的支持。 powershell对IIS7管理更好,对IIS6管理相对较弱,只能做一些start/stop iis 的操作。 常用语法:start-webitem stop-webitem get-webitemstate .创建Web站点 New-Item iis:\Sites\TestSite -bindings @{protocol="http";bindingInformation=":80:TestSite"} -physicalPath c:\test #New-item iis:\Site\TestSite –bindings :新建站点TestSite,并实施绑定 # protocol=”http” 使用http协议 #bindinginfomation=”;80:TestSite” 将80端口映射到站点TestSite # physicalPath c:\test :站点的物理路径是c:\test • 创建Web应用程序 New-Item 'IIS:\Sites\Default Web Site\DemoApp' -physicalPath c:\test -type Application #type Application :类型是应用程序 九. PowerShell如何实行对系统进行管理 重要命令:get-process和stop-process;get-service 例:停止所有无响应的程序 Get-Process | Where-Object -FilterScript {$_.Responding -eq $false} | Stop-Process 例:停止所有其它windows powershell对话 Get-Process -Name powershell | Where-Object -FilterScript {$_.Id -ne $PID} | Stop-Process - PassThru 例:挂起一个服务spooler Suspend-service –name spooler 例:重新启动多个服务 Get-Service | Where-Object -FilterScript {$_.CanStop} | Restart-Service #先获得服务列表,并对它们进行筛选,然后执行重新启动 Get-wmiobject是进行常规系统管理最重要的命令。 例:收集本地计算机桌面相关信息 Get-WmiObject -Class Win32_Desktop -ComputerName .| Select-Object -Property [a-z]* #wmi类列出的信息很详细,其中还包括“以双下划线表示的wmi元数据” #可通过select-object进行筛选 #-computername可以省略的,后面的 . 代表本地计算机名称 例:收集BIOS信息 Get-wmiobject –class win32_bios 例:收集CPU信息 Get-wmiobject –class win32_processor Get-WmiObject -Class Win32_Processor -ComputerName .| Select-Object -Property [a-z]* et-WmiObject -Class Win32_ComputerSystem -ComputerName .| Select-Object -Property SystemType #得到处理器系列的一般说明字符串 例:列出计算机制造商和型号 Get-wmiobject –class win32_computersystem 例:获得登陆到计算机的用户 Get-wmiobject –class win32_computersystem –property username | select-object –property username #select-object –property username精简输出内容 例:列出已打补丁信息 Get-wmiobject –class win32_quickfixengineering –property hotfixid #-property hotfixid更有目的的筛选 Get-WmiObject -Class Win32_QuickFixEngineering -ComputerName .-Property Hot FixId | Select-Object -Property HotFixId # 上面语句还会返回其它数据,通过Select-Object -Property HotFixId进一步缩小范围 例:列出所有用户和所有者 Get-WmiObject -Class Win32_OperatingSystem -ComputerName .| Select-Object -Property NumberOfLicensedUsers,NumberOfUsers,RegisteredUser 精简为 Get-WmiObject -Class Win32_OperatingSystem -ComputerName .| Select-Object -Property *user* 例:列出磁盘空间和剩余空间 Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" -ComputerName . #drivertype=3 硬盘类型 例:获得登陆会话信息 Get-wmiobject –class win32_logonsession 例:获得本地时间 Get-WmiObject -Class Win32_LocalTime -ComputerName .| Select-Object -Property [a-z]* 例:获得计算机服务 Get-WmiObject -Class Win32_Service -ComputerName .| Format-Table -Property Status,Name,DisplayName -AutoSize –Wrap #获得本地计算机服务列表可用get-service,但win32_service还可以远程操作 例:列出使用windows installer应用程序 Get-wmiobject –class win32_product #并不是所有应用程序都使用windows installer服务 例:查找Microsoft.NET FrameWork 2.0的缓存位置 Get-WmiObject -Class Win32_Product -ComputerName .| Where-Object -FilterScript {$_.Name -eq "Microsoft .NET Framework 2.0"} | Select-Object -Property [a-z]* 例:同上 Get-WmiObject -Class Win32_Product -ComputerName .-Filter "Name='Microsoft .NET Framework 2.0'"| Select-Object -Property [a-z]* #该语句是使用WMI进行筛选,即使用WQL查询语言筛选 # WQL 查询常用的字符(例如,空格或等于号)在 Windows PowerShell 中有特殊含义。因此,谨慎的做法是始终将 Filter 参数的值放在一对引号内。还可以使用 Windows PowerShell 转义字符,即倒引号 (`),但它可能不会提高可读性。以下命令相当于前面的命令,并返回相同结果,但是使用倒引号“`”会将特殊字符转义,而不是将整个筛选器字符串放在引号内: Get-WmiObject -Class Win32_Product -ComputerName .-Filter Name`=`'Microsoft` .NET` Framework` 2.0`' | Select-Object -Property [a-z]* 例:查询windows installer应用程序的某些具体属性 Get-WmiObject -Class Win32_Product -ComputerName .| Format-List Name,InstallDate,InstallLocation,PackageCache,Vendor,Version,IdentifyingNumber 如果只是查询应用程序名称,可精简为 Get-wmiobject –class win32_product | format-wide –column 1 例:列出所有可卸载的应用程序(在“添加/删除”中可以看到的程序) #她们对应注册表位置HKLM\Software\Microsoft\Windows\CurrerntVersion\Uninstall New-psdrive –name unins –psprovider registry –root hklm:\software\microsoft\windows\currentversion\uninstall #新建一个驱动器unins,这样就可以查询了 Get-childitem –path unins: #获得可卸载应用程序的具体信息 (Get-childitem –path unins:).length #获得可卸载应用程序的数目 Get-childitem –path unins: | foreach-object –process {$_.getvalue(“displayname”)} #显示可卸载应用程序名称 # Get-ChildItem -Path Uninstall:| Where-Object -FilterScript { $_.GetValue("DisplayName") -eq " 360安全浏览器 1.35"} 注意,执行没效果 (Get-WmiObject -Class Win32_Product -Filter "Name='瑞星在线杀毒'" -ComputerName .).InvokeMethod("unins",$null) #卸载” 瑞星在线杀毒” 注意,没成功 #unins是已经定义的新驱动器 提取uninstallstring属性来获取可卸载程序的命令行字卸载符串 Get-ChildItem -Path Unins:| ForEach-Object -Process { $_.GetValue("UninstallString") } #注意unins:一定是事先定义好的驱动器 按名称筛选获取可卸载程序的命令行字卸载符串 Get-ChildItem -Path Uninstall:| Where-Object -FilterScript { $_.GetValue("DisplayName") -like "Win*"} | ForEach-Object -Process { $_.GetValue("UninstallString") } 例:在PC01计算机上远程安装MSI应用程序,共享安装路径必须符合UNC (Get-WMIObject -ComputerName PC01 -List | Where-Object -FilterScript {$_.Name -eq "Win32_Product"}).InvokeMethod("Install","\\AppSrv\dsp\NewPackage.msi") #UNC 通用命名约定 例:升级windows installer应用程序 前提:要升级的已安装的应用程序名;升级包的路径 (Get-WmiObject -Class Win32_Product -ComputerName .-Filter "Name='OldAppName'").InvokeMethod("Upgrade","\\AppSrv\dsp\OldAppUpgrade.msi") 注销系统:logoff 或 shutdown –l 或 (Get-WmiObject -Class Win32_OperatingSystem -ComputerName .).InvokeMethod("Win32Shutdown",0) #win32shutdown是method 关闭或重启动计算机:tsshutdn.exe 或 shutdown.exe 获得连到本地打印机:get-wmiobject –class win32_printer 或 (New-Object -ComObject WScript.Network).EnumPrinterConnections() #后者可列出“打印机和使用端口” 添加网络打印机:(new-object –comobject wscript.network).addwindowsprinterconnection(“\\打印机的UNC路径“) 设置默认打印机:(Get-WmiObject -ComputerName .-Class Win32_Printer -Filter "Name='HP LaserJet 5Si'").InvokeMethod("SetDefaultPrinter",$null) 或 (New-Object -ComObject WScript.Network).SetDefaultPrinter('HP LaserJet 5Si') 删除打印机连接:(New-Object -ComObject WScript.Network).RemovePrinterConnection("\\Printserver01\Xerox5") 获得计算机IP地址:get-wmiobject –class win32_networkadapterconfiguration –filter ipenabled=true | select-object –property ipaddress,macaddress #注意,为什么ipaddress是通过括号()包起来的,因为ipaddress是个数组 获得网络适配器IP详细配置数据:Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName .| Select-Object -ExpandProperty IPAddress #可使用select-object –expandproperty参数来扩展ipaddress 获得网络适配器更详细数据:Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName .| Select-Object -Property [a-z]* -ExcludeProperty IPX*,WINS* #select-object –property设定属性选择,-excludeproperty ipx*排除有关属性 对计算机进行ping操作:Get-WmiObject -Class Win32_PingStatus -Filter "Address='127.0.0.1'" -ComputerName .| Select-Object -Property Address,ResponseTime,StatusCode #只用管道符前的语句,反馈的信息很乱 #statuscode状态代码为0表示ping成功 使用数组对一系列计算机进行ping操作: 1..254| ForEach-Object -Process {Get-WmiObject -Class Win32_PingStatus -Filter ("Address='192.168.1."+ $_ + "'") -ComputerName .}| Select-Object -Property Address,ResponseTime,StatusCode #红色部分表示ping的范围,1..254表示数组 对多个地址ping: "127.0.0.1","localhost","research.microsoft.com" | ForEach-Object -Process {Get-WmiObject -Class Win32_PingStatus -Filter ("Address='" + $_ + "'") -ComputerName .}| Select-Object -Property Address,ResponseTime,StatusCode #因为有多个地址,所以需要foreach-object对多个地址分别进行ping操作 生成一组完整地址:$ips=1..254 | foreach-object –process {“192.168.1.”+$_} 为网络适配器设置指定的DNS域: Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=true -ComputerName .| ForEach-Object -Process { $_.InvokeMethod("SetDNSDomain", "fabrikam.com")} #红色部分为设置的指定DNS域,当然可以修改 创建共享目录:net share tempshare=c:\temp /users:25 /remark:"test share of the temp folder" # /users:number 允许访问共享文件夹的用户数量 #/remark:” “ 对共享文件夹进行注释 删除共享:net share tempshare /delete 映射网络驱动器到本地:net use B:\\FPS01\users 或 (New-Object -ComObject WScript.Network).MapNetworkDrive("B:", "\\FPS01\users") 将本地文件夹映射为windows可访问的驱动器 Subst m: $env:programfiles #将programfiles文件夹映射为m驱动器 处理文件和文件夹 列出某驱动器下所有项:get-childitem –force c:\ -recurse #-force 列出隐藏项或系统项 #-recurse 列出当前驱动器下的所有子文件夹内容 #类似cmd.exe下的dir和UNIX下的ls Get-ChildItem -Path $env:ProgramFiles -Recurse -Include *.exe | Where-Object -FilterScript {($_.LastWriteTime -gt "2005-10-01") -and ($_.Length -ge 1m) -and ($_.Length -le 10m)} #列出晚于2005-10-01修改的,大小在1M和10M之间的programfile文件夹下的所有可执行文件 注意,执行没通过 复制文件:copy-item –path c:\test.txt –destination c:\test.bat –force #-force 不管目标文件test.bat是否存在都强制复制 复制文件夹:copy-item c:\temp\test1 –recurse c:\temp\test2 复制所选项:copy-item –filter *.txt –path c:\temp –recurse –destination c:\temp1 #将c:\temp下包括其子文件夹下的所有的txt文件都拷贝到c:\temp1 利用COM类scripting.filesystem备份:(New-Object -ComObject Scripting.FileSystemObject).CopyFile("c:\boot.ini", "c:\boot.bak") 创建新的空文件:new-item –path ‘c:\test.txt’ –itemtype “file” 创建新文件夹:new-item –path ‘c:\temp’ –itemtype “directory” 删除文件和空文件夹:remove-item c:\test.txt ;remove-item c:\temp –recurse #recurse不需要确认,直接删除,包括子文件夹 读取文本内容:get-content -path c:\test.txt #执行该语句,将显示c:\test.txt的内容 #get-content cmdlet把文本的内容看作是数组,每行是一个元素 #(get-content –path c:\test.txt).length获取文本的行数。 # $txt=get-content –path c:\test.txt将文本内容存储于变量$txt中 例:显示某DOC文件的字数/字符数/行(不包括空白) get-content test.doc | measure-object -word -character -line -ignorewhitespace 列出注册表项: Get-chliditem –path hkcu: -force -recurse Get-childitem –path registry::hkcu Get-chliditem –path registry::hkey_current_user Get-childitem –path Microsoft.powershell.core\registry::hkcu Get-childitem –path Microsoft.powershell.core\registry::hkey_current_user #以上语句功能类似,显示注册表指定当前项内容 #-force 显示系统项或隐藏项;-recurse 显示注册表所有子项,还有include,exclude,filter #microsoft.powershell.core\registry 说明registry提供程序的默认路径,可简写为registry 例:命令查找 HKCU:\Software 中具有不超过一个子项且正好具有四个值的所有项 Get-ChildItem -Path HKCU:\Software -Recurse | Where-Object –FilterScript {($_.SubKeyCount -le 100) -and ($_.ValueCount -eq 400) } 测试不成功! 获得注册表条目信息 Get-itemproperty hkcu:\software\microsoft\windows\currentversion\run #-itemproperty是列出项的属性和属性值的信息,即显示注册表右侧窗口信息 #-childitem是列出当前项下的子项信息,即显示注册表左侧窗口信息,如果有的话! #这里可以将-itemproperty改为-item,但显然没有前1个参数提供的信息更有条理性 使用-name参数获得指定注册表条目信息 例:获得hkcu:\software\microsoft\windows\currentversion\run下ctfmon.exe的信息 Get-itemproperty hkcu:\software\microsoft\windows\currentversion\run –name ctfmon.exe #使用reg命令也可以完成以上操作 例:reg query HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\run /v ctfmon.exe #同样可以使用COM对象wscript.shell来完成 例:(New-Object -ComObject WScript.Shell).RegRead("HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\ctfmon.exe") 拷贝项 例:Copy-Item -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion' -Destination hkcu: #为什么从hkcu:到hklm:反过来拷贝不行呢? 新建项 New-item hkcu:\testnewcreate 或 new-item registry::hkcu:\testnewcreate #记住hkcu:\testnew中没有:应该改为registry::hkcu\ testnewcreate #如果新建项与原有项重名,可通过-force强制建立,其它类似 新建项的条目 例:New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion -Name PowerShellPath -PropertyType String -Value $PSHome 利用path参数的值数组可以在多个位置建立注册表条目 例:new-itemproperty –path hkcu:\software\microsoft\windows\currentversion, hklm:\software\microsoft\windows\currentversion –name testzgk –property string –value “我爱你海红” #propertytype参考表 PropertyType 值 含义 Binary 二进制数据 DWord 一个有效的 UInt32 数字 ExpandString 一个可以包含动态扩展的环境变量的字符串 MultiString 多行字符串 String 任何字符串值 QWord 8 字节二进制数据 重命名注册表条目 例:Rename-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion -Name PowerShellPath -NewName PSHome –passthru #-passthru可以看到重命名后的条目名称 删除项 Remove-item hkcu:\testnewcreate 或 Remove-item registry::hkcu\ testnewcreate 例:删除'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion 所有项 Remove-item HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion 如果想保留HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion 项只删除它里面的所有项 Remove-item HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\* 删除条目 例:Remove-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion -Name PSHome CMD UNIX使用的命令对应PowerShell的命令和别名 CMD 命令 Unix 命令 PS 命令 PS 别名 dir ls Get-ChildItem gci cls clear Clear-Host(函数) 不可用 del、erase、rmdir rm Remove-Item ri copy cp Copy-Item ci move mv Move-Item mi rename mv Rename-Item rni type cat Get-Content gc cd cd Set-Location sl md mkdir New-Item ni 不可用 pushd Push-Location 不可用 不可用 popd Pop-Location 不可用  


   此帖被 +4 点积分     点击查看详情   
评分人:【 lxmxn 分数: +4  时间:2009-2-8 02:52


2009-2-5 16:36
查看资料  发短消息  网志   编辑帖子  回复  引用回复

请注意:您目前尚未注册或登录,请您注册登录以使用论坛的各项功能,例如发表和回复帖子等。


可打印版本 | 推荐给朋友 | 订阅主题 | 收藏主题



论坛跳转: