PowerShell 技能连载 - Read-Host 阻塞自动化操作

使用 Read-Host 向用户提示输入信息可能会造成问题,因为它影响了脚本的自动化运行。一个更好的方法是将 Read-Host 包装在 param() 代码块中。通过这种方式,该信息可以通过无人值守操作的参数传入,也可以通过交互式提示传入:

1
2
3
4
5
6
7
8
param
(
$Name = $(Read-Host -Prompt 'Enter your name'),
$Id = $(Read-Host -Prompt 'Enter your ID')
)


"You are $Name and your ID is $Id"

当您运行以上脚本时,它像 Read-Host 一模一样地显示提示信息。您也可以通过参数执行该脚本:

1
PS> C:\myscript.ps1 –Name test –Id 12

If you do not need custom prompting, you can go even simpler, and declare parameters as mandatory by adding [Parameter(Mandatory)] above each parameter variable.
如果您不需要自定义提示信息,您还可以更加简单,只需要在每个参数变量上加上 [Parameter(Mandatory)] 使它们变为必需参数。

PowerShell 技能连载 - 映射网络驱动器

PowerShell 提供很多种方式来连接到 SMB 文件共享。以下是三种不同的方法:

1
2
3
4
5
6
# adjust path to point to your file share
$UNCPath = '\\server\share'

net use * $UNCPath
New-PSDrive -Name y -PSProvider FileSystem -Root $UNCPath -Persist
New-SmbMapping -LocalPath 'x:' -RemotePath $UNCPath

Net.exe 是最多功能的方法,在 PowerShell 的所有版本中都有效。通过传入一个 “*”,它自动选择下一个有效的驱动器盘符。

New-PSDrive 从 PowerShell 3 起支持 SMB 共享。New-SmbMapping 需要 SmbShare 模块并且现在看来有点古怪:重启后才能在 Windows Explorer 中显示该驱动器。

PowerShell 技能连载 - 安全地删除数据

要安全地删除文件、文件夹,或整个驱动器,PowerShell 可以使用内置的 cipher.exe 工具。这行代码可以安全地删除旧的用户配置文件:

1
Cipher.exe /w:c:\Users\ObsoleteUser

请注意要删除的文件夹路径和参数 /w 之间需要用一个 : 分隔。删除数据需要消耗一定时间:Windows 要多次覆盖整个数据内容,以确保它不可恢复。

PowerShell 技能连载 - 查找 OU

(来自 Microsoft 免费的 RSAT 工具的)Get-OrganizationalUnit 可以基于识别名或 GUID 来搜索 OU,或者可以使用 -Filter 参数。

不幸的是,-Filter 不能方便地自动化。以下代码并不能工作,并不能返回所有名字中包含 “Test” 的 OU:

1
2
$Name = 'Test'
Get-ADOrganizationalUnit -Filter { Name -like "*$Name*" }

这个结果很令人惊讶,因为以下这行代码可以工作(前提是您确实有名字包含 “Test” 的 OU):

1
Get-ADOrganizationalUnit -Filter { Name -like "*Test*" }

通常情况下,如果您想用简单的通配符来搜索,那么使用简单的 LDAP 过滤器十分管用。以下代码查找所有名字中包含 “Test” 的 OU:

1
2
$Name = 'Test'
Get-ADOrganizationalUnit -LDAPFilter "(Name=*$Name*)"

PowerShell 技能连载 - 测试 OU

假设您已安装了免费的 Microsoft RSAT 工具,以下是一个简单的方法来检测一个 OU 是否存在:

1
2
3
$OUPath = 'OU=TestOU,DC=train,DC=powershell,DC=local'
$exists = $(try { Get-ADOrganizationalUnit -Identity $OUPath -ErrorAction Ignore } catch{}) -ne $null
"$OUPath : $exists"

$exits 的值将是 $true$false,表示是否找到该 OU。请注意使用 try/catch 处理错误的方法:Get-ADOrganizationalUnit 将在指定的 OU 不存在时抛出终止错误,所以需要 try/catch 来捕获这些错误。

PowerShell 技能连载 - 验证变量有效性

变量和函数参数可以通过验证属性自动地验证有效性。以下是一个简单的例子,确保 $test1 只能存储 1-10 之间的值:

1
[ValidateRange(1,10)]$test1 = 10

当您将一个小于 1 或大于 10 的值赋给这个变量,PowerShell 将会抛出一个异常。不过通过这种方式您无法控制异常的问本。

通过使用脚本验证器,您可以选择自己希望的错误信息:

1
2
3
4
5
6
7
8
[ValidateScript({
If ($_ -gt 10)
{ throw 'You have submitted a value greater than 10. That will not work, dummy!' }
Elseif ($_ -lt 1)
{ throw 'You have submitted a value lower than 1. That will not work, dummy!' }

$true
})]$test2 = 10

以下是输出结果:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
PS C:\> $test2 =  4

PS C:\> $test2 = 11
You have submitted a value greater than 10. That will not work, dummy!
At line:5 char:3
+ { throw 'You have submitted a value greater than 10. That will not work, dummy ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (You have submitted a...not work, dummy!:String
) [], RuntimeException
+ FullyQualifiedErrorId : You have submitted a value greater than 10. That will not work, dummy!



PS C:\> $test2 = -2
You have submitted a value lower than 1. That will not work, dummy!
At line:7 char:3
+ { throw 'You have submitted a value lower than 1. That will not work, dummy ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (You have submitted a...not work, dummy!:String
) [], RuntimeException
+ FullyQualifiedErrorId : You have submitted a value lower than 1. That will not work, dummy!

PowerShell 技能连载 - 克隆 DHCP 服务器设置

从 Windows Server 2012 开市,您可以快速地导出和重新导入 DHCP 设置。克隆或迁移 DHCP 服务器是通过快照的形式。以下的例子从 \ORIGDHCP 导出设置并导入本地的 DHCP 服务器中:

1
2
Export-DHCPServer -File "$env:temp\dhcpsettings.xml" -Computername ORIGDHCP
Import-DHCPServer -File "$env:temp\dhcpsettings.xml"

PowerShell 技能连载 - 搜索 AD 用户

免费的 Microsoft RSAT 工具给我们带来了 “ActiveDirectory” PowerShell module:许多 cmdlet 可以帮助您管理 Active Directory 用户和计算机。

一个 cmdlet 特别有用。与其使用 Get-ADUser 和复杂得过滤器来查找 AD 用户,我们可以使用更方便的 Search-ADAccount。它注重于某些公共场景的查找用户功能。例如这行代码可以找出所有 120 天未活跃的用户账户:

1
Search-ADAccount -AccountInactive -TimeSpan 120 -UsersOnly

PowerShell 技能连载 - 生成随机密码

以下是一个非常简单的创建复杂随机密码的方法:

1
2
3
4
Add-Type -AssemblyName System.Web
$PasswordLength = 12
$SpecialCharCount = 3
[System.Web.Security.Membership]::GeneratePassword($PasswordLength, $SpecialCharCount)

The API call lets you choose the length of the password, and the number of non-alphanumeric characters it contains.

PowerShell 技术 QQ 群