PowerShell 技能连载 - 查找递归的 AD 成员

在 AD 中,有一个看起来很奇怪的过滤器:1.2.840.113556.1.4.1941。它被称为“链式匹配规则”,可以用来快速查找嵌套的成员。

您所需的是某个成员的 DN。然后,您可以像这样使用它:

1
2
3
4
#requires -Version 1 -Modules ActiveDirectory

$DN = 'place DN here!'
Get-ADGroup -LDAPFilter "(member:1.2.840.113556.1.4.1941:=$($DN))"

Since this is a native LDAP filter, you can even use it without the ActiveDirectory module, resorting to native .NET methods:
由于它是一个原生的 LDAP 过滤器,您甚至可以在没有 ActiveDirectory 模块的情况下以 .NET 原生的方式使用它。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
$DN = 'place DN here!'
$strFilter = "(member:1.2.840.113556.1.4.1941:=$DN)"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry('LDAP://rootDSE')
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = "LDAP://$($objDomain.rootDomainNamingContext)"
$objSearcher.PageSize = 1000
$objSearcher.Filter = $strFilter
$objSearcher.SearchScope = 'Subtree'
$colProplist = 'name'
foreach ($i in $colPropList){
$null = $objSearcher.PropertiesToLoad.Add($i)
}
$colResults = $objSearcher.FindAll()
foreach ($objResult in $colResults)
{
$objItem = $objResult.Properties
$objItem.name
}

PowerShell 技能连载 - 清除回收站

在 PowerShell 5.0 之前,要清除回收站得手工删除每个驱动器根目录下隐藏的 $Recycle.Bin 文件夹里的内容。

有一些作者推荐使用名为 Shell.Application 的 COM 对象。它不一定可靠,因为回收站不一定可见,取决于资源管理器的设置。

幸运的事,PowerShell 5.0 终于提供了 Clear-RecycleBin Cmdlet。

PowerShell 技能连载 - 自动获取重要的支持响应信息

Here is a fun function to provide you with a good first level support response in case everyone is off for Christmas:
这是一个有趣的函数,当所有人都下班去过圣诞时将给您提供重要的支持响应信息。

#requires -Version 3

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

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

您需要 Internet 连接来运行这段脚本。

PowerShell 技能连载 - 查询当前登录的用户名

有两种方式可以查询当前登录的用户:

# User logged on to a physical box
Get-WmiObject -Class Win32_ComputerSystem | Select-object -ExpandProperty UserName


# Owners of explorer.exe processes (desktop is an Explorer process)
Get-WmiObject -Class Win32_Process -Filter 'Name="explorer.exe"'  |
  ForEach-Object {
    $owner = $_.GetOwner()
    '{0}\{1}' -f  $owner.Domain, $owner.User
  } |
  Sort-Object -Unique

两种使用 Get-WmiObject 的方式都支持本地和远程方式调用。

PowerShell 技能连载 - 获取操作系统清单

如果您的老板需要一份您 AD 中所有计算机的操作系统清单,这也许是个好办法:

#requires -Version 1 -Modules ActiveDirectory

$max = 100

$os = Get-ADComputer -Filter * -Properties OperatingSystem -ResultPageSize $max |
Group-Object -Property OperatingSystem -NoElement |
Select-object -ExpandProperty Name |
ForEach-Object { '"{0}"' -f $_ }

$list = $os -join ','
$list
# copy list to clipboard
$list | clip

该脚本将从您的 AD 中获取计算机账户并将它们根据操作系统分组,然后将它整理成一个清单。请注意使用 PageSize 因为在一个大型的组织中获取所有计算机信息可能会花费很长时间。

PowerShell 技能连载 - 根据 OU 分析操作系统

以下是一个快捷的脚本,扫描 Active Directory 中的所有 OU,得到所有的计算机账户,然后将每个 OU 的信息按照操作系统分组:

#requires -Version 2 -Modules ActiveDirectory

