Windows Powershell 3 极速入门

Learn Windows PowerShell 3 in a Month of Lunches(2rd)

2013, DON JONES

  这本书基于 PowerShell 3.0,做初学者教材甚好,若有 Linux shell 基础则可一目十行。如下便是摘录式笔记,仅记录一些感兴趣的重点,涉及大部分章节。
  书中很少涉及语法,因为按作者的说法:操起命令直接上,这才是 PS 的主要使用模式(PowerShell-ish ways),而非一般的脚本编程,流控之类的语法都只是命令的粘合剂。
  读完一遍,对 PS 突出印象:

  • 现代化的、风格一致的设计
    应该借鉴了 Linux shell、python、C# 等;一致性降低了学习使用成本
  • 面向对象、基于 .NET 框架
    一切皆对象,消除了无结构文本的弊端;可以直接使用 .NET 对象,功能真强
  • 命令式
    开发迭代模型:run—result—modify—retry
ch2. Meet PowerShell(初识 PS)

PowerShell 包含两个组件:

  1. PS console
    轻快,不支持双字节字符集,无补全
  2. PS ISE (integrated scripting environment)
    基于 WPF,支持中文,强大的帮助与补全

查看版本号: $PSVersionTable

ch3. Using the help system(帮助系统)

媲美 GUI 的 CLI 帮助系统:能迅速找到命令并了解其用法(支持通配符)

  • Get-Command 查找匹配的命令
  • Get-Help 查看命令用法
  • Get-Member 查看对象的类型和成员
  • Help 是 function,相当于 Get-Help | More
    查看示例:Help Get-EventLog -example
    详细信息:Help -full
  • Show-command 带 GUI 帮助的填写

4 种命令 Command:cmdlet(命名约定 verbs+nouns),function,workflow,externApp。例: Get-Service -name e,s*
帮助系统先升级:update-help(-Source 可指定本地更新源)
多个参数搭配路径

ch4. Running commands(命令)

cmdlet:原生命令,为 .Net 语言编写

  • 可选 optional 参数整个在方括号里 [-ComputerName <string[]>],这里的数组用逗号分隔的列表表示;用参数缩写时能唯一标识即可,如 -comp
  • 否则为强制 mandatory 参数,[-LogName] <string>
  • 若参数名称也在方括号里,则为位置 positional 参数

externApp(外部命令,但应优先用 cmdlet)
$exe = “C:\mount.exe”
$host = “srv”
$user = “nick”
& $exe -h $host -u $user
新写法:-- C:\mount.exe -h srv -u nick,会直接传给 cmd,不解析

ch5. Working with providers

PSProvider 适配器,以类文件系统的方式,来导航与管理数据存储(动态结构),如注册表。查看可用:Get-PSProvider
相关 cmdlet 的 noun 常带 “Item”(指单独对象,如文件)
ItemProperty 表示 item 属性,如只读,一般都有 -Path 属性,支持通配符;ChildItem 指子对象

ch6. The pipeline: connecting commands(Pipeline)
ch7. Adding commands(PS 扩展机制)

两种:module 和 snap-in(dll+xml)
get-pssnapin -registered 注册
add-pssnapin sqlservercmdletsnapin100,sqlserverprovidersnapin100
Get-Command -pssnapin sqlservercmdletsnapin100
module 不用注册,根据 $PSModulePath 自动发现,按需加载
get-command -Module DnsClient

有些特定的管理 shell 其实是带参数启动 powershell.exe -noexit -command import-module ActiveDirectory

ch8. Objects: data by another name(对象)

查看:get-process | get-member

a collection of objects as a big in-memory table of
information, with propertiesas the columns and individual objects the rows.

PS 对象一般来自 .net 框架,但 ETS(Extensible Type System)会添加些额外属性(ScriptProperty,NoteProperty,AliasProperty)以利使用。
对象的 property 用的很多,但 action/method 很少用,因为通常由 cmdlet 实现
Get-Process | Sort-Object VM,ID -desc
Get-Process | Select-Object Name,ID,VM,PM
Select-Objectis 用来选择或新建 properties(会产生新对象), 以及特定行,-expandProperty 可以获取值列表. 而 Where-Object 根据指定条件删除或过滤 pipeline 里的 objects。
pipeline 的每一步都可能产生不同对象,所以要用 gm 来确定

ch9. The pipeline,deeper(深入 pipeline)

Pipeline parameter binding:
Try1. ByValue:把输入与参数类型进行匹配;参数需支持pipelineInputByValue(可通过 Help -full 查看);仅能匹配一个参数(能否手动指定?)
Try2. ByPropertyName:仅名字匹配;需支持pipInByPropertyName;多参数匹配
圆括号命令用法:
Get-WmiObject -class Win32_BIOS -ComputerName (Get-Content .\comput
ers.txt)

