迷迷糊呼的学了一些,还是不知所措,不知哪位朋友有入门的清晰感觉,共研之!
学习疑问:
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 开发组博克
http://blogs.msdn.com/PowerShell/
6. PowerShell新闻组Microsoft.Public.Windows.PowerShell
7. 脚本中心
http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspxPowerShell
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 c:\windows
get-childitem
*.dll
# 使用-exclude **.dll是为了排除与“win95或16位windows兼容的DLL
# 但是我在自己的机器上没有使用-exclude也没有显示有关与“win95或16位windows
# 兼容的DLL,我想这根windows的使用环境有关,设计语句毕竟要严谨和考虑全面
例:get-childitem –path c:\windows\*.dll –recurse –exclude *.dll
#该语句不会返回任何结果,因为*.dll中的通配符会排除所有DLL
#get-childitem –path c:\windows –include *.dll –recurse –exclude *.dll
通配符
* ? 和
其中 表示阔住匹配的字符
例:get-childitem c:\windows\*
#表示枚举出c:\windows目录下所有以x或z打头的文件
例:get-childitem c:\windows\?????.log
#表示枚举出c:\windows下所有5个任意字符的log文件
七.WMI对象操作
WMI是系统管理的核心技术。WMI类描述可管理的资源,很多类有很多属性。
get-wmiobject –list #获得本地或远程可用的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=”
http://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(“
http://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的静态属性
| get-member –static
#注意,有-static和没有-static显示内容是不同的
#有-static则显示system.environment的静态属性
#没有显示system.environment的runtimetype
# | get-member –membertype property并不能显示静态属性
#之所以写没有写成是因为system是默认的可省略
例:静态属性的应用
::osversion
静态类system.math有一些method是相同的,可通过参数区分它们。
| get-member –static –membertype method
例:::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键选择变量的属性和方法。
定向输出:用 “ > ”表示。
注释 :用“ # ”表示。
引号 :注意“单 双”引号的区别。
八. 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 *
#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 *
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 *
例:获得计算机服务
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 *
例:同上
Get-WmiObject -Class Win32_Product -ComputerName .-Filter "Name='Microsoft .NET Framework 2.0'"| Select-Object -Property *
#该语句是使用WMI进行筛选,即使用WQL查询语言筛选
# WQL 查询常用的字符(例如,空格或等于号)在 Windows PowerShell 中有特殊含义。因此,谨慎的做法是始终将 Filter 参数的值放在一对引号内。还可以使用 Windows PowerShell 转义字符,即倒引号 (`),但它可能不会提高可读性。以下命令相当于前面的命令,并返回相同结果,但是使用倒引号“`”会将特殊字符转义,而不是将整个筛选器字符串放在引号内:
Get-WmiObject -Class Win32_Product -ComputerName .-Filter Name`=`'Microsoft` .NET` Framework` 2.0`' | Select-Object -Property *
例:查询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 * -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 不可用
A bit迷糊 after learning some, still at a loss. Is there any friend who has a clear feeling of getting started, let's study together!
Learning Questions:
1. How to arbitrarily display the method of a certain object and use it (already closed)?
2. How to use the command line uninstall string of uninstallable programs in PowerShell?
I. PowerShell Commonly Used Shortcuts
F7: Displays the command history that has been entered, and you can select and execute them one by one using the up and down arrows.
ALT+F7: Clears the command history.
ESC: Clears all characters currently entered.
CTRL+END: Clears the content from the cursor to the end of the line.
CTRL+C / CTRL+BREAK: Terminates the execution of the command.
↑: Queries historical commands upwards.
↓: Queries historical commands downwards.
II. Resource List
1.
www.powershell.com
: Can download the PowerShell Plus tool, which is more convenient than the PowerShell tool provided by Microsoft. The latter has no auto-completion function.
2. forums.microsoft.com\china
3. PowerShell Blog: vista.itech.net
4. Install PowerShell:
www.microsoft.com/downloads
5. PowerShell Development Team Blog
http://blogs.msdn.com/PowerShell/
6. PowerShell Newsgroup Microsoft.Public.Windows.PowerShell
7. Script Center
http://www.microsoft.com/technet/scriptcenter/hubs/msh.mspxPowerShell
8.
III. What is PowerShell
PowerShell is the future of system administration and scripting language development.
It is an interactive Shell environment (a new generation of command parser) and scripting language provided by Microsoft for the command line interface, enabling both command line users and script writers (by writing to COM objects to achieve many functions) to utilize the powerful functions of the.NET Framework (such as the class library of the.NET Framework - FCL), helping administrators complete flexible and automated work.
PowerShell is built on.NET, so it requires the support of.NET Framework v2.0 for installation.
PowerShell is object-based, and the output of commands is objects.
PowerShell is installed in %systemroot%\system32\
IV. Variables and Parameters in PowerShell
Variables in PowerShell should be understood as objects, not text.
The symbol for defining a variable: $. For example, to define a variable var, use $var. Assign a value to the variable: $var = 123 $var1 = abd. You can also embed variables into variables. For example, $var2 = "$var $var1", the value of $var2 is 123 abd. If it is $var2 = '$var $var1', then $var $var1 is assigned to $var2 as a string. Remember the difference between single quotes and double quotes.
For data types, you can not define and declare.
View all variables: get-variable
View the set of commands that can operate on variables: get-command –noun varibale
Common system variables: $pshome $home $profile
Four modes of variables: local script global private.
Example: Corresponding operations on environment variables
Get-childitem env:
Example: Specific reference to environment variables
$env:os
# Explanation: The system environment variables in CMD.EXE can still be used in PowerShell
-: Parameter lead character. For example, if there is a parameter Name, it must be written as -Name when writing.
Common parameters include: WhatIf Confirm Verbose Debug Warn ErrorAction ErrorVariable
OutVariable OutBuffer, they are all controlled by the PowerShell engine. Each time a cmdlet implements these parameters, their behavior is always the same.
-Syntax: Obtain the syntax of the cmdlet. For example, get-process –syntax
Important Parameter Explanation
-noun can obtain a series of commands that affect objects of the same type
-passthru can see the execution process of the command
-whatif can preview the possible consequences of the command. This parameter can realize the reference to the prototype pattern. Not every cmdlet can use this parameter.
-credential specifies the user account name
-eq equal operator. Adding I –ieq means case-insensitive comparison; -ceq case-sensitive comparison.
V. cmdlets and Skills in PowerShell
cmdlets naming rule:
A single cmdlet can only complete a single task. To complete complex tasks, it must be done through the pipeline |. | not only plays the role of passing the execution result of the previous cmdlet to the next cmdlet, but also plays the role of connecting commands, that is, commands can be written in multiple lines for easy reading.
| is executed concurrently.
Aliases: Aliases. For example, gps=get-process sort=sort-object ft=format-table. You can customize the alias of the command. The command is Get-Alias -Name gi -Value Get-Item. Note that system-defined aliases such as gi gcm scm cannot be changed.
Command abbreviation: For easy memory, Set is represented by S, Get by G, Item by I, Command by CM. For example, get-command=gcm; get-wmiobject=gwmi etc.
Get-command: Obtain all available cmdlets. Note that it does not include aliases function script, etc.
Example: Want to obtain detailed information of alias/ function /script commands
get-command –commandtype alias/function/externalscript
get-aliases: Obtain all aliases of commands.
get-help: Obtain help.
Example: Obtain the help information and its syntax of the command
get-help –name get-command –full/-detail -syntax
#-name: Can be omitted
get-process -?
Example: help or man display the help information of the command in pages
help get-service or man get-service
Example: Use the more function to display the help information in pages
get-process | more
# more can also read the content of the file and display it in pages, such as more c:\test.txt
Example: Display the help information of conceptual topics
get-help about_*
#about_: Represents the prefix of conceptual topics
get-help about_where
#Display the help information of the specific conceptual topic where
Example: get-command *_service
#Obtain the cmdlets related to service operation
#_ can be removed, written as *service, but the * cannot be removed. Writing get-command service will cause an error!
Example: Obtain a series of commands that affect the same type of object
get-command –noun service
#-noun: This parameter can obtain a series of commands that affect the same type of object, similar to get-command *service
Example: get-service | get-member
#If you want to fully understand the object structure of get-service, you can output this command to get-member through |
Example: Obtain some of the output objects of a certain command
get-process –name powershell | format-table –property processname,fileversion,starttime,name,id,company,path –autosize -wrap –groupby company
# -property is very useful for obtaining the information of the output object!
# -autosize means automatically adjusting the column width
# -wrap means automatically wrapping lines if the content cannot be displayed
#-width 2147483647 prevents the table from being truncated due to being too wide
# -groupby is used to control the table output, grouping based on the specified property value, which is easy to display a very large and difficult-to-display table
# -autosize and -wrap used together have a good display effect, but it consumes a lot of system resources. It is recommended to put properties with relatively small widths such as name at the end
# If you want to display all properties, you can use * to represent
#
Example: Obtain the specific information of a certain service/process
get-service –name alerter/get-process -name powershell
Example: List all commands with the verb get
get-command –verb get
#verb: The meaning of the parameter
Example: List the folders and files in the current directory
get-childitem
#get-childitem c:\ List the directories and files under the C drive
#get-childitem c:\ | out-host Output the directories and files under the C drive to the screen. If there is a lot of output information, this operation consumes a lot of CPU and memory. You can use the -paging parameter to output one screen at a time.
#out-null: Shield the output; out-printer: Print the output
Example: Output control commands format-wide/format-list/format-table/format-custom
Example: Output control commands out-host/out-null/out-printer/out-file -Encoding ASCII –width 2147483647
get-process | format-table | out-file –filepath c:\test.txt
#Output get-process to c:\test.txt
#Note that out-file creates unicode by default. -Encoding ASCII changes the file to ASCII, which is convenient for tool processing of the output
#-width 2147483647 prevents the table from being truncated due to being too wide
Example: To view the object structure of get-process
get-process | get-member | out-host –paging
Example: To view a certain type of information in the object structure of get-process
get-process | get-member –membertype property
# MemberType allows using the following values: AliasProperty, CodeProperty, Property, NoteProperty, ScriptProperty, Properties, PropertySet, Method, CodeMethod, ScriptMethod, Methods, ParameterizedProperty, MemberSet and All.
Exploration and Discovery
Get-Help, Get-Command
Get-Member: View the "structure of the object", which is very important.
Object-Oriented Small Commands
Compare, Group, Measure, Select, Sort, Tee, Where
Format Control
Format-(Custom, List, Table, Wide)
Task-Oriented Commands
Process: get/stop(-process)
System Service: get/start/stop/suspend/resume/restart(-service)
Event Log: get-eventlog
Main Commands in CLI (Command Line Interface) (????---Not understood---????????)
– Shell Functions (CLI available code)
– PowerShell Scripts (.PS1)
– Native commands (.EXE, .BAT, etc.)
Use Whanif to preview the execution result: For example, shutting down a process will have an impact on the system, so use it to preview first.
$?: Test whether the command is executed successfully.
Key Point:
Not all commands that conform to the "verb-noun" command specification are cmdlets of PowerShell. For example, clear-host is an internal function of PowerShell. You can judge whether its commandtype is function or cmdlet by get-command –name clear-host.
In addition to cmdlets being built-in commands of PowerShell, aliases function scirip executable files and external files of registered file type handlers all belong to the commands of PowerShell.
PowerShell has no auto-completion function, but can be extended by TAB. The condition is that after entering "verb + hyphen -", press the TAB key to automatically find the first matching command. If it is not the one you need, you can complete it through TAB again.
VI. Commands for File System Operations
get-location: Obtain the current directory
set-location –path c:\: Change the current directory to c:\, but there is no process prompt
set-location -path c:\ -passthru ##Change the current directory to c:\, with process prompt
set-locaiton \\server\shared directory: server remote server
push-location -path “local settings”: Push the current directory into the stack and change the directory to local settings
push-location -path temp: Push the current directory into the stack and change the directory to temp
pop-location -passthru: Restore the directory pushed into the stack. You can use it to pop the most recently used directory
cd –path hkcm:\software: Change the current directory to hkcm:\software
PowerShell uses the noun "item" to represent the content under the drive. If it is a file system drive, the item can be "folder or file or PowerShell drive".
Common operation commands for items: new-item rename-item copy-item remove-item invoke-item
invoke-item: Execute the item, which is a handler with the default application in the registry (similar to associated programs)
Example: invoke-item c:\1.txt
# Call notepad.exe to open 1.txt because the default associated program for txt is notepad.exe
invoke-item c:\windows
# Is equivalent to "double-click to open the windows directory", associated with the resource manager
invoke-item c:\test.bat
# Execute the bat
Example: Create 1.txt #new-item –path c:\1.txt –itemtype file/directory
Example: Rename 1.txt under the C drive to 2.txt under the D drive
rename-item –path c:\1.txt d:\2.txt
# This command is wrong because rename cannot move the directory, only rename within the same directory
# Correct: move-item –path c:\1.txt –destination d:\2.txt –passthru #Can see the specific moving process
Example: Copy a directory
copy-item –path c:\new –destination c:\temp
# Note that if there is content under new, the content cannot be copied to temp. Without parameters, only the container is copied
copy-item –path c:\new –destination c:\temp –recurse –force –passthru
# -recurse means copying the content inside the container as well
Example: Delete a directory
remove-item –path c:\temp –recurse
# If there is no -recurse, deleting the directory requires confirmation
# -recurse has different meanings under different commands
get-command –noun item: Obtain all operation commands for items
get-childitem: Used to enumerate "folders/files/registry".
Example: set-location c:\windows
get-childitem
*.dll
# Using -exclude **.dll is to exclude DLLs compatible with "win95 or 16-bit windows"
# But I didn't display the DLLs compatible with "win95 or 16-bit windows" on my own machine. I think this is related to the use environment of windows. The design statement must be rigorous and comprehensive
Example: get-childitem –path c:\windows\*.dll –recurse –exclude *.dll
# This statement will not return any results because the wildcards in *.dll will exclude all DLLs
#get-childitem –path c:\windows –include *.dll –recurse –exclude *.dll
Wildcards
* ? and
Among them, means matching the enclosed characters
Example: get-childitem c:\windows\*
# Means enumerating all files starting with x or z under the c:\windows directory
Example: get-childitem c:\windows\?????.log
# Means enumerating all 5 arbitrary character log files under c:\windows
VII. WMI Object Operations
WMI is the core technology of system management. WMI classes describe manageable resources, and many classes have many properties.
get-wmiobject –list #Obtain the available WMI class resources locally or remotely
By default, get-wmiobject uses the root/imv2 namespace. If you need to specify the namespace, you must use -namespace
Example: get-wmiobject –list –computernaem 192.168.1.1 –namespace root
Example: Specifically use a certain WMI class win32_operatingsystem
get-wmiobject –class win32_operatngsystem –namespace root –computername
# Self-written command. The error is that win32_operatngsystem is missing i, and root should be root/cimv2
get-wmiObject -Class Win32_OperatingSystem -Namespace root/cimv2 –ComputerName .
#. represents the style of WMI, representing the computer name
# If get-wmiobject has no parameters, the first parameter is class by default; the parameter namespace has the default namespace root/cimv2; for local operations, the parameter computername can be omitted
# This command line can be abbreviated as get-wmiobject win32_operatingsystem
Can view more properties of the class
get-wmiobject win32_operatingsystem | get-member –membertype property
View non-default properties
get-wmiobject win32_operatingsystem | Format-Table -Property TotalVirtualMemorySize,TotalVisibleMemorySize,FreePhysicalMemory,FreeVirtualMemory,FreeSpaceInPagingFiles
Use wildcard abbreviation
get-wmiobject win32_operatingsystem | Format-table –Property total*,free*
# Change table to list to enhance the readability of the result
Use the where-object cmdlet pipeline to filter objects (using comparison operators)
In the pipeline, $_ represents the object in the pipeline; - represents the prefix of the comparison operator; {} encloses the script block; the parameter -filterscript is used for filtering.
Example: Get-WmiObject -Class Win32_SystemDriver | Where-Object -FilterScript {$_.State -eq "Running"} | Where-Object -FilterScript {$_.StartMode -eq "Manual"} | Format-Table -Property Name,DisplayName,pathname
This statement is equivalent to
Get-WmiObject -Class Win32_SystemDriver | Where-Object -FilterScript { ($_.State -eq "Running") -and ($_.StartMode -eq "Manual") } | Format-Table -Property Name,DisplayName
Use the foreach-object cmdlet to perform repeated operations on multiple objects
Example: Get-WmiObject -Class Win32_LogicalDisk | ForEach-Object -Process {($_.FreeSpace)/1024.0/1024.0}
Use select-object to select objects
Example: get-wmiobject –class win32_logicaldisk | select-object –property name,freespace | get-member
Use sort-object to sort
Example: get-wmiobject –class win32_systemdriver | sort-object –property state,name | format-table –property name,state,started,displayname –autosize
# Sort the state and name properties output in format-tabel
# descending sort in reverse order
V. Operations on.NET Objects
Some components have.NET Framework and COM interfaces. PowerShell allows using these components to expand and enhance system management work
The.NET Framework is a class library containing many classes, such as System.Diagnostics.EventLog, which can manage event logs.
Example: $applog=new-object –typename system.diagnostics.eventlog –argumentlist application, computername/ip
# Store the object in a variable for easy calling
# Without -argumentlist, the log can be created but is empty. Adding parameters can manage the specific log
# Enter the variable $applog to see the number of logs
# –argumentlist application passes application as a parameter to the parameter -argumentlist, playing the role of a constructor
# computername/ip accesses remote logs
get-eventlog: View the log
Example: Obtain the methods / properties of the object
$application | get-member –membertype method/property
# Among them, a method obtained is clear
Clear log information
$application.clear()
# () must be added. clear() represents the method, to distinguish it from the same-named property
Example: View the latest three logs of applicatio
get-eventlog –logname application –newest 3
# The log types also include system security
VIII. Operations on.COM (Component Object Model) Objects
COM components include the libraries contained in WSH and Active X applications. new-object can operate on these components
New-object –comobject wscript.shell #Create a COM object
# Can also create WScript.Network, Scripting.Dictionary and Scripting.FileSystemObject
Example: Use the COM object to create a shortcut
$shorcut=new-object –comobject wscript.shell
# Create a COM object and save it to a variable
$shorcut | get-member
# Obtain the operation methods of the object, including createshortcut
$net=$shorcut.createshortcut(“c:\test.url”)
# Establish a storage path and name for the created shortcut
# Note that do not miss the suffix.url, it can also be.lnk, depending on the need; also remember that () is followed closely
$net.targetpath=”
http://10.*.*.*”
# Establish content mapping for the created shortcut. Because it is.url, it maps to a website
$net.save()
# Store the shortcut. It will not be created successfully without storing
Example: Use the COM object to start an IE instance
The separately running COM object is called an Active X executable program.
$ie=New-object –comobject internetexplorer.application
# Create an IE instance using the internetexplorer ProgID, that is, internetexplorer.application
# This process runs independently
Get-process
# The above created IE instance is not visible, but it can be viewed through the process
$ie.visible=$true
# Make the IE instance visible
$ie.navigate(“
http://www.sohu.com”)
# Use navigate to navigate to a specific website
$ie.document.body.innertext
# Retrieve text content in the web page
$ie.quit()
# Close IE
$ie | get-member
# After closing IE, this variable becomes invalid. You can check it through get-member
$ie=$null
# Clear the reference of the remaining variable
Remove-variable ie
# Completely clear this variable
Example: Create a non-standard COM object
New-object –comobject excel.application –strict
# -strict creates a non-standard COM object
Because get-member has an optional parameter –inputobject, so $shorcut | get-member can be rewritten as
get-member –inputobject $shorcut
Note that -inputobject will treat the parameter as a single item. So if there are multiple objects stored in variables, then
-inputobject will treat them as an array of objects.
VIII. Static Classes
Static classes: Not all.NET Framework classes can be used with new-0bject. The properties and methods in static classes are fixed and can only be referenced, not modified, such as System.Environment and System.Math.
Therefore, new-object system.environment is wrong.
The properties of static classes are also static. The static properties of static classes are referenced through ::.
Example: How to view the static properties of system.environment
| get-member –static
# Note that the content displayed with -static and without -static is different
# With -static, the static properties of system.environment are displayed
# Without, the runtimetype of system.environment is displayed
# | get-member –membertype property cannot display static properties
# The reason why is written instead of is that system is the default and can be omitted
Example: Application of static properties
::osversion
There are some identical methods in the static class system.math, which can be distinguished by parameters.
| get-member –static –membertype method
Example: ::sqrt(9)
VIII. Providers and Drives in PowerShell
Providers abstract the access data layer between PowerShell and drives, so that different drives can be interacted with under a unified mechanism. But actually, we don't feel the existence of providers.
Get-help –category provider #Obtain all provider types.
Name the PowerShell drive with the noun PSDrive.
There are four types of drives:
Filesystem file system drive: such as C: D:
Registry registry drive: such as HKLM: HKLU:
Certificate certificate drive: such as CER:
Env drive (environment variable drive): Env:
Variable drive (variable drive):
Custom drive: There are three conditions, 1. The name of the drive; 2. Psprovider; 3. Root is the corresponding path of the drive. Example New-PSDRIVE -name zgktest –psprovider registry –root hklm\software\microsoft\windows\current. Enter the command to enter this drive: cd zgktest: or set-location zgktest: -passthru. The command to view the content under this drive is dir.
get-psdrive: Obtain the list of all drives
get-psdrive –psprovider certificate: Obtain the specified certificate drive
# -psprovider: is to specify the provider, remember not to miss ps
remove-psdriver –name drivername: Delete the specified drive
The drives of PowerShell are for PowerShell's own use. The resource manager and cmd.exe cannot open the drives of PowerShell.
When PowerShell exits, the newly defined drive will disappear. You can export the new console through the export-console command, and then import it into a new session through the parameter psconsolefile.
VI. Execution Policy of PowerShell Scripts
The execution policy of PowerShell is divided into four types: Restricted, default, prohibits all script execution; AllSigned, only runs trusted scripts; RemoteSigned, all local scripts can be executed, regardless of whether they are trusted. If the script is downloaded from the Internet, it must be trusted; UnRestricted, all scripts can be executed.
Command to change the policy: set executionpolicy remotesigned, change the default policy from restricted to remotesigned.
Makecert.exe: Make a trusted security script (provided by Microsoft).
Steps to make a trusted script using makecert.exe:
1. Create a trust certificate: 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. Export the trust certificate: 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. Use the trust certificate to trust-sign the script: Set-AuthenticodeSignature D:\myscript.ps1 $cert
VII. Syntax and Operations
get-member: Obtain properties and methods. Example: $var1 | get-member Obtain the properties and methods of $var. $var. Use the TAB key to select the properties and methods of the variable.
Directional output: Use " > " to represent.
Comment: Use "#" to represent.
Quotation marks: Pay attention to the difference between "single and double" quotes.
VIII. PowerShell's Management of IIS
Requires the support of the IIS PowerShell provider plug-in.
PowerShell manages IIS7 better, and manages IIS6 relatively weakly, only being able to do some start/stop IIS operations.
Common syntax: start-webitem stop-webitem get-webitemstate
. Create a Web site
New-Item iis:\Sites\TestSite -bindings
@{protocol="http";bindingInformation=":80:TestSite"} -physicalPath
c:\test
#New-item iis:\Site\TestSite –bindings: Create a site TestSite and implement binding
# protocol=”http” Use http protocol
#bindinginfomation=”;80:TestSite” Map port 80 to site TestSite
# physicalPath c:\test: The physical path of the site is c:\test
• Create a Web application
New-Item 'IIS:\Sites\Default Web Site\DemoApp' -physicalPath
c:\test -type Application
#type Application: The type is an application
IX. How PowerShell Manages the System
Important commands: get-process and stop-process; get-service
Example: Stop all unresponsive programs
Get-Process | Where-Object -FilterScript {$_.Responding -eq $false} | Stop-Process
Example: Stop all other Windows PowerShell dialogs
Get-Process -Name powershell | Where-Object -FilterScript {$_.Id -ne $PID} | Stop-Process -
PassThru
Example: Suspend a service spooler
Suspend-service –name spooler
Example: Restart multiple services
Get-Service | Where-Object -FilterScript {$_.CanStop} | Restart-Service
# First obtain the service list, filter them, and then execute the restart
Get-wmiobject is the most important command for regular system management.
Example: Collect desktop-related information of the local computer
Get-WmiObject -Class Win32_Desktop -ComputerName .| Select-Object -Property *
# The information listed by the WMI class is very detailed, and it also includes "WMI metadata represented by double underscores"
# Can be filtered through select-object
#-computername can be omitted, and. behind represents the local computer name
Example: Collect BIOS information
Get-wmiobject –class win32_bios
Example: Collect CPU information
Get-wmiobject –class win32_processor
Get-WmiObject -Class Win32_Processor -ComputerName .| Select-Object -Property *
et-WmiObject -Class Win32_ComputerSystem -ComputerName .| Select-Object -Property SystemType
# Get a general description string of the processor series
Example: List the computer manufacturer and model
Get-wmiobject –class win32_computersystem
Example: Obtain the user logged in to the computer
Get-wmiobject –class win32_computersystem –property username | select-object –property username
#select-object –property username simplifies the output content
Example: List the installed patch information
Get-wmiobject –class win32_quickfixengineering –property hotfixid
#-property hotfixid filters more purposefully
Get-WmiObject -Class Win32_QuickFixEngineering -ComputerName .-Property Hot
FixId | Select-Object -Property HotFixId
# The above statement will also return other data. Further narrow the range through Select-Object -Property HotFixId
Example: List all users and owners
Get-WmiObject -Class Win32_OperatingSystem -ComputerName .| Select-Object -Property NumberOfLicensedUsers,NumberOfUsers,RegisteredUser
Simplified to
Get-WmiObject -Class Win32_OperatingSystem -ComputerName .| Select-Object -Property *user*
Example: List disk space and remaining space
Get-WmiObject -Class Win32_LogicalDisk -Filter "DriveType=3" -ComputerName .
#drivertype=3 hard disk type
Example: Obtain login session information
Get-wmiobject –class win32_logonsession
Example: Obtain local time
Get-WmiObject -Class Win32_LocalTime -ComputerName .| Select-Object -Property *
Example: Obtain computer services
Get-WmiObject -Class Win32_Service -ComputerName .| Format-Table -Property Status,Name,DisplayName -AutoSize –Wrap
# Obtaining the local computer service list can use get-service, but win32_service can also operate remotely
Example: List applications using the Windows installer
Get-wmiobject –class win32_product
# Not all applications use the Windows installer service
Example: Find the cache location of Microsoft.NET FrameWork 2.0
Get-WmiObject -Class Win32_Product -ComputerName .| Where-Object -FilterScript {$_.Name -eq "Microsoft .NET Framework 2.0"} | Select-Object -Property *
Example: Same as above
Get-WmiObject -Class Win32_Product -ComputerName .-Filter "Name='Microsoft .NET Framework 2.0'"| Select-Object -Property *
# This statement uses WMI for filtering, that is, using WQL query language for filtering
# Special characters (such as spaces or equal signs) commonly used in WQL queries have special meanings in Windows PowerShell. Therefore, it is prudent to always put the value of the Filter parameter in a pair of quotes. You can also use the Windows PowerShell escape character, that is, the backquote (`), but it may not improve readability. The following command is equivalent to the previous command and returns the same result, but uses the backquote "`" to escape special characters instead of putting the entire filter string in quotes:
Get-WmiObject -Class Win32_Product -ComputerName .-Filter Name`=`'Microsoft` .NET` Framework` 2.0`' | Select-Object -Property *
Example: Query some specific properties of the Windows installer application
Get-WmiObject -Class Win32_Product -ComputerName .| Format-List Name,InstallDate,InstallLocation,PackageCache,Vendor,Version,IdentifyingNumber
If you only want to query the application name, it can be simplified as
Get-wmiobject –class win32_product | format-wide –column 1
Example: List all uninstallable applications (programs that can be seen in "Add/Remove")
# They correspond to the registry location HKLM\Software\Microsoft\Windows\CurrerntVersion\Uninstall
New-psdrive –name unins –psprovider registry –root hklm:\software\microsoft\windows\currentversion\uninstall
# Create a new drive unins, so that you can query
Get-childitem –path unins:
# Obtain the specific information of uninstallable applications
(Get-childitem –path unins:).length
# Obtain the number of uninstallable applications
Get-childitem –path unins: | foreach-object –process {$_.getvalue(“displayname”)}
# Display the name of uninstallable applications
# Get-ChildItem -Path Uninstall:| Where-Object -FilterScript { $_.GetValue("DisplayName") -eq " 360安全浏览器 1.35"} Note that the execution has no effect
(Get-WmiObject -Class Win32_Product -Filter "Name='瑞星在线杀毒'" -ComputerName .).InvokeMethod("unins",$null)
# Uninstall "瑞星在线杀毒" Note that it was not successful
#unins is the newly defined drive
Extract the uninstallstring property to obtain the command line uninstall string of the uninstallable program
Get-ChildItem -Path Unins:| ForEach-Object -Process { $_.GetValue("UninstallString") }
# Note that unins: must be the previously defined drive
Filter by name to obtain the command line uninstall string of the uninstallable program
Get-ChildItem -Path Uninstall:| Where-Object -FilterScript { $_.GetValue("DisplayName") -like "Win*"} | ForEach-Object -Process { $_.GetValue("UninstallString") }
Example: Remotely install an MSI application on the PC01 computer. The shared installation path must conform to UNC
(Get-WMIObject -ComputerName PC01 -List | Where-Object -FilterScript {$_.Name -eq "Win32_Product"}).InvokeMethod("Install","\\AppSrv\dsp\NewPackage.msi")
#UNC Universal Naming Convention
Example: Upgrade the Windows installer application
Prerequisite: The name of the installed application to be upgraded; the path of the upgrade package
(Get-WmiObject -Class Win32_Product -ComputerName .-Filter "Name='OldAppName'").InvokeMethod("Upgrade","\\AppSrv\dsp\OldAppUpgrade.msi")
Log off the system: logoff or shutdown –l or (Get-WmiObject -Class Win32_OperatingSystem -ComputerName .).InvokeMethod("Win32Shutdown",0)
#win32shutdown is the method
Shut down or restart the computer: tsshutdn.exe or shutdown.exe
Obtain the connected local printer: get-wmiobject –class win32_printer or
(New-Object -ComObject WScript.Network).EnumPrinterConnections()
# The latter can list "printers and used ports"
Add a network printer: (new-object –comobject wscript.network).addwindowsprinterconnection(“\\打印机的UNC路径“)
Set the default printer: (Get-WmiObject -ComputerName .-Class Win32_Printer -Filter "Name='HP LaserJet 5Si'").InvokeMethod("SetDefaultPrinter",$null) or
(New-Object -ComObject WScript.Network).SetDefaultPrinter('HP LaserJet 5Si')
Delete a printer connection: (New-Object -ComObject WScript.Network).RemovePrinterConnection("\\Printserver01\Xerox5")
Obtain the computer IP address: get-wmiobject –class win32_networkadapterconfiguration –filter ipenabled=true | select-object –property ipaddress,macaddress
# Note that why ipaddress is enclosed in parentheses () is because ipaddress is an array
Obtain detailed configuration data of the network adapter IP: Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName .| Select-Object -ExpandProperty IPAddress
# Can use the select-object –expandproperty parameter to expand ipaddress
Obtain more detailed data of the network adapter: Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=TRUE -ComputerName .| Select-Object -Property * -ExcludeProperty IPX*,WINS*
# select-object –property sets property selection, -excludeproperty ipx* excludes relevant properties
Ping the computer: Get-WmiObject -Class Win32_PingStatus -Filter "Address='127.0.0.1'" -ComputerName .| Select-Object -Property Address,ResponseTime,StatusCode
# Only use the statement before the pipeline, the feedback information is very messy
# statuscode status code 0 means ping is successful
Use an array to ping a series of computers:
1..254| ForEach-Object -Process {Get-WmiObject -Class Win32_PingStatus -Filter ("Address='192.168.1."+ $_ + "'") -ComputerName .}| Select-Object -Property Address,ResponseTime,StatusCode
# The red part means the range of ping, 1..254 means an array
Ping multiple addresses:
"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
# Because there are multiple addresses, you need to use foreach-object to ping multiple addresses separately
Generate a group of complete addresses: $ips=1..254 | foreach-object –process {“192.168.1.”+$_}
Set the specified DNS domain for the network adapter:
Get-WmiObject -Class Win32_NetworkAdapterConfiguration -Filter IPEnabled=true -ComputerName .| ForEach-Object -Process { $_.InvokeMethod("SetDNSDomain", "fabrikam.com")}
# The red part is the specified DNS domain to be set, of course, it can be modified
Create a shared directory: net share tempshare=c:\temp /users:25 /remark:"test share of the temp folder"
# /users:number allows the number of users accessing the shared folder
#/remark:” “ comments on the shared folder
Delete the share: net share tempshare /delete
Map a network drive to the local: net use B:\\FPS01\users or
(New-Object -ComObject WScript.Network).MapNetworkDrive("B:", "\\FPS01\users")
Map the local folder as a Windows accessible drive
Subst m: $env:programfiles
# Map the programfiles folder as drive m
Process files and folders
List all items under a certain drive: get-childitem –force c:\ -recurse
#-force lists hidden items or system items
#-recurse lists the content of all subfolders under the current drive
# Similar to dir in cmd.exe and ls in UNIX
Get-ChildItem -Path $env:ProgramFiles -Recurse -Include *.exe | Where-Object -FilterScript {($_.LastWriteTime -gt "2005-10-01") -and ($_.Length -ge 1m) -and ($_.Length -le 10m)}
# List all executable files under the programfile folder that were modified after 2005-10-01 and have a size between 1M and 10M Note that the execution did not pass
Copy a file: copy-item –path c:\test.txt –destination c:\test.bat –force
#-force forces the copy regardless of whether the target file test.bat exists
Copy a folder: copy-item c:\temp\test1 –recurse c:\temp\test2
Copy selected items: copy-item –filter *.txt –path c:\temp –recurse –destination c:\temp1
# Copy all txt files under c:\temp, including those under subfolders, to c:\temp1
Back up using the COM class scripting.filesystem: (New-Object -ComObject Scripting.FileSystemObject).CopyFile("c:\boot.ini", "c:\boot.bak")
Create a new empty file: new-item –path ‘c:\test.txt’ –itemtype “file”
Create a new folder: new-item –path ‘c:\temp’ –itemtype “directory”
Delete files and empty folders: remove-item c:\test.txt ;remove-item c:\temp –recurse
# recurse does not require confirmation and directly deletes, including subfolders
Read text content: get-content -path c:\test.txt
# Execute this statement to display the content of c:\test.txt
#get-content cmdlet treats the content of the text as an array, and each line is an element
#(get-content –path c:\test.txt).length obtains the number of lines in the text.
# $txt=get-content –path c:\test.txt stores the text content in variable $txt
Example: Display the word count/character count/line (excluding blanks) of a certain DOC file
get-content test.doc | measure-object -word -character -line -ignorewhitespace
List registry items:
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
# The above statements have similar functions and display the content of the specified current item in the registry
#-force displays system items or hidden items; -recurse displays all subitems in the registry, and there are include, exclude, filter
#microsoft.powershell.core\registry indicates the default path of the registry provider, which can be abbreviated as registry
Example: The command finds all items in HKCU:\Software that have no more than 100 subitems and exactly 400 values
Get-ChildItem -Path HKCU:\Software -Recurse | Where-Object –FilterScript {($_.SubKeyCount -le 100) -and ($_.ValueCount -eq 400) } The test is not successful!
Obtain registry entry information
Get-itemproperty hkcu:\software\microsoft\windows\currentversion\run
#-itemproperty lists the information of the properties and property values of the item, that is, displays the information in the right window of the registry
#-childitem lists the information of the subitems under the current item, that is, displays the information in the left window of the registry if there is any!
# Here, -itemproperty can be changed to -item, but obviously the information provided by the previous parameter is more organized
Use the -name parameter to obtain the specified registry entry information
Example: Obtain the information of ctfmon.exe under hkcu:\software\microsoft\windows\currentversion\run
Get-itemproperty hkcu:\software\microsoft\windows\currentversion\run –name ctfmon.exe
# The above operation can also be completed using the reg command
Example: reg query HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\run /v ctfmon.exe
# The same can be completed using the COM object wscript.shell
Example: (New-Object -ComObject WScript.Shell).RegRead("HKCU\SOFTWARE\Microsoft\Windows\CurrentVersion\Run\ctfmon.exe")
Copy an item
Example: Copy-Item -Path 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion' -Destination hkcu:
# Why is it not possible to copy from hkcu: to hklm: in reverse?
Create an item
New-item hkcu:\testnewcreate or new-item registry::hkcu:\testnewcreate
# Remember that there is no : in hkcu:\testnew, it should be changed to registry::hkcu\ testnewcreate
# If the newly created item has the same name as the existing item, it can be created forcefully through -force, and others are similar
Create an entry of the new item
Example: New-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion -Name PowerShellPath -PropertyType String -Value $PSHome
Use the value array of the path parameter to create registry entries in multiple locations
Example: new-itemproperty –path hkcu:\software\microsoft\windows\currentversion, hklm:\software\microsoft\windows\currentversion –name testzgk –property string –value “我爱你海红”
# Propertytype reference table
PropertyType values Meaning
Binary Binary data
DWord A valid UInt32 number
ExpandString A string that can contain dynamically expanded environment variables
MultiString Multiline string
String Any string value
QWord 8-byte binary data
Rename a registry entry
Example: Rename-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion -Name PowerShellPath -NewName PSHome –passthru
#-passthru can see the renamed entry name
Delete an item
Remove-item hkcu:\testnewcreate or Remove-item registry::hkcu\ testnewcreate
Example: Delete all items under 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion
Remove-item HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion
If you want to keep the HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion item and only delete all items inside it
Remove-item HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\*
Delete an entry
Example: Remove-ItemProperty -Path HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion -Name PSHome
CMD UNIX used commands corresponding to PowerShell commands and aliases
CMD command Unix command PS command PS alias
dir ls Get-ChildItem gci
cls clear Clear-Host (function) Not available
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
Not available pushd Push-Location Not available
Not available popd Pop-Location Not available