Managing Objects with PowerShell Scripts

This section provides an overview of how to use cmdlets to access and manage authentication and privilege elevation information stored in Active Directory using Windows PowerShell scripts. It provides a summary of the operations you can perform using cmdlets and how to establish a connection to Active Directory. For more examples of how to perform common administrative tasks using the cmdlets, see the samples included with the software.

Using cmdlets to Manage Access

The Server Suite access module for PowerShell provides cmdlets that perform operations on objects that correspond to the core elements of Server Suite data. Those core elements are:

  • Computer role definitions
  • Computers
  • Groups and group profiles
  • NIS network maps and map entries
  • Role assignments
  • UNIX and Windows rights
  • User role definitions
  • Users and user profiles
  • Zones and zone properties

In most cases, cmdlets can manipulate Server Suite information in any type of zone. However, because authorization differs greatly between hierarchical and classic zones, the cmdlets that enable you to work with rights, roles, or role assignments are only applicable in hierarchical zones. You should not use the cmdlets for rights, roles, and role assignments in classic zones. Other than this limitation, you can use the cmdlets to create, access, modify, and remove information associated with any of the core elements of Server Suite data for access control and privilege management.

Most of the cmdlets perform one of the following basic operations:

  • Add-CdmXxx cmdlets add a right to a specified role.
  • Get-CdmXxx cmdlets get the properties of a specified object.
  • New-CdmXxx cmdlets create new Server Suite objects, such as a new zone or a new role definition.
  • Remove-CdmXxx cmdlets delete a specified object or remove a right from a specified role.
  • Set-CdmXxx cmdlets set or change the properties of a specified object.

In addition to these basic operations, there are cmdlets for exporting and importing rights and roles from one zone to another and for establishing connections with Active Directory.

For descriptions of the use and parameters for each cmdlet, use the get-help command within the PowerShell console. For example, if you want to see a description and syntax summary for the New-CdmZone cmdlet, type the following command in the PowerShell console:

get-help New-CdmZone

To see detailed information about a cmdlet’s parameters and code examples, you can use the -detailed or -full option. For example, type the following command in the PowerShell console:

get-help New-CdmZone -detailed

Creating and Using a Connection

Because the Server Suite access module for PowerShell cmdlets manipulate objects in Active Directory, you must establish a connection with Active Directory before using cmdlets to perform other tasks. To do that, you must specify a target domain or domain controller and the credentials to use when connecting to that domain or domain controller.

Once the credentials are set, all subsequent calls share that information—you do not have to provide the credential or the domain controller for any subsequent calls.

The following example illustrates how to use the administrator account to connect to the finance.acme domain, then add the user joe.doe to the Engineering zone:

Copy
PS C:\> Set-CdmCredential "finance.acme" "administrator"
PS C:\> Get-CdmCredential
Target         Type   User
------         ----   ----
finance.acme   Forest administrator@finance.acme
PS C:\> $zone = Get-CdmZone -Name "Engineering"
PS C:\> New-CdmUserProfile -Zone $zone -User "joe.doe@finance.acme" -Login "jdoe"

In this example, the cmdlets that get the zone and create the user profile use the credential that is cached by the Set-CdmCredential command. The Get-CdmCredential cmdlet shows what credentials are currently cached.

Managing Connections

You can use the following cmdlets to manage connections to Active Directory by adding, modifying, or using cached credentials or specifying domain-controller-to-domain mappings:

  • Set-CdmCredential to add or modify a credential in the cache.

  • Get-CdmCredential to list the credentials currently cached.

  • Set-CdmPreferredServer to specify a domain controller to use for a domain.

  • Get-CdmPreferredServer to list all previously defined domain mappings.

Specifying Credentials

You can use the Set-CdmCredential cmdlet to specify a credential that you want to cache as a PSCredential object. Create the PSCredential object using the Get‑Credential cmdlet. The Get-Credential cmdlet prompts users to specify a username and password. You can also pass the username as a parameter to the Get-Credential cmdlet to have the cmdlet prompt the user for the password.

Organizing cmdlet Operations in a Sequence

There is no fixed sequence for calling cmdlets. There is, however, a logical sequence to follow to pass data from one cmdlet to another. For example, to get all of the user UNIX profiles in a zone, you must first identify the zone object before you call the Get-CdmUserProfile cmdlet, To accomplish this, you could organize the calls in the following sequence:

Copy
$zone = Get-CdmZone -Name "myZone"
Get-CdmUserProfile -Zone $zone

Similarly, to get all of the UNIX user profiles for a computer, you must first identify the computer object:

Copy
$computer = Get-CdmManagedComputer -Name "myComputer"
Get-CdmUserProfile -Computer $computer

In most cases, you can determine from the parameters of a cmdlet whether you need to call another cmdlet first. For example, if you want to add a right to a role, you must have created the role first so it can be specified as a parameter to the Add-CdmXxx cmdlet.

For most Set-CdmXxx or Remove-CdmXxx cmdlets, you must call the corresponding Get‑CdmXxx or Add-CdmXxx cmdlet to obtain the object first. For example, to delete role1 from zone1, you might call the cmdlets as follows:

Get-CdmRole -Zone "cn=zone1,cn=Zones,dc=acme,dc=com" -Name "role1" | Remove‑CdmRole

In this example, the Get-CdmRole cmdlet retrieves “role1” from the specified zone and passes it to the Remove-CdmRole cmdlet via a PowerShell pipe.

Confirming Licenses

All of the authentication and privilege elevation cmdlets check for a valid license before performing the requested action. The license check succeeds only if there is at least one evaluation, workstation, or server license that has not expired.

If the license check fails, the cmdlet displays an error and stops running. Otherwise, the result is cached. The next time a cmdlet tries to access the same forest, it uses the cached result rather than performing the license check again.

The cache is only effective in one PowerShell console. If another PowerShell console runs a cmdlet accessing the same forest, the cmdlet in that console must perform a separate license check.

Working with Sample Scripts

There are several sample scripts included with the software to demonstrate a few common administrative tasks. You can copy and modify these samples to use them in your environment or study them as examples for writing your own custom scripts. The sample scripts include detailed comments about the operations performed to accomplish the following tasks.

Table: Sample Scripts for Administrative Tasks

Sample Script Demonstrates
backup.ps1 How to create a backup copy of a self-contained Server Suite zone. This script creates an XML file that contains all computer, user, and group profiles, authorization information, and child zone information for a parent Server Suite zone. You cannot use this script to backup SFU zones or child zones.
CreateZoneAndDelegate.ps1 How to create a new zone and delegate all zone administrative tasks to a specific trustee.
RemoveAllOrphans.ps1 How to find and delete all user, group, and computer profiles that no longer have a corresponding Active Directory account on all managed computers in each zone.
RemoveEmptyCompRoles.ps1 How to find and remove computer roles that have no members. This script is only applicable for hierarchical zones.
RemoveEmptyZones.ps1 How to find and remove zones that have no computers, users, or authorization information. This script only removes a zone if it contains no user or group profiles, joined computers, role assignments, computer roles, or child zones. If any of these objects exist for a zone, the zone is not removed. This script is only applicable for hierarchical zones.
ResetOrphanChildZones.ps1 How to find child zones that no longer have a parent zone and reset them as independent zones.
restore.ps1 How to restore a self-contained Server Suite zone from a backup created using the backup.ps1 sample script.

Running a Sample Script

To run a sample script:

  1. Open the Server Suite access module for PowerShell.

  2. Verify you have permission to execute scripts by running Get-ExecutionPolicy. In most cases, the permission to execute scripts is restricted.

  3. If necessary, use Set‑ExecutionPolicy to allow execution. For example:

    Set-ExecutionPolicy Unrestricted

    For more about execution policies and the options available, run the get‑help command.

  4. Verify you are in the directory where the scripts are located.

  5. Execute the sample script. For example:

    .\RemoveAllOrphans

Modifying the Backup and Restore Scripts for Your Needs

If you want to use the sample backup and restore scripts to backup self-contained Server Suite zones, you must modify the content of the scripts before executing them. To run a modified sample backup script:

  1. Open the backup.ps1 file in a text editor.

  2. Modify the path to the zone you want to back up and the path to the backup file at the start of the sample script. For example:

    Copy
     $zoneDn = "CN=Headquarters,CN=Zones,OU=Acme Sales,DC=pistolas,DC=org"
     $xmlPath = "C:\Program Files\Centrify\HQ-test.xml"
  3. Modify the confirmation message at the end of the script to display the path to the backup file. For example:

    Write-Host "Backup to C:\Program Files\Centrify\HQ-test.xml is done."

  4. Save your changes with a new file name, for example, HQbackup.ps1, to keep the sample backup.ps1 script unchanged.

  5. Open the Server Suite access module for PowerShell.

Using the Default Windows PowerShell Console

Alternatively, you can use the default Windows PowerShell console. If you choose to use that console, run import-module with the path to the access module for PowerShell libraries before performing the above procedure. For example, if you installed the module in the default location, run the following command to import the Server Suite access module for PowerShell:

import-module “C:\Program Files\Centrify\PowerShell\Centrify.DirectControl.PowerShell.dll”

Creating New Zones with the Sample CreateZoneAndDelegate Script

You can use the CreateZoneAndDelegate.ps1 sample script to automate creating new zones and assigning an Active Directory user or group as the zone administrator. By default, the script delegates all administrative tasks to the user or group you specify. To use the script without modification, simply specify the Active Directory container where you want to create the zone, the zone name, and the user or group designated as the zone administrator.

To create new zone using the sample script:

  1. Open the Server Suite access module for PowerShell.

  2. Verify you are in the directory where the scripts are located.

  3. Execute the sample script with the required command line arguments. For example:

    .\CreateZoneAndDelegate -Container “cn=Zones,ou=Acme Sales,dc=pistolas,dc=org” -ZoneName seattle -trustee frank.smith@pistolas.org

  4. Open Access Manager.

  5. Right click Zones and select Open Zone to search for and select the new zone.

  6. If you want to delegate specific administrative tasks, copy the sample script and modify the Set-CdmDelegation call to specify a list of tasks. For example:

    Copy
    Set-CdmDelegation -Zone $zone -Task "AddUsers",”AddGroups” -Trustee $trustee;
    Write-Host "$trustee is delegated the rights to add users and groups.";

Generating Reports from Predefined Scripts

Most of the predefined reports in access manager report center have a corresponding PowerShell script that you can use to generate reports from the PowerShell console. For details, see Using Predefined Scripts to Generate Reports.

Writing Custom Scripts

Most cmdlets and scripts return information efficiently without any special handling or any noticeable effect on performance. If you plan to write custom scripts that may return large data sets, you should consider ways to improve performance. For example, if you are writing a script that exports a large number of zones or reports on a large number of users, you might want to use the following recommendations as guidelines:

  • When testing the performance of the script, use the standard Measure-Command cmdlet to accurately measure cmdlet and script performance.

The Measure-Command cmdlet ignores the time it takes to print all of the results returned to the PowerShell console. In many cases, the execution of a script is efficient, but rendering the results in the PowerShell console might make the cmdlet or script performance seem unacceptable.

  • Consider how you want to balance memory usage and performance when using the PowerShell pipeline if your cmdlet or script returns large data collections.

    For example, you might use foreach in a script instead of using the pipeline to improve performance. Use syntax similar to this:

    foreach ($cmd in Get-CdmUserProfile -Zone $z) { action_on_each_cmd }

    Instead of:

    Get-CdmUserProfile -Zone $z | action_on_each_cmd

    However, if you choose not to use the pipeline, all of the returned objects stay in memory and might cause an out-of-memory error. Therefore, you should try to maintain balance between the scripts memory usage and performance.

  • Cache the data, if possible, by writing the results to a file.

    For example, to add 1000 users to a zone use syntax similar to this to get a zone once:

    $zone = Get-CdmZone -Dn "cn=QA,cn=Zones,dc=ajax,dc=org"$profile1 = New-CdmUserProfile -Zone $zone -User user1@ajax.org -Uid 10001 ... $profile1000 = New-CdmUserProfile -Zone $zone -User user1000@ajax.org -Uid 11000

    Instead of using syntax like this, which gets the zone from its distinguished name (DN) for every user:

    $profile1 = New-CdmUserProfile -Zone "cn=QA,cn=Zones,dc=ajax,dc=org" ‑User user1@domain.com -Uid 10001 ... $profile1000 = New-CdmUserProfile -Zone "cn=QA,cn=Zones,dc=ajax,dc=org" ‑User user1000@domain.com -Uid 11000

  • Use Export-Csv instead of Out-File if possible. The Export-Csv cmdlet writes results to a file faster than the Out-File cmdlet.

  • If you are writing a script that generates a very large data set—for example, reporting information for a global zone—you might want to use the native .NET FileStream function. The FileStream function is the fastest way to write content to a file.

    For example, you might use a code snipper like this:

    Copy
    $fs = New-Object IO.FileStream <file>, 'Append','Write','Read'
       $fw = New-Object System.IO.StreamWriter $fs
         $zone = Get-CdmZone -Dn "cn=global,cn=Zones,dc=ajax,dc=org"
        foreach ($cz in $zone) {$fw.WriteLine("{0} {1}", $cz.Name, $cz.Type)}
      $fw.Close()
     $fs.Dispose()

Enabling Logging for cmdlets

For performance, logging for cmdlets is disabled by default. To enable logging, you must modify the registry on the computer where you are running the access module for Windows PowerShell.

To enable logging:

  1. Run regedit to open the Registry Editor

  2. Select the HKEY_CURRENT_USER > Software > Server Suite registry key.

  3. Right-click, then select New > Key and type CIMS.

  4. Select the new CIMS key, right-click, then select New > String Value with the name of LogPath.

  5. Specify the path to the log file as the value. For example, set the value to C: \Temp\Log.

  6. Select the new CIMS key, right-click, then select New > DWORD (32-bit) Value with the name of TraceLevel.

  7. Specify the level of detail to write to the log file as the value. The valid settings are:

    0 to disable logging. 1 to only log error messages. 2 to log errors and warning messages. 3 to log errors, warnings, and informational messages. 4 to log all debugging and tracing messages.

    For example, set the value to 4 to enable detailed logging of all messages.

Viewing a Summary of cmdlet Commands

You can use the get-help command with different options to get summary about the cmdlets available in the Server Suite access module for PowerShell or detailed information about the specific cmdlets you want to use. For example, you can use get-help with the ‑full command-line option to see complete reference information for a specified cmdlet or get-help -example to display only the examples for a specified cmdlet.

To see the current list of cmdlets available open the Server Suite access module for PowerShell, run the get-help cdm command. This command displays a summary of the access module for PowerShell cmdlets similar to the following table (rendered as ASCII characters):

Table: Summary of cmdlet Commands Output by the get-help cdm Command

Name Synopsis
Add-CdmApplicationRight Adds a Windows application right...
Add-CdmCommandRight Adds a UNIX command right to a s...
Add-CdmDesktopRight Adds a Windows desktop right to ...
Add-CdmNetworkAccessRight Adds a Windows network access ri...
Add-CdmPamRight Adds a PAM application access ri...
Add-CdmSshRight Adds an SSH application right to...
Export-CdmData Exports roles and rights from th...
Get-CdmApplicationRight Gets an application right from a...
Get-CdmCommandRight Gets a command right from a zone...
Get-CdmComputerRole Gets a computer role from a zone.
Get-CdmCredential Gets user credentials.
Get-CdmDesktopRight Gets a Windows desktop right fro...
Get-CdmEffectiveGroupProfile Gets effective group profiles fo...
Get-CdmEffectiveUnixRight Gets the effective UNIX rights a...
Get-CdmEffectiveUserProfile Gets effective user profiles for...
Get-CdmEffectiveWindowsRight Gets the effective Windows right...
Get-CdmGroupProfile Gets group UNIX profiles.
Get-CdmManagedComputer Gets zoned or auto-zoned managed...
Get-CdmNetworkAccessRight Gets a Windows network applicati...
Get-CdmNisMap Gets NIS maps for the specified ...
Get-CdmNisMapEntry Gets NIS map entries for the spe...
Get-CdmPamRight Gets a PAM application access ri...
Get-CdmPreferredServer Gets domain to server mapping.
Get-CdmRole Gets roles from a zone.
Get-CdmRoleAssignment Gets role assignments.
Get-CdmSshRight Gets an SSH application right fr...
Get-CdmUserProfile Gets user UNIX profiles.
Get-CdmZone Gets the zone object.
Import-CdmData Imports roles and rights into a ...
New-CdmApplicationRight Creates a new Windows applicatio...
New-CdmCommandRight Creates a new command right in a...
New-CdmComputerRole Creates a new computer role in a...
New-CdmDesktopRight Creates a new Windows desktop ri...
New-CdmGroupProfile Creates a new UNIX group profile.
New-CdmManagedComputer Pre-creates a computer or comput...
New-CdmMatchCriteria Creates a new match criteria for...
New-CdmNetworkAccessRight Creates a new Windows network ac...
New-CdmNisMap Creates a new NIS map in a speci...
New-CdmNisMapEntry Creates a new NIS map entry in a...
New-CdmPamRight Creates a new PAM application ac...
New-CdmRole Creates a new role in a zone.
New-CdmRoleAssignment Creates a new role assignment.
New-CdmUserProfile Creates a new UNIX user profile.
New-CdmZone Creates a new zone.
Remove-CdmApplicationRight Deletes a Windows application ri...
Remove-CdmCommandRight Deletes a command right or remov...
Remove-CdmComputerRole Deletes a computer role from a z...
Remove-CdmDesktopRight Deletes a Windows desktop right ...
Remove-CdmGroupProfile Deletes a UNIX group profile.
Remove-CdmManagedComputer Removes a managed computer from ...
Remove-CdmNetworkAccessRight Deletes a Windows network access...
Remove-CdmNisMap Deletes a NIS map from a zone.
Remove-CdmNisMapEntry Deletes a map entry from a NIS map.
Remove-CdmPamRight Deletes a PAM application access...
Remove-CdmRole Deletes a role.
Remove-CdmRoleAssignment Deletes a role assignment from a...
Remove-CdmSshRight Removes an SSH right from a role.
Remove-CdmUserProfile Deletes a UNIX user profile.
Remove-CdmZone Deletes an existing zone.
Set-CdmApplicationRight Updates an existing Windows appl...
Set-CdmCommandRight Updates an existing command right.
Set-CdmComputerRole Updates an existing computer role.
Set-CdmCredential Adds a user credential.
Set-CdmDelegation Updates the delegation of admini...
Set-CdmDesktopRight Updates an existing Windows desk...
Set-CdmGroupProfile Updates an existing UNIX group p...
Set-CdmNetworkAccessRight Updates an existing Windows netw...
Set-CdmNisMap Updates an existing NIS map.
Set-CdmNisMapEntry Updates an existing NIS map entry.
Set-CdmPamRight Updates an existing PAM applicat...
Set-CdmPreferredServer Specifies a preferred server.
Set-CdmRole Updates an existing role.
Set-CdmRoleAssignment Updates an existing role assignm...
Set-CdmUserProfile Updates an existing UNIX user pr...
Set-CdmZone Updates an existing zone.