ch10. Formatting—and why it’s done on the right(格式化)
ch11. Filtering and comparisons(过滤与比较)
  • Filter left (命令需支持 -filter 参数)
  • Where-Object(使用类似的比较符)
    Get-Service | Where { $_.Status -eq ‘Running‘ } --> Get-Service | Where Status -eq ‘Running‘(单条件可化简)
    (5 -gt 10) -and (10 -gt 100)
    $_.Responding -eq $False
ch12. A practical interlude(实践)
  • 需求:remove all print jobs from a local printer “Accounting” every 3 a.m.
  • 寻找命令 help *task*;get-command -module scheduledtasks
  • 学习用法 help new-scheduledtask -full
ch13. Remote control: one to one, and one to many
ch14. Using Windows Management Instrumentation(WMI)

WMI 能够获取大量系统信息,但不好用(缺乏统一规划,文档缺乏)。对 PS 来说只是个可以借用的外部技术,建议使用 CIM 封装命令与之交互



wmi 必知必会

repository
— namespace 例如 root\CIMv2 就包含了所有系统和硬件信息
— class 代表管理组件,一个实例对应一个现实组件
软件:wmi explorer


  • Get-WmiObject(retrieve all instances of that class from the computer specified,legacy!) + Invoke-WmiMethod
    查看 Get-WmiObject -Namespace root\CIMv2 -list | where name -like ‘dis
    gwmi -class win32_desktop -filter “name=’COMPANY\Administrator’”
  • Get-CimInstance + Invoke-CimMethod
    查看 Get-CimClass -Namespace root\CIMv2
    Get-CimInstance -ClassName Win32_LogicalDisk
ch15. Multitasking with background jobs(后台多任务)

Help * -parameter asjob

ch16. Working with many objects, one at a time(批量操作)

批量操作的三种方法:batch cmdlets, WMImethods, and object enumeration.

  • Get-Service -name BITS,Spooler,W32Time -computer Server1,Server2,Server3 | Set-Service -passthru -startuptype Automatic
    Stop-Service -name *B*
    缺点是批量处理时一般没有输出,此时可以使用 -passThru 来查看被处理的输入
  • gwmi win32_networkadapterconfiguration -filter “description like ‘%intel%’” | Invoke-WmiMethod -name EnableDHCP
    会输出一个 result object,可以看到每个操作的 ReturnValue,但无法分辨
  • gwmi win32service -filter “name = ‘BITS’” | foreach-object {$.change($null,$null,$null,$null,$null,$null,$null,”[email protected]”) }
ch17. Security alert
ch18. Variables: a place to store your stuff(变量)

一切皆对象
${My Variable} = ‘SERVER-R2’,’SERVER1’,’localhost’
[int]$number = Read-Host “Enter a number”(类型声明)

‘$‘ is a cue to the shell that what follows is going to be a variable name, and that we want to access the contents of that variable.

能够存放多个不同类型的对象
单引号 — a literal string
双引号 — expansion string,但仅在初始解析时替换!
转义符 — ˜
subexpression — $(cmd) ==> string

ch19. Input and output
ch20. Sessions: remote control with less work

长连接
$iis_servers = new-pssession -comp web1,web2,web3

  • Using sessions with Enter-PSSession(interactive)
  • Using sessions with Invoke-Command
    invoke-command -command { get-wmiobject -class win32_process } -session (get-pssession -comp loc*)
  • Disconnect & Reconnect session
ch21. You call this scripting?

如何写 help 文档
One script, one pipeline

within a script, you only have one pipeline to work with.
Normally, your scripts should strive to only output one kind of object, so that PowerShell can produce sensible text output.
ch22. Improving your parameterized script(命令行选项)
ch23. Advanced remoting configuration
ch24. Using regular expressions to parse text files
ch25. Additional random tips, tricks, and techniques
ch26. Using someone else’s script
ch27. Never the end

进阶学习:

  • PowerShell’s simplified scripting language
  • Scope
  • Functions, and the ability to build multiple tools into a single script file
  • Error handling
  • Writing help
  • Debugging
  • Custom formatting views
  • Custom type extensions
  • Script and manifest modules
  • Using databases
  • Workflows
  • Pipeline troubleshooting
  • Complex object hierarchies
  • Globalization and localization
  • GUI-based PowerShell tools
  • Proxy functions
  • Constrained remoting and delegated administration
  • Using .NET
时间: 2024-08-10 19:15:41

Windows Powershell 3 极速入门的相关文章

有奖试读—Windows PowerShell实战指南(第2版)

