今天依旧通过PowerShellPlus的示例脚本来学习PowerShell。

## =====================================================================
## Title       : Add-ADUserToGroup
## Description : Add Active Directory User to a Group
## Author      : Idera
## Date        : 9/22/2008
## Input       : -server 
##               -domain
##               -ou
##               -group
##               -user
##               -verbose 
##               -debug   
## Output      : 
## Usage       : PS> .\Add-ADUserToGroup -server localhost:389 -domain Idera -ou sales -group Management -user Joe Smith -verbose -debug
## Notes       : Adapted from Windows PowerShell Cookbook, Lee Holmes
## Tag         : PowerShell, AD
## Change log  :
##  4/1/2009 - Added Read-Host input prompts and Write-Verbose and Write-Debug statements
## =====================================================================

param
(
   [string]$server = "$(Read-Host 'Server [e.g. localhost:389]')", 
   [string]$domain = "$(Read-Host 'Domain [e.g. Idera]')", 
   [string]$ou = "$(Read-Host 'Organizational Unit [e.g. Sales]')",
   [string]$group = "$(Read-Host 'Group [e.g. Outside Sales]')", 
   [string]$user = "$(Read-Host 'User [e.g. Joe Smith]')", 
   [switch]$verbose = $true,
   [switch]$debug = $false
)

function main()
{
	if ($verbose) {$VerbosePreference = "Continue"}
	if ($debug) {$DebugPreference = "Continue"}
	Write-Verbose "Add Active Directory User to a Group..."
	Add-ADUserToGroup $server $domain $ou $group $user
}

function Add-ADUserToGroup($server,$domain,$ou,$group,$user)
{
	trap [Exception] 
	{
		write-error $("TRAPPED: " + $_.Exception.Message);
		continue;
	}

	# The group must be pre-existing for the specified OU and domain
	$groupObj = [adsi]"LDAP://$server/cn=$group,ou=$ou,dc=$domain,dc=COM"
	Write-Debug "Group object is LDAP://$server/ou=$ou,dc=$domain,dc=COM"
	
	# The user must be pre-existing for the specified OU and domain
	$userObj = "LDAP://$server/cn=$user,ou=$ou,dc=$domain,dc=COM"
	Write-Debug "User object is LDAP://$server/cn=$user,ou=$ou,dc=$domain,dc=COM"
	
	Write-Debug "Creating user ($user) in group ($group)"
  	$groupObj.Add($userObj)
}

main

这个脚本的功能是添加AD用户到AD组。

通过参数传递服务器,域,组织单元,用户,组等信息。

49行是骑过ADSI命令连接到LDAP服务器获取组对象。53行是通过ADSI命令获取用户对象。57行就是调用组对象的ADD方法添加用户。

其它的Write-Debug相当对编程语言中的输出Debug日志。只是Cmdlets的输出全部在控制台了。