번역 제안
 
다른 사람들의 제안:

progress indicator
다른 제안이 없습니다.
TechNet Magazine > Home > All Issues > 2009 > TechNet Magazine 6월 2009 >  Windows PowerShell: 자동화 사용자 제공, 파트 4
내용 보기:  나란히내용 보기: 나란히
이 내용은 기계 번역되었으며 커뮤니티 구성원이 편집할 수 있습니다. 아래의 각 문장과 연결된 "편집" 링크를 클릭하여 번역을 개선해 주시기 바랍니다.
Windows PowerShell Automating User Provisioning, Part 4
Don Jones


This is the conclusion of a four-part series in which I've shown you how to automate the process of provisioning new users in Active Directory. So far, I've demonstrated how to create new user Active Directory accounts, create their home folders, and assign permissions to these home folders. Now, I need to add the users to some domain groups and update a few directory attributes.
To quickly refresh your memory, I am using a "master function" to coordinate all these efforts, which I explained in Part 1 of this series. The master function looks like this:
Function Provision {
  PROCESS {
    CreateUser $_
    CreateHomeFolder $_
    AddToGroups $_
    UpdateAttributes $_
  }
}
In Part 2 of the series, I created the CreateUser function, and in Part 3, I covered the CreateHomeFolder function. This month, I will deal with the AddToGroups and UpdateAttributes functions.

Deciding On Input
All four of my functions get a hashtable that contains user attributes. My original example, in Part 1, read those attributes from a Comma-Separated Values (CSV) file. At the time, I didn't go into much depth on how I planned to convey what domain groups a user should be added to. There are a lot of ways I could potentially do this. For example, I could have my CSV file include a single column named Groups and populate that column with some delimited list of names, like this:
"Domain Users,Sales,Marketing,East"
Or, I could have a separate column in the CSV for each group and then on the data rows put a 1 when the user should belong to that group and a 0 for groups I don't want the user to belong to. It might look like this in the CSV:
Domain Users,Sales,Marketing,East
1,1,0,0
1,0,1,1
I suspect that the second approach might be easier for a less-technical person (perhaps someone in the Human Resources department) to work with since it looks a bit more like a checklist. This is also something you could easily create in a Microsoft Access table or a Microsoft Excel spreadsheet and then export to a CSV file, retaining this format. So for this example, I'm going to go with the second layout.
As for the "additional attributes," I'll continue to assume those are coming from specific columns in the CSV file. For example, if I want to populate the postalCode attribute, then let's assume that I've included an appropriate column in the CSV file, and that my Import function (which I discussed in Part 1 of this series) is reading that column into the hashtable along with the other columns.
That means my hashtable may contain something like $userinfo['Domain Users'], which would be 1 if I want the user to belong to that group. The hashtable might also contain $userinfo['postalCode'] with the appropriate value for each new user.