为什么要学PowerShell? Windows用户都已习惯于使用图形化界面去完成工作,因为GUI总能轻易地实现很多功能,并且不需要记住很多命令.使得短时间学会一种工具成为可能. 但是不幸的是,GUI并不能带来效率提升上的汇报,如果你花费5分钟在活动目录中创建一个新的用户(一般需要填写大量信息),之后再新建用户时,通常不会更快,那么新建100个新用户就会花费500分钟,通常没有任何办法使得我们输入信息以及单击操作更快,从而加快这个过程. 微软一直都有CMD命令来进行Windows的操作,但是很不

《Python黑客编程之极速入门》正式开课

玄魂 玄魂工作室 今天 之前开启了一个<Python黑客编程>的系列,后来中断了,内容当时设置的比较宽,不太适合入门.现在将其拆分成两个系列<Python黑客编程之极速入门>和<Python黑客编程之网络安全>,以便初学者有一个入门和提升的过程. 我们首先开启的是<Python黑客编程之极速入门>,考虑到学习质量的保证问题, 这次采用的是培训的方式,图文教程+课后练习+答疑+案例介绍+扩展阅读. 培训目前只面向我们知识星球内部成员(加入星球自动享受该课程权益

Windows下FFmpeg高速入门

本系列文章导航 Windows下FFmpeg高速入门 ffmpeg參数解释 mencoder和ffmpeg參数具体解释(Java处理视频) Java 生成视频缩略图(ffmpeg) 使用ffmpeg进行视频文件转换成FLV整理 java 视频处理 mencoder java 视频处理 ffmped+mencoder Windows下FFmpeg高速入门 FFmpeg简单介绍 FFmpeg是什么? FFmpeg是用于录制.转换和流化音频和视频的完整解决方式, 包含 libavcodec ,一套率先

Windows Server 2008 R2入门之用户管理

今天为大家带来的是Windows Server 2008 R2入门之用户管理,以便大家更快的熟悉2008r2工作组中用户.组的创建.删除.日常管理等,接下来我们直接进入正文. 一.用户账户概述: "用户"是计算机的使用者在计算机系统中的身份映射,不同的用户身份拥有不同的权限,每个用户包含一个名称和一个密码: 在Windows中,每个用户帐户有一个唯一的安全标识符(Security Identifier,SID),用户的权限是通过用户的SID记录的.SID的格式如下所示:S-1-5-21

Windows PowerShell 学习---第一章 PowerShell介绍

第1章 PowerShell介绍 1.1.什么是PowerShell 2006年,微软发布一款叫做Windows PowerShell的全新脚本语言. PowerShell与命令提示符shell一样,PowerShell可以进行交互性地输入命令.也可以很容易的使用管道和重定向将文件和程序串联起来. 不过,PowerShell确是一个强大的面向对象的语言,可以用于复杂的脚本编程. 1.2.面向对象的命令shell 关于cmd 如果在命令提示符下输入dir,dir命令将会在屏幕打印出目录中的文件名.

部署 Windows PowerShell Web 访问

部署 Windows PowerShell Web 访问 适用对象:Windows Server 2012, Windows Server 2012 R2 Windows PowerShell® Web Access 在 Windows Server® 2012 中首次引入,充当 Windows PowerShell 网关,可提供以远程计算机为目标的基于 Web 的 Windows PowerShell 控制台. 它可让 IT 专业人士在 Web 浏览器中运行来自 Windows PowerSh

在 Windows 7 和 Windows Server 2008 R2 上安装 Windows PowerShell 3.0

在 Windows 7 和 Windows Server 2008 R2 上安装 Windows PowerShell 3.0 Windows 7 和 Windows Server 2008 R2 内核版本同为6.1,以下步骤说明如何在运行 Windows 7 SP1 和 Windows Server 2008 R2 SP1 的机器上安装 Windows PowerShell 3.0. 安装准备 1. 在安装Windows Management Framework 3.0之前,卸载任何Windo

使用 Windows PowerShell 来管理和开发 windowsazure.cn 账户的特别注意事项

6月6日,微软面向中国大陆用户开放了Microsoft Azure公众预览版的申请界面.大家可以申请免费的 beta 试用,收到内附邀请码的通知邮件后只需输入激活码即可开始免费试用.具体网址为: http://windowsazure.cn/zh-cn/pricing/free-trial/ 在实际使用这个账号的时候,发现有一些地方需要特别注意. 在使用PowerShell工具中,需要下载发布配置文件(PublishSettingProfile),从而获得设置Windows PowerShell

Windows PowerShell 会话中使用 FSharp 代码编译器

<# $fSharpCode= @" moduleTest let HelloWorld = "Hello World!!!!" printfn "%s" HelloWorld let rec Loop n = seq [ if n <= 0 then () else yield n; yield! Loop (n-1) ] |> Seq.sort printfn "%A" (Loop 5) let rec facto