Get-ADOrganizationalUnit -Filter * |
  ForEach-Object {
    $OU = $_

    Get-ADComputer -Filter * -SearchBase $OU.DistinguishedName -SearchScope SubTree -Properties Enabled, OperatingSystem |
      Where-Object { $_.Enabled -eq $true } |
      Group-Object -Property OperatingSystem -NoElement |
      Select-Object -Property Count, Name, OU, OUDN |
      ForEach-Object {
        $_.OU = $OU.Name
        $_.OUDN = $OU.DistinguishedName
        $_
      }
  } |
  Out-GridView

PowerShell 技能连载 - 理解 -f 操作符

您也许已经遇到过 -f 操作符并且很好奇它做了什么。它是一个格式化操作符并且提供了一种相当简单的方法来操作数组元素并创建字符串。

让我们从一个值数组开始,比如这个:

$info = 'PowerShell', $PSVersionTable.PSVersion.Major, $pshome

您可以通过序号访问单个数组元素。

PS> $info[0]
PowerShell

PS> $info[1]
4

PS> $info[2]
C:\Windows\System32\WindowsPowerShell\v1.0

如果您需要将该数组的元素合并为一个字符串,这时候 -f 操作符就能够大显身手了。它能够使用相同的序号来读取数组元素并将它们组成一个字符串。以下是一些例子,它们使用 $info 中的信息来组成不同的字符串:

PS> '{0} Version is {1}. Location "{2}' -f $info

PowerShell Version is 4. Location "C:\Windows\System32\WindowsPowerShell\v1.0

PS> '{0} {1}' -f $info

PowerShell 4

PS> '{0} {1:0.0}' -f $info

PowerShell 4.0

PS> '{0}: {2}' -f $info

PowerShell: C:\Windows\System32\WindowsPowerShell\v1.0

PowerShell 技能连载 - 为大量文件建立拷贝备份

PowerShell 可以为您的文件建立备份。您所需要调整的只是需要备份的文件类型,以及您需要备份的目标文件扩展名。

这个例子将影响(直接)存储在您的用户目录下的 PowerShell 脚本。也许这个文件夹下并没有这类文件,所以要么拷入一个文件来测试这个脚本,要么指定一个不同的文件夹路径。

每个脚本将被备份到相同的主文件名,而扩展名为“.ps1_old”的文件中。

当您改变 $Recurese 的值时,脚本将会为您的用户文件夹下的所有 PowerShell 创建备份。

#requires -Version 1

$ExtensionToBackup = '.ps1'
$BackupExtension = '.ps1_old'
$FolderToProcess = $HOME
$Recurse = $false


Get-ChildItem -Path $FolderToProcess -Filter $ExtensionToBackup -Recurse:$Recurse |
  ForEach-Object {
    $newpath = [System.IO.Path]::ChangeExtension($_.FullName, $BackupExtension)
    Copy-Item -Path $_.FullName -Destination $newpath
 }

PowerShell 技能连载 - 将结果通过管道直接传给 Office Word

只需要几行代码,您就可以实现一个 Out-OfficeWord 指令。它接受传入的数据并将它们插入一个新的 Word 文档中(假设 Word 已经安装)。

#requires -Version 1

function Out-OfficeWord
{
  param
  (
    $Font = 'Courier',

    $FontSize = 12,

    $Width = 80,

    [switch]
    $Landscape
  )

  $Text = $Input | Out-String -Width $Width

  $WordObj = New-Object -ComObject Word.Application
  $document = $WordObj.Documents.Add()
  $document.PageSetup.Orientation = [Int][bool]$Landscape
  $document.Content.Text = $Text
  $document.Content.Font.Size = $FontSize
  $document.Content.Font.Name = $Font
  $document.Paragraphs | ForEach-Object { $_.SpaceAfter = 0 }
  $WordObj.Visible = $true
}

要在 Word 中建立一个正在运行中的进程列表,只需要运行这段代码:

Get-Process | Out-OfficeWord -Landscape -Font Consolas -FontSize 8

接下来,您可以将结果另存为 PDF、改进格式,或打印出来。