PowerShell 技能连载 - 自动加载 Module

从 PowerShell 3.0 开始,PowerShell 具备了能够智能识别哪些 Cmdlet 是由哪个扩展 Module 导出的特性。所以您再也不需要知道 Module 的名称并且(用 Import-Module 手动导入它)。与之相反,自动完成和智能感知特性将为所有安装在标准 Module 文件夹中的每一个命令提供建议。以下是列出这些标准文件夹的方法:

PS> $env:PSModulePath -split ';'
C:\Users\Victor\Documents\WindowsPowerShell\Modules
C:\Program Files\WindowsPowerShell\Modules
C:\Windows\system32\WindowsPowerShell\v1.0\Modules\

这些标准文件夹也许不一定相同,您可以根据需要增加更多的文件夹到环境变量中,甚至将 Module 存放在 USB 闪存盘或外置驱动器中。以下命令将把 USB 驱动器的路径增加到您的模块列表中,这样在该文件夹中的所有 Module 也将会被自动加载:

PS> $env:PSModulePath += ';g:\mypersonalmodules'

PowerShell 技能连载 - 安装 Windows Server 2012 桌面体验

如果您希望将 Windows Server 2012 (或 Windows Server 2008 R2)作为工作站机器使用并且使它看起来像 Windows 8(包括在文件浏览器中刻录 ISO 文件,以及个性化您的桌面和其它设置),您所需要做的只是添加桌面体验功能。以下是用 PowerShell 实现的方法:

Add-WindowsFeature -Name Desktop-Experience

在 PowerShell 2.0 中,您首先需要手动导入合适的 module:

Import-Module ServerManager

PowerShell 技能连载 - 以不同用户运行 PowerShell

当您将 PowerShell 固定到任务栏后,您可以右键单击固定的 PowerShell 图标来打开一个跳转列表并且使用完整的 Administrator 特权来打开 PowerShell 或 ISE 编辑器。

您还可以按住 SHIFT 键并且右键单击跳转列表中的 PowerShell 图标。这将打开另一个快捷菜单,您可以在这里选择一个完全不同的凭据来运行 PowerShell。

并没有针对 ISE 编辑器的这个选项,但是当您以不同的凭据运行了 PowerShell 之后,您可以简单地键入命令“ise”来以相同的账户运行 ISE 编辑器。

PowerShell 技能连载 - 监测日志文件

从 PowerShell 3.0 开始,实时监测基于文本的日志文件变得很容易。试试以下代码:

$Path = "$home\Desktop\testfile.txt"

'Test' | Out-File "$home\Desktop\testfile.txt"
notepad $Path

Get-Content -Path $Path -Tail 0 -Wait | Out-GridView -Title $Path

这段代码将在桌面上创建一个文本文件,然后在记事本中打开它。然后 PowerShell 将开始监视文件的变化。一旦您向记事本窗口键入新的文本并保存,则变化的部分会呈现在 PowerShell 的网格视图中。

要监视另一个基于文本的日志文件,只需要改变路径参数即可。由于 PowerShell 在监视文件的状态下处于阻塞状态,您可能需要在另一个 PowerShell 实例中执行新的代码。

译者注:Get-Content -Tail 的效果和 Linux 下的 tail -f 命令的执行效果一致。但 PowerShell 是面向 .NET 对象的,可以利用管道和其它命令,例如 Out-GridView 配合,更为强大。

PowerShell 技能连载 - 按 F1 跳转到 PowerShell 帮助主题

要在 PowerShell 3.0 ISE 编辑器中获得 PowerShell 所有类型的操作符帮助信息,首先列出关于操作符的所有帮助主题:

help operators

您将会见到一个类似这样的列表:

PS> help operators

Name                              Category  Module                    Synopsis
----                              --------  ------                    --------
about_Arithmetic_Operators        HelpFile                            SHORT DESCRIPTION
about_Assignment_Operators        HelpFile                            SHORT DESCRIPTION
about_Comparison_Operators        HelpFile                            SHORT DESCRIPTION
about_Logical_Operators           HelpFile                            SHORT DESCRIPTION
about_Operators                   HelpFile                            SHORT DESCRIPTION
about_Type_Operators              HelpFile                            SHORT DESCRIPTION

如果您没有看见这个列表,您也许需要先下载 PowerShell 帮助文档。请通过 Update-Help 来查看方法!

然后,单击其中的任意一个主题,然后按下 F1 键。帮助窗口将会打开,并显示详细的帮助。

PowerShell 技能连载 - 键盘技巧

在 PowerShell ISE 4.0 控制台窗格中,按住 CTRL 键,然后按 向上 键,可以将光标从命令行中移到结果区域中。

PowerShell 技能连载 - 查找缺少邮箱地址的 Active Directory 用户

LDAP 查询的功能非常强大,可以帮助查找缺少信息的账户。

这段代码将返回所有带邮箱地址的 Active Directory 用户:

$searcher = [ADSISearcher]"(&(sAMAccountType=$(0x30000000))(mail=*))"
$searcher.FindAll() |
  ForEach-Object { $_.GetDirectoryEntry() } |
  Select-Object -Property sAMAccountName, name, mail

如果您想查询相反的内容,请通过“!”号进行相反的查询。以下代码可以返回所有缺少邮箱地址的 Active Directory 用户:

$searcher = [ADSISearcher]"(&(sAMAccountType=$(0x30000000))(!(mail=*)))"
$searcher.FindAll() |
  ForEach-Object { $_.GetDirectoryEntry() } |
  Select-Object -Property sAMAccountName, name, mail

用 PowerShell 脚本获取天气实况

只要两行命令,就可以“轻松”地获取实时天气预报:

(curl http://61.4.185.48:81/g/ -UseBasicParsing).Content -cmatch 'var id=(\d+);' | Out-Null
irm "http://www.weather.com.cn/data/sk/$($matches[1]).html" | select -exp weatherinfo

使用效果:

PS >(curl http://61.4.185.48:81/g/ -UseBasicParsing).Content -cmatch 'var id=(\d+);' | Out-Null
PS >irm "http://www.weather.com.cn/data/sk/$($matches[1]).html" | select -exp weatherinfo


city    : 福州
cityid  : 101230101
temp    : 15
WD      : 北风
WS      : 2级
SD      : 79%
WSE     : 2
time    : 10:20
isRadar : 1
Radar   : JC_RADAR_AZ9591_JB

您还可以把第二行改为以下形式,获取更猛的数据:

irm "http://m.weather.com.cn/data/$($matches[1]).html" | select -exp weatherinfo

或:

irm "http://www.weather.com.cn/data/cityinfo/$($matches[1]).html" | select -exp weatherinfo

源代码下载

顺便透露一下,高富帅一般不这么看天气预报哦!

PowerShell 技能月刊

编号 发布时间 标题 PDF
Vol.01 2013年06月 文件系统任务 下载
Vol.02 2013年07月 数组和哈希表 下载
Vol.03 2013年08月 日期、时间和文化 下载
Vol.04 2013年09月 对象和类型 下载
Vol.05 2013年10月 WMI 下载
Vol.06 2013年11月 正则表达式 下载
Vol.07 2013年12月 函数 下载
Vol.08 2013年12月 静态 .NET 方法 下载
Vol.09 2014年01月 注册表 下载
Vol.10 2014年02月 Internet 相关任务 下载
Vol.11 2014年03月 XML 相关任务 下载
Vol.12 2014年08月 安全相关任务 下载

如果您(和我一样)足够懒,也可以用这样一行 PowerShell 代码来下载:

1..12 | ForEach-Object { Invoke-WebRequest "http://powershell.com/cs/PowerTips_Monthly_Volume_$_.pdf" -OutFile "PowerTips_Monthly_Volume_$_.pdf" }

PowerShell 技能连载 - 自动找借口的脚本

译者注:您没有看错!这是近期最邪恶的一个技巧,文末有译者机器上的实验效果。

厌倦了每次自己想蹩脚的借口?以下脚本能让您每调用一次 Get-Excuse 就得到一个新的接口!您所需的一切只是 Internet 连接:

function Get-Excuse
{
  $url = 'http://pages.cs.wisc.edu/~ballard/bofh/bofhserver.pl'
  $ProgressPreference = 'SilentlyContinue'
  $page = Invoke-WebRequest -Uri $url -UseBasicParsing
  $pattern = '<br><font size = "\+2">(.+)'

  if ($page.Content -match $pattern)
  {
    $matches[1]
  }
}

如果您需要通过代理服务器或者身份认证来访问 Internet,那么请查看函数中 Invoke-WebRequest 的参数。您可以通过它提交代理服务器信息,例如身份验证信息。

译者注:以下是 Get-Excuse 为笔者找的“借口”,很有创意吧 ;-)

PS >Get-Excuse
your process is not ISO 9000 compliant
PS >Get-Excuse
evil hackers from Serbia.
PS >Get-Excuse
piezo-electric interference
PS >Get-Excuse
Bogon emissions
PS >Get-Excuse
because Bill Gates is a Jehovah's witness and so nothing can work on St. Swithin's day.
PS >Get-Excuse
Your cat tried to eat the mouse.
PS >Get-Excuse
It works the way the Wang did, what's the problem
PS >Get-Excuse
Telecommunications is upgrading.
PS >Get-Excuse
Your computer's union contract is set to expire at midnight.
PS >Get-Excuse
Daemon escaped from pentagram
PS >Get-Excuse
nesting roaches shorted out the ether cable
PS >Get-Excuse
We ran out of dial tone and we're and waiting for the phone company to deliver another bottle.
PS >Get-Excuse
Root nameservers are out of sync