Populating Groups
My AddToGroups function needs to accommodate every possible group that might be listed in my input file. I'm basically just going to check for each group to see if this user has a 1 or 0, and if the user has a 1, then I'll add the user to the group. Since the number 0 is usually synonymous with the Boolean value False, while anything non-zero (such as 1) is synonymous with True, that will make the comparisons pretty easy. So the function looks like this:
Function AddToGroup {
  Param($userinfo)
  If ($userinfo['Sales']) { Add-QADGroupMember 
    -identity 'DOMAIN\Sales' '
    -member ('DOMAIN\'+$userinfo
     ['samAccountName']) }
  If ($userinfo['East]) { Add-QADGroupMember 
    -identity 'DOMAIN\East' '
    -member ('DOMAIN\'+$userinfo
     ['samAccountName']) }
  If ($userinfo['Marketing]) { Add-
    QADGroupMember 
    -identity 'DOMAIN\Marketing' 
    -member ('DOMAIN\'+$userinfo
     ['samAccountName']) }
}
And so forth. Keep in mind that we're still using the Quest AD Cmdlets, which are free from www.quest.com/powershell .
All that repetitive code bugs me. I think what I'd like to do instead is create an array of possible group names and then enumerate through that array. That way, adding and removing groups in the future doesn't require me to copy and paste code—I'd just have to modify the array. So now the function looks like this:
Function AddToGroup {
  Param($userinfo)
    $groups = 'Sales','Marketing','East'
  Foreach ($group in $groups) {
    If ($userinfo[$group]) { 
      Add-QADGroupMember
        -identity 'DOMAIN\'+$group
        -member ('DOMAIN\'+$userinfo
         ['samAccountName']) }
}
}
That's a bit leaner and cleaner, and it will easily accommodate future changes.

Additional Attributes
Finally, I need to deal with any additional attributes that I want to set. Here I am going to use the same approach: Create an array of allowable attribute names and then enumerate through that array. In this case, I'm going to allow for a situation where one or more attributes are blank for a given user, like so:
Function UpdateAttributes {
  Param($userinfo)
    $attribs = 'postalCode','title',
      'physicalDeliveryOfficeName'
  Foreach ($attrib in $attribs) {
    If ($userinfo[$attrib] –ne '') {
      $update = @{$attrib=$userinfo
       ['attrib']}
    Set-QADUser
      -identity 'DOMAIN\'+$userinfo
       ['samAccountName'] 
      -objectAttributes $update
    }
  }
}
Because the Set-QADUser cmdlet actually accepts a hashtable for the –objectAttributes parameter, you might think I can just feed it the $userinfo hashtable. However, I have things in there, such as group names, that aren't Active Directory attribute names so that trick wouldn't work. Furthermore, I don't want to send any empty attributes, so I want the ability—as I've done with this function—to run through all the attributes first and then update only the attributes that actually have values in the original CSV file.

Taking It Further
There are obviously a lot of things you could do to expand this script. Here are a few ideas that come to mind:
  • Instead of retrieving information from a CSV file, you could get it from a database (such as a personnel database). You just need to replace the Import function, as discussed in Part 1 of this series.
  • You could perform other provisioning tasks. You just need to add more functions to the master Provision function. Remember to keep each major task in its own subordinate function and you'll make things easier to write, debug, and maintain.
  • You could write out a log file of provisioning activity. For example, you can use Out-File to append text to a log file within each of the subordinate functions.
  • Using the techniques covered in this series, you can write a reprovisioning script to reassign groups, permissions, and Active Directory attributes when a user moves to a different position within the company.
Windows PowerShell Q&A

Q What Microsoft products can be managed with Windows PowerShell cmdlets?

ACurrently, the list includes Exchange Server 2007, System Center Virtual Machine Manager, System Center Operations Manager, and System Center Data Protection Manager. SQL Server 2008 also includes some Windows PowerShell cmdlets, although they're largely geared toward enabling the execution of Transact-SQL statements (Transact-SQL being the native scripting language in SQL Server).
But there's no reason to stop there. You can also manage Active Directory using a free set of cmdlets from www.quest.com/powershell ; cmdlets for Internet Information Services (IIS) 7.0 are under development; and there are even cmdlets for non-Microsoft products, such as VMWare, IBM WebSphere MQ, and more. You can also use existing command-line tools to manage Windows components, such as IIS, DNS, DHCP, Windows Firewall, and more.

Some Final Thoughts
I hope you'll find the completed script and all its subordinate functions to be, at the very least, a useful starting point in creating your own provisioning scripts. By way of conclusion, I want to offer a few comments on some of the decisions I've made throughout.
I chose to use hashtables for the user information rather than custom objects because hashtables provide a somewhat easier way to enumerate through a set of properties when I don't know in advance what all those properties will be. In other words, hashtables are a bit easier to use when I know that I will need to add more attributes, and when I might not use the same attributes every time I run the script.
I chose to use Cacls.exe to modify folder permissions because, as I described in Part 3 of this series, it's just easier than the shell's *-ACL cmdlets. Also, using Cacls.exe allowed me to demonstrate one way that you can parameterize external command-line tools by using shell variables.
I chose to use Quest's Active Directory cmdlets rather than ADSI because the cmdlets offer what I feel is a more native approach to manipulating the directory in Windows PowerShell. ADSI can be a pain to work with, and it forces you to use a more procedural programming style over the command-centric style I was able to use in this example.
Whether or not you choose to make the same decisions for your scripts, I hope you'll find these techniques and different approaches useful in solving some of your administrative automation challenges. I also invite you to share your suggestions and improvements with me. On my Web site, ConcentratedTech.com, you'll find a Contact page where you're welcome to send me an e-mail. And please be sure to let me know if I can share your comments in a future issue of TechNet Magazine.

Don Jones is a co-founder of Concentrated Technology , where he blogs weekly about Windows PowerShell, SQL Server, App-V, and other topics. Contact him through his Web site.

Windows PowerShell 사용자 제공, 파트 4 자동화
Don Jones


이것은 있는 I 이미 살펴보았습니다 새 Active Directory 사용자 프로비저닝 과정을 자동화하는 방법을 4회에 결론. 지금까지 Active Directory 계정에 새 사용자 만들기, 해당 홈 폴더 만들기 및 홈 폴더 사용 권한을 할당합니다 방법을 보여 주는 I 완료. 이제 필자는 할 일부 도메인 그룹에 사용자를 추가할 몇 가지 디렉터리 특성을 업데이트합니다.
사용자 메모리 빠르게 고치려면 " 마스터 함수를 " 사용하여 I 있을 모든 이러한 노력을, 이 연재 기사의 Part 1 설명되어 있는 조정하기 위해. 마스터 함수는 다음과 같습니다.
Function Provision {
  PROCESS {
    CreateUser $_
    CreateHomeFolder $_
    AddToGroups $_
    UpdateAttributes $_
  }
}
Part 2 계열의 I CreateUser 함수를 만들고 파트를 3에서 CreateHomeFolder 함수를 다루는 I. 이번 달 I 됩니다 처리하는 AddToGroups 및 UpdateAttributes 함수를.

입력 설정 결정
내 함수의 네 모두 사용자 특성이 들어 있는 해시 테이블의 가져옵니다. 원래 예제에서는 파트 1 에서 Comma-Separated 값 (CSV) 파일에서 이러한 특성을 읽습니다. 시 I 않았습니다 갖춥니다 훨씬 깊이 I 계획된 방법에 따라 어떤 도메인 사용자 그룹을 전달하기 위해 추가해야 합니다. 많은 방법으로 이 잠재적으로 실행할 수 있으며 예를 들어, 내 CSV 파일 그룹 이름이 단일 열을 포함하고 같은 이름의 일부 구분된 목록 사용하여 해당 열에 채우기 있을 I 못했습니다.
"Domain Users,Sales,Marketing,East"
또는 각 그룹에 대해 CSV 별도의 열에 있는 I 수 클릭한 다음 데이터에 대한 행 넣을 1 사용자가 합니다 속해 있는 그룹 및 그룹에 대해 0을 원하지 사용자가 속한 경우. 다시 이 있는 경우 CSV 다음과 같습니다.
Domain Users,Sales,Marketing,East
1,1,0,0
1,0,1,1
필자는 의심되는 검사 같은 더 보이는 이후 작동하도록 두 번째 방법은 (아마도 다른 인사 부서의 (낮은 기술 사람을 쉽게 수 있습니다. 이것은 수 수 쉽게 Microsoft Access 테이블에 또는 Microsoft Excel 스프레드시트를 만들 내보낸 다음 CSV 파일에 이 형식을 유지하면서 내용이 또한. 따라서 예를 들어, 두 번째 레이아웃이 이동 이동하는 'm I.
" 추가 특성을 " 경우와 이러한 CSV 파일에 특정 열에서 들어오는 가정합니다 계속 I 것입니다. 예를 들어, 다음 보겠습니다 postalCode 특성을 채우는 하려면 있는 CSV 파일에 해당 열 포함되어 있습니까 적이 있으며 이 연재 기사의 1부에서 설명한) 내 가져오기 함수를 열을 다른 열과 함께 해시 테이블의 읽어들이는 경우 있는 가정하십시오.
내 해시 테이블의 있을 같이 $ userinfo [' Domain Users '], 사용자가 해당 그룹에 속할 수 하려면 1 됩니다 있는 의미합니다. 도 해시 테이블의 각 새로운 사용자에 대해 적절한 값으로 $ userinfo [' postalCode '] 포함될 수 있습니다.

그룹 채우기
내 AddToGroups 함수를 포함할 모든 가능한 그룹에서 내 입력 파일에 있는 나열될 수 있습니다 합니다. 필자는 'm 기본적으로 바로 이동하는 경우 이 사용자가 1 또는 0, 추가하고 사용자가 1 있으면 I 살펴보겠습니다 사용자 그룹에 보려면 각 그룹을 확인합니다. 아무 것도 없는 동안 부울 값을 False로 일반적으로 동의어 경우 숫자 0-1) 로 0은 동의어 이후 True, 함께 있는 됩니다 쉽게 비교를 매우. 따라서 함수는 다음과 같습니다.
Function AddToGroup {
  Param($userinfo)
  If ($userinfo['Sales']) { Add-QADGroupMember 
    -identity 'DOMAIN\Sales' '
    -member ('DOMAIN\'+$userinfo
     ['samAccountName']) }
  If ($userinfo['East]) { Add-QADGroupMember 
    -identity 'DOMAIN\East' '
    -member ('DOMAIN\'+$userinfo
     ['samAccountName']) }
  If ($userinfo['Marketing]) { Add-
    QADGroupMember 
    -identity 'DOMAIN\Marketing' 
    -member ('DOMAIN\'+$userinfo
     ['samAccountName']) }
}
및 등. 자유롭게 Quest AD cmdlet 여전히 사용하고 있음을 염두에 www.quest.com/powershell .
모든 반복적인 코드를 버그를 표시. 어떤 I 'd 같이 하려면 생각합니다 대신 가능한 그룹 이름의 배열을 만들고 해당 배열을 열거하는 있습니다. 따라서 추가 및 앞으로 그룹을 제거하는 필요하지 않습니다 코드를 복사하여 알림 즉 I 'd 바로 배열의 수정해야 할. 이제 함수는 다음과 같습니다.
Function AddToGroup {
  Param($userinfo)
    $groups = 'Sales','Marketing','East'
  Foreach ($group in $groups) {
    If ($userinfo[$group]) { 
      Add-QADGroupMember
        -identity 'DOMAIN\'+$group
        -member ('DOMAIN\'+$userinfo
         ['samAccountName']) }
}
}
있는 비트 leaner 및 클리너, 있으며 나중에 변경 내용을 쉽게 맞게 됩니다.

추가 특성
마지막으로, 설정하려면 I 추가 특성을 처리해야 합니다. 여기에 같은 방법을 사용할 것인지 중 I: 허용되는 특성 이름의 배열을 만들고 해당 배열을 열거합니다. 이 경우 하나 이상의 특성이 지정된 사용자에 대한 비어 있는 상황을 위한 것인지 'm I 같이:
Function UpdateAttributes {
  Param($userinfo)
    $attribs = 'postalCode','title',
      'physicalDeliveryOfficeName'
  Foreach ($attrib in $attribs) {
    If ($userinfo[$attrib] –ne '') {
      $update = @{$attrib=$userinfo
       ['attrib']}
    Set-QADUser
      -identity 'DOMAIN\'+$userinfo
       ['samAccountName'] 
      -objectAttributes $update
    }
  }
}
Set-QADUser cmdlet을 실제로 –objectAttributes 매개 변수에 대한 해시 테이블의 허용하는, 없으므로 I 수 바로 피드 이를 $ userinfo 해시 테이블의 생각할 수 있습니다. 그러나 해당 트릭을 작동하지 않는 Active Directory 특성 이름 없는 그룹 이름 같은 있습니다 수행할 있어야. 또한 않으려는 기능을 원하는 있으므로 모든 빈 특성을 보낼 (필자는 이 함수를 사용하여 수행한 것처럼, 즉 모든 특성을 통해 처음 실행할 및 원본 CSV 파일에 실제로 값이 있는 특성을 업데이트할.

It 추가로 수행
물론 확장하려면 이 스크립트를 실행할 수 작업 많은 가지 있습니다. 고려하여 제공되는 몇 가지 아이디어 다음과 같습니다.
  • CSV 파일에서 정보를 검색하는 대신 못했습니다 메시지가 해당 (예: 직원 데이터베이스) 데이터베이스에서. 바로 이 연재 기사의 Part 1에서 설명한 것처럼 가져오기 함수를 대체해야 합니다.
  • 기타 준비 작업을 수행할 수 수 있습니다. 방금 마스터 Provision 함수를 자세한 기능을 추가해야 합니다. 각 주요 작업을 하위 기능을 유지하기 위해 기억하고 살펴보겠습니다 쉽게 수 작업을 쓰기, 디버깅 및 유지.
  • 프로비저닝 활동을 중 로그 파일을 작성할 수 있습니다. 예를 들어, 수 수 사용합니다 하위 함수의 각 로그 파일에 텍스트를 추가할 Out-File.
  • 이 기술을 사용하여 다루는, 회사 내의 다른 위치로 이동할 때 그룹, 권한 및 Active Directory 특성을 다시 reprovisioning 스크립트를 작성할 수 있습니다.
Windows PowerShell 질문과 대답

Q: 어떤 Microsoft 제품에 Windows PowerShell cmdlet을 사용하여 관리할 수 있습니다.?

A현재 목록에는 Exchange Server 2007, System Center Virtual Machine Manager, System Center Operations Manager 및 System Center Data Protection Manager가 포함됩니다. 또한 SQL Server 2008 Transact-SQL 문을 (Transact-SQL 중인 SQL Server의 기본 스크립트 언어를) 설정 쪽으로 대상으로 거의 있을 수 있지만 몇 가지 Windows PowerShell cmdlet이 포함되어 있습니다.
그러나 없습니다 있습니다 중지하려면 이유가 없습니다. 사용 가능한 에서 cmdlet의 집합을 사용하여 Active Directory 관리할 수도 있습니다. www.quest.com/powershell ; cmdlet IIS (인터넷 정보 서비스) 7.0용 개발의 아래에 있으며 VMWare, IBM WebSphere MQ 및 비 Microsoft 제품에 대한 경우에도 cmdlet. 또한 기존 명령줄 도구를 사용하여 IIS, DNS, DHCP, Windows 방화벽 및 같은 Windows 구성 요소를 관리할 수 있습니다.

일부 최종 생각
완료된 스크립트 및 모든 해당 하위 함수를 최소한, 제공 스크립트를 만드는 유용한 시작 위치가 될 찾을 수 있기를. 의해 방법을 결론, 필자는 할 몇 가지 댓글 전체에서 변경한 적이 결정을 일부를 제공합니다.
필자는 hashtables 모를 사전에 모든 속성을 수 어떤 속성 집합을 통해 열거할 다소 쉽게 방법을 제공하기 때문에 사용자 지정 개체가 아니라 사용자 정보를 hashtables 사용할 선택했습니다. 즉, hashtables 더 스크립트를 실행할 때마다 동일한 특성을 사용할 없습니다 있습니다 때 및 자세한 특성을 추가할 합니까 필자가 아는 경우에 사용할 비트 쉽습니다.
Cacls.exe를 사용하여 있으므로, 필자는 이 연재 기사의 파트 3 설명된 대로 바로 셸 프로그램의 보다 쉽게 폴더 사용 권한을 수정할 선택했습니다. *-ACL cmdlet. 또한 Cacls.exe 사용할 알림 보여 주는 한 가지 방법은 셸 변수를 사용하여 외부 명령줄 도구를 매개 변수화할 수 있습니다.
필자는 Quest 프로그램의 Active Directory cmdlet 대신 사용하도록 ADSI cmdlet을 어떤 I 느낌을 Windows PowerShell 디렉터리를 조작하는 데 더 네이티브 접근 방식을 제공하는 때문에 선택했습니다. ADSI 취약 작업할 수 있으며 이 예제를 사용할 수 있었습니다 명령 중심 스타일 위에 이상의 프로시저 프로그래밍 스타일을 사용하도록 합니다.
스크립트에 대한 같은 결정을 선택할 수 있는지 여부를 I 활용하시기 수 살펴보겠습니다 이러한 기술과 다른 방법을 일부 관리 자동화 과제를 해결하는 데 유용합니다. 필자는 또한 초대할 제안 및 향상된 알림 함께 공유할 수 있습니다. ConcentratedTech.com, 내 웹 사이트에서 전자 메일을 보내주지 시작 관리자라면 있는 연락처 페이지를 찾은. 있으며 주십시오 수 TechNet Magazine 나중에 10월호에서 주석을 공유할 수 있습니까 알림 합니다.

Don Jones 창립자이자 concentrated 기술 여기서 Windows PowerShell, SQL Server App-V 매주에 대한 작업 블로그 및 기타 항목을. 문의 사항이 있으면 그의 웹 사이트를 통해 문의하십시오.

Page view tracker