Удалить компьютер из ad powershell
Before a user can log into a computer and access network and domain-based resources, that computer must be a member of the Active Directory environment. In this guide, you’ll find out how to automate daily tasks related to computer accounts, such how to easily create, rename and remove accounts.
In all, you’ll learn how to use PowerShell to perform the following computer account management tasks:
- Join a Computer to a Domain
- Join Multiple Computers to a Domain
- Create Computer Accounts from a CSV File
- Delete Computer Accounts Using a List
- Remove Stale Computer Accounts in Active Directory with PowerShell
- Rename a Computer and Join It to a Domain
- Disable Computer Accounts using a List
PowerShell ISE is the best tool for working with PowerShell scripts. Start the PowerShell ISE tool with administrator privileges by pressing “Windows+R” and entering “runas /profile /user:Administrator PowerShell_ISE” in the Run window. (Alternatively, you can right-click on the PowerShell ISE icon and choose the “Run as administrator” option.) Type in the administrator’s password when prompted.
Before you can work with AD and its objects, you need to import the Active Directory module for Windows PowerShell. In Microsoft Windows Server 2008 R2, you need to enable this module by running the following command:
In Microsoft Windows Server 2012 and later, this module is enabled by default.
Join a Computer to a Domain
The most common task is joining a computer to a domain controller. To join a PC to an Active Directory domain, run the following PowerShell script locally:
The computer will restart and then join the domain; it will be added to the default container.
To join a computer to a DC remotely, you need to enhance this script this way:
The $pc variable and –LocalCredential parameter are used to authenticate the computer to the domain. Note that in order to use this method, you must disable the firewall on the local computer.
Join Multiple Computers to a Domain
You can add more than one computer to the domain by either specifying them in the command line as a comma-delimited list or importing their names from a text file.
Here’s how to specify the computers in a comma-delimited list:
And here’s how to use a text file with the list of computers that should be joined:
Remove a Computer from a Domain with PowerShell
To remove a computer from a domain remotely, use the Remove-Computer cmdlet. Here, we’re removing a computer from a domain, so no local credentials are needed and we can skip the ?LocalCredential parameter:
To remove multiple computers using a list in a TXT file, use the script above for joining computers to a DC, replacing the Add-Computer cmdlet with Remove-Computer. Note that you will still need domain admin credentials to complete this unjoin operation.
Create a Computer Object in AD
To create a computer object, use the New-ADComputer cmdlet. For example, execute the following cmdlet parameters to create a computer object with “WKS932” as its name and the default LDAP path value:
Create Computer Accounts from a CSV File
If you have a list of computers that should be imported into Active Directory, save the list to a CSV file with the heading “computer” and the list of computer names in the column below it. Run the following PowerShell script on your domain controller to add computers from the CSV file, making sure you have the “Path” and “File” variables set correctly:
Delete a Computer from AD
To delete a computer account from AD, use the Remove-ADObject cmdlet. The -Identity parameter specifies which Active Directory computer to remove. You can specify a computer by its distinguished name, GUID, security identifier (SID) or Security Accounts Manager (SAM) account name.
You will be prompted to confirm the deletion.
Delete Computer Accounts Using a List
If you have a text file with a list of old computers, you can streamline the task of removing them using PowerShell. The following script will read the computer names from a TXT file and delete the corresponding accounts via a chain of commands, or pipeline:
Remove Stale Computer Accounts from Active Directory with PowerShell
Stale accounts in Active Directory can be compromised, leading to security incidents, so it is critical to keep an eye on them. This PowerShell script will query Active Directory and return all computers that have not been logged in to for the past 30 days; you can easily change this default value in the script. It also will remove those accounts to keep your AD clean.
There is one computer, FS1, that has been not been logged on to for more than 30 days. The system will prompt for confirmation before deleting it from the domain:
If you want to disable, rather than delete, the inactive computer accounts, replace the Remove-ADComputer cmdlet with Set-ADComputer and -Enabled $false parameter and value.
Rename a Computer
To change a computer name, use the Rename-Computer cmdlet. Note that the computer must be online and connected to Active Directory.
If you want to run this script locally, it will look like this:
Rename a Computer and Join It to a Domain
You can improve the renaming script by joining the computer to the domain and putting it into the specified OU simultaneously. The script should be run on the target machine, not on the domain controller.
The script will prompt for the credentials of an account that has permissions to join computers to the domain, and then the computer will be renamed, restarted and joined to the domain.
Disable an AD Computer Account
Use the Disable-ADAccount cmdlet to disable Active Directory user, computer and service accounts. If you specify a computer account name, remember to append a dollar sign ($) at the end of the name; otherwise, you’ll get an error after script execution.
Disable Computer Accounts using a List
You can also disable computer accounts in bulk using a list in a text file:
Reset an AD Computer Account
Like a user account, a computer account interacts with Active Directory using a password. But for computer accounts, a password change is initiated every 30 days by default and the password is exempted from the domain’s password policy. Password changes are driven by the client (computer), not AD.
Computer credentials usually unknown to the user because they are randomly set by the computer. But you can set your own password; here is a PowerShell script for doing so:
Conclusion
Now you have learned how to manage Active Directory computer accounts with PowerShell. You can enhance all these scripts on your own to make them fit to your purposes.
Remember that it’s critical to closely track all changes to computer accounts, so you can quickly spot any unwanted modifications and respond appropriately.
Jeff is a former Director of Global Solutions Engineering at Netwrix. He is a long-time Netwrix blogger, speaker, and presenter. In the Netwrix blog, Jeff shares lifehacks, tips and tricks that can dramatically improve your system administration experience.
The Remove-ADObject cmdlet removes an Active Directory object. You can use this cmdlet to remove any type of Active Directory object.
The Identity parameter specifies the Active Directory object to remove. You can identify an object by its distinguished name (DN) or GUID. You can also set the Identity parameter to an Active Directory object variable, such as $, or pass an object through the pipeline to the Identity parameter. For example, you can use the Get-ADObject cmdlet to retrieve an object and then pass the object through the pipeline to the Remove-ADObject cmdlet.
If the object you specify to remove has child objects, you must specify the Recursive parameter.
For AD LDS environments, the Partition parameter must be specified except when: - Using a DN to identify objects: the partition will be auto-generated from the DN.
- Running cmdlets from an Active Directory provider drive: the current path will be used to set the partition.
- A default naming context or partition is specified.
To specify a default naming context for an AD LDS environment, set the msDS-defaultNamingContext property of the Active Directory directory service agent (DSA) object (nTDSDSA) for the AD LDS instance.
Examples
-------------------------- EXAMPLE 1 --------------------------
Remove the object identified by the DistinguishedName 'CN=AmyAl-LPTOP,CN=Computers,DC=FABRIKAM,DC=COM'.
-------------------------- EXAMPLE 2 --------------------------
Deletes the container with DistinguishedName 'OU=Finance,OU=UserAccounts,DC=FABRIKAM,DC=COM' including the child objects. Note: All the children of the container including the ones which are protected from accidental deletion are also deleted.
-------------------------- EXAMPLE 3 --------------------------
Removes the object with objectGUID '65511e76-ea80-45e1-bc93-08a78d8c4853' without giving the confirmation prompt.
-------------------------- EXAMPLE 4 --------------------------
removes the object with DistinguishedName 'CN=InternalApps,DC=AppNC' from an LDS instance.
-------------------------- EXAMPLE 5 --------------------------
Recycles all the objects in the recycle bin which used to be in the container 'OU=Accounting,DC=Fabrikam,DC=com'.
Parameters
Specifies the authentication method to use. Possible values for this parameter include:
The default authentication method is Negotiate.
A Secure Sockets Layer (SSL) connection is required for the Basic authentication method.
The following example shows how to set this parameter to Basic.
Type: ADAuthType Accepted values: Negotiate, Basic Position: Named Default value: Microsoft.ActiveDirectory.Management.AuthType.Negotiate Accept pipeline input: False Accept wildcard characters: False Prompts you for confirmation before running the cmdlet.
Type: SwitchParameter Aliases: cf Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False Specifies the user account credentials to use to perform this task. The default credentials are the credentials of the currently logged on user unless the cmdlet is run from an Active Directory PowerShell provider drive. If the cmdlet is run from such a provider drive, the account associated with the drive is the default.
To specify this parameter, you can type a user name, such as "User1" or "Domain01\User01" or you can specify a PSCredential object. If you specify a user name for this parameter, the cmdlet prompts for a password.
You can also create a PSCredential object by using a script or by using the Get-Credential cmdlet. You can then set the Credential parameter to the PSCredential object The following example shows how to create credentials.
$AdminCredentials = Get-Credential "Domain01\User01"
The following shows how to set the Credential parameter to these credentials.
If the acting credentials do not have directory-level permission to perform the task, Active Directory PowerShell returns a terminating error.
Type: PSCredential Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False Specifies an Active Directory object by providing one of the following property values. The identifier in parentheses is the LDAP display name for the attribute.
The cmdlet searches the default naming context or partition to find the object. If two or more objects are found, the cmdlet returns a non-terminating error.
This parameter can also get this object through the pipeline or you can set this parameter to an object instance.
Derived types, such as the following are also accepted:
This example shows how to set this parameter to an ADObject object instance named "ADObjectInstance".
Type: ADObject Position: 0 Default value: None Accept pipeline input: True Accept wildcard characters: False Specifies to retrieve deleted objects and the deactivated forward and backward links. When this parameter is specified, the cmdlet uses the following LDAP controls:
Show Deleted Objects (1.2.840.113556.1.4.417)
Show Deactivated Links (1.2.840.113556.1.4.2065)
Note: If this parameter is not specified, the cmdlet will not return or operate on deleted objects.
Type: SwitchParameter Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False Specifies the distinguished name of an Active Directory partition. The distinguished name must be one of the naming contexts on the current directory server. The cmdlet searches this partition to find the object defined by the Identity parameter.
The following two examples show how to specify a value for this parameter.
In many cases, a default value will be used for the Partition parameter if no value is specified. The rules for determining the default value are given below. Note that rules listed first are evaluated first and once a default value can be determined, no further rules will be evaluated.
In AD DS environments, a default value for Partition will be set in the following cases: - If the Identity parameter is set to a distinguished name, the default value of Partition is automatically generated from this distinguished name.
- If running cmdlets from an Active Directory provider drive, the default value of Partition is automatically generated from the current path in the drive.
- If none of the previous cases apply, the default value of Partition will be set to the default partition or naming context of the target domain.
In AD LDS environments, a default value for Partition will be set in the following cases:
- If the Identity parameter is set to a distinguished name, the default value of Partition is automatically generated from this distinguished name.
- If running cmdlets from an Active Directory provider drive, the default value of Partition is automatically generated from the current path in the drive.
- If the target AD LDS instance has a default naming context, the default value of Partition will be set to the default naming context. To specify a default naming context for an AD LDS environment, set the msDS-defaultNamingContext property of the Active Directory directory service agent (DSA) object (nTDSDSA) for the AD LDS instance.
- If none of the previous cases apply, the Partition parameter will not take any default value.
Specifies that the cmdlet should remove the object and any children it contains.
The following example shows how to specify this parameter.
Note: Specifying this parameter it will remove all child objects even if there are objects marked with ProtectedFromAccidentalDeletion.
Type: SwitchParameter Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False Specifies the Active Directory Domain Services instance to connect to, by providing one of the following values for a corresponding domain name or directory server. The service may be any of the following: Active Directory Lightweight Domain Services, Active Directory Domain Services or Active Directory Snapshot instance.
Domain name values:
Fully qualified domain name
Directory server values:
Fully qualified directory server name
Fully qualified directory server name and port
The default value for the Server parameter is determined by one of the following methods in the order that they are listed:
-By using Server value from objects passed through the pipeline.
-By using the server information associated with the Active Directory PowerShell provider drive, when running under that drive.
-By using the domain of the computer running Powershell.
The following example shows how to specify a full qualified domain name as the parameter value.
Type: String Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter Aliases: wi Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False Inputs
None or Microsoft.ActiveDirectory.Management.ADObject
An Active Directory object is received by the Identity parameter. Derived types, such as the following are also accepted:
Outputs
None
Notes
This cmdlet does not work with an Active Directory Snapshot.
This cmdlet does not work with a read-only domain controller.
This cmdlet does not work when connected to a Global Catalog port.
By default, this cmdlet has the -Confirm parameter set, which prompts you to confirm before a removal of the specified object type can occur. To bypass prompting for confirmation before removal, you can specify -Confirm:$false when using this cmdlet.
The Remove-ADComputer cmdlet removes an Active Directory computer.
The Identity parameter specifies the Active Directory computer to remove. You can identify a computer by its distinguished name, GUID, security identifier (SID), or Security Accounts Manager (SAM) account name. You can also set the Identity parameter to a computer object variable, such as $ , or you can pass a computer object through the pipeline to the Identity parameter. For example, you can use the Get-ADComputer cmdlet to retrieve a computer object and then pass the object through the pipeline to the Remove-ADComputer cmdlet.
Examples
Example 1: Remove a specified computer from Active Directory
This command removes a specified computer from Active Directory.
Example 2: Remove all computers from a specified location using a filter
This command removes all computers in the location specified by using the Filter parameter.
Example 3: Remove all computers from a specified location using a filter
This command removes all computers from the location specified by using the Filter parameter. The command does not prompt you for confirmation.
Example 4: Remove a computer and all leaf objects that are located under a specified directory
This command removes a computer and all leaf objects that are located underneath it in the directory. Note that only a few computer objects create child objects, such as servers running the Clustering service. This example can be useful for removing those objects and any child objects owned by and associated with them.
Parameters
The default authentication method is Negotiate.
A Secure Sockets Layer (SSL) connection is required for the Basic authentication method.
Type: ADAuthType Accepted values: Negotiate, Basic Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False Prompts you for confirmation before running the cmdlet.
Type: SwitchParameter Aliases: cf Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False Specifies the user account credentials to use to perform this task. The default credentials are the credentials of the currently logged on user unless the cmdlet is run from an Active Directory module for Windows PowerShell provider drive. If the cmdlet is run from such a provider drive, the account associated with the drive is the default.
To specify this parameter, you can type a user name, such as User1 or Domain01\User01 or you can specify a PSCredential object. If you specify a user name for this parameter, the cmdlet prompts for a password.
You can also create a PSCredential object by using a script or by using the Get-Credential cmdlet. You can then set the Credential parameter to the PSCredential object.
If the acting credentials do not have directory-level permission to perform the task, Active Directory module for Windows PowerShell returns a terminating error.
Type: PSCredential Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False - A distinguished name
- A GUID (objectGUID)
- A security identifier (objectSid)
- A Security Accounts Manager account name (sAMAccountName)
The cmdlet searches the default naming context or partition to find the object. If the identifier given is a distinguished name, the partition to search is computed from that distinguished name. If two or more objects are found, the cmdlet returns a non-terminating error.
This parameter can also get this object through the pipeline or you can set this parameter to a computer object instance.
Type: ADComputer Position: 0 Default value: None Accept pipeline input: True Accept wildcard characters: False Specifies the distinguished name of an Active Directory partition. The distinguished name must be one of the naming contexts on the current directory server. The cmdlet searches this partition to find the object defined by the Identity parameter.
In many cases, a default value is used for the Partition parameter if no value is specified. The rules for determining the default value are given below. Note that rules listed first are evaluated first and once a default value can be determined, no further rules are evaluated.
In Active Directory Domain Services environments, a default value for Partition is set in the following cases:
- If the Identity parameter is set to a distinguished name, the default value of Partition is automatically generated from this distinguished name.
- If running cmdlets from an Active Directory provider drive, the default value of Partition is automatically generated from the current path in the drive.
- If none of the previous cases apply, the default value of Partition is set to the default partition or naming context of the target domain.
In Active Directory Lightweight Directory Services (AD LDS) environments, a default value for Partition is set in the following cases:
- If the Identity parameter is set to a distinguished name, the default value of Partition is automatically generated from this distinguished name.
- If running cmdlets from an Active Directory provider drive, the default value of Partition is automatically generated from the current path in the drive.
- If the target AD LDS instance has a default naming context, the default value of Partition is set to the default naming context. To specify a default naming context for an AD LDS environment, set the msDS-defaultNamingContext property of the Active Directory directory service agent (DSA) object (nTDSDSA) for the AD LDS instance.
- If none of the previous cases apply, the Partition parameter will not take any default value.
Specifies the Active Directory Domain Services instance to connect to, by providing one of the following values for a corresponding domain name or directory server. The service may be any of the following: Active Directory Lightweight Domain Services, Active Directory Domain Services or Active Directory snapshot instance.
Specify the Active Directory Domain Services instance in one of the following ways:
Domain name values:
- Fully qualified domain name
- NetBIOS name
Directory server values:
- Fully qualified directory server name
- NetBIOS name
- Fully qualified directory server name and port
The default value for this parameter is determined by one of the following methods in the order that they are listed:
- By using the Server value from objects passed through the pipeline
- By using the server information associated with the Active Directory Domain Services Windows PowerShell provider drive, when the cmdlet runs in that drive
- By using the domain of the computer running Windows PowerShell
Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter Aliases: wi Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False Inputs
None or Microsoft.ActiveDirectory.Management.ADComputer
The Remove-Computer cmdlet removes the local computer and remote computers from their current domains.
When you remove a computer from a domain, Remove-Computer also disables the domain account of the computer. You must provide explicit credentials to unjoin the computer from its domain, even when they are the credentials of the current user. You must restart the computer to make the change effective. Also, when you remove a computer from a domain, you must move it to a workgroup. Use the WorkgroupName parameter to specify the workgroup.
To move a computer from a workgroup to a domain, from one workgroup to another, or from one domain to another, use the Add-Computer cmdlet.
To get the results of the command, use the Verbose and PassThru parameters. To suppress the user prompt, use the Force parameter.
Remove-Computer removes the local computer and remote computers from domains. It includes credential parameters that specify alternate credentials for connecting to remote computers, and unjoining from a domain, a Restart parameter for restarting the affected computers, and a WorkgroupName parameter for specifying the name of the workgroup to which computers are added.
Examples
Example 1: Remove the local computer from its domain
This example removes the local computer from the domain to which it is joined.
The UnjoinDomainCredential parameter provides the credentials of a domain administrator. The PassThru and the Verbose common parameters display information about the success or failure of the command. The Restart parameter restarts the computer to complete the remove operation.
When no workgroup name is specified, the computer is moved to the workgroup named after it is removed from its domain.
Example 2: Move several computers to a legacy workgroup
This example removes all the computers listed in the OldServers.txt file from their domains and moves them into the Legacy workgroup.
The LocalCredential parameter provides the credentials of a user who has permission to connect to remote computers. The UnjoinDomainCredential parameter provides the credentials of a user who has permission to remove the computers from their domains. The Force parameter suppresses the confirmation prompts for each computer. The Restart parameter restarts each of the computers after it is removed from its domain.
Example 3: Remove computers from a workgroup without confirmation
This example removes the remote computer, Server01, and the local computer from their domains and adds them to the Local workgroup.
The Force parameter suppresses the confirmation prompt for each computer. The Restart parameter restarts the computers to make the change effective.
Parameters
Specifies the computers to be removed from their domains. The default is the local computer.
Type the NetBIOS name, an IP address, or a fully qualified domain name (FQDN) of the remote computers. To specify the local computer, type the computer name, a dot (.), or localhost.
This parameter does not rely on PowerShell remoting. You can use the ComputerName parameter of Remove-Computer even if your computer is not configured to run remote commands.
This parameter was introduced in PowerShell 3.0.
Type: String [ ] Position: Named Default value: None Accept pipeline input: True Accept wildcard characters: False Prompts you for confirmation before running the cmdlet.
Type: SwitchParameter Aliases: cf Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False Suppresses the user prompt. By default, Remove-Computer prompts you for confirmation before removing each computer.
Type: SwitchParameter Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False Specifies a user account that has permission to connect to the computers that the ComputerName parameter specifies. The default is the current user.
Type a user name, such as User01 or Domain01\User01 , or enter a PSCredential object, such as one generated by the Get-Credential cmdlet. If you type a user name, the cmdlet prompts you for a password. To specify a user account that has permission to remove the computer from its current domain, use the UnjoinDomainCredential parameter.
This parameter was introduced in PowerShell 3.0.
Type: PSCredential Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False Returns the results of the command. Otherwise, this cmdlet does not generate any output.
Type: SwitchParameter Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False Indicates that this cmdlet restarts the computers that are being removed. A restart is often required to make the change effective.
This parameter was introduced in PowerShell 3.0.
Type: SwitchParameter Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False Specifies a user account that has permission to remove the computers from their current domains. Explicit credentials, as provided by this parameter, are required to remove remote computers from a domain, even when the value is the credentials of the current user.
Type a user name, such as User01 or Domain01\User01, or enter a PSCredential object, such as one generated by Get-Credential . If you type a user name, this cmdlet prompts you for a password.
To specify a user account that has permission to connect to the remote computers, use the LocalCredential parameter.
This parameter was introduced in PowerShell 3.0.
Type: PSCredential Aliases: Credential Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False Shows what would happen if the cmdlet runs. The cmdlet is not run.
Type: SwitchParameter Aliases: wi Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False Specifies the name of a workgroup to which the computers are added when they are removed from their domains. The default value is WORKGROUP. When you remove a computer from a domain, you must add it to a workgroup.
This parameter was introduced in PowerShell 3.0.
Type: String Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False Inputs
You can pipe computer names to thiscmdlet.
Outputs
When you use the PassThru parameter, Remove-Computer returns a ComputerChangeInfo object. Otherwise, this cmdlet does not generate any output.
Командлет Remove-Computer удаляет локальный компьютер и удаленные компьютеры из текущих доменов.
При удалении компьютера из домена Remove-Computer также отключает учетную запись домена компьютера. Необходимо предоставить явные учетные данные, чтобы отменить присоединение компьютера из своего домена, даже если они являются учетными данными текущего пользователя. Чтобы внести изменения в силу, необходимо перезагрузить компьютер. При удалении компьютера из домена необходимо переместить его в рабочую группу. Используйте параметр WorkgroupName для указания рабочей группы.
Чтобы переместить компьютер из рабочей группы в домен, из одной рабочей группы в другую или из одного домена в другой, используйте Add-Computer командлет.
Чтобы получить результаты выполнения команды, используйте параметры Verbose и PassThru. Чтобы скрыть запрос к пользователю, используйте параметр Force.
Remove-Computer удаляет локальный компьютер и удаленные компьютеры из доменов. Это включает в себя параметры учетных данных, в которых указаны альтернативные учетные данные для подключения к удаленным компьютерам и отсоединения от домена, параметр Restart для перезагрузки затронутых компьютеров, параметр WorkgroupName для указания имени рабочей группы, в которую добавляются компьютеры.
Примеры
Пример 1. Удаление локального компьютера из своего домена
В этом примере удаляется локальный компьютер из домена, к которому он присоединен.
Параметр UnjoinDomainCredential предоставляет учетные данные администратора домена. PassThru и подробные общие параметры отображают сведения об успешном выполнении или сбое команды. Параметр перезапуска перезагрузит компьютер, чтобы завершить операцию удаления.
Если имя рабочей группы не указано, компьютер перемещается в рабочую группу, именуемую после удаления из домена.
Пример 2. Перемещение нескольких компьютеров в устаревшую рабочую группу
В этом примере все компьютеры, перечисленные в OldServers.txt файле, удаляются из своих доменов и перемещаются в рабочую группу прежних версий .
Параметр LocalCredential предоставляет учетные данные пользователя, имеющего разрешение на подключение к удаленным компьютерам. Параметр UnjoinDomainCredential предоставляет учетные данные пользователя, имеющего разрешение на удаление компьютеров из своих доменов. Параметр Force подавляет запросы подтверждения для каждого компьютера. Параметр перезапуска перезапускает каждый компьютер после удаления из своего домена.
Пример 3. Удаление компьютеров из рабочей группы без подтверждения
В этом примере удаленный компьютер, Server01 и локальный компьютер удаляются из доменов и добавляются в локальную рабочую группу.
Параметр Force подавляет запрос подтверждения для каждого компьютера. Параметр перезапуска перезагрузит компьютеры, чтобы внести изменения в силу.
Параметры
Указывает компьютеры, удаляемые из своих доменов. По умолчанию это локальный компьютер.
Введите имя NetBIOS, IP-адрес или полное доменное имя (FQDN) удаленных компьютеров. Чтобы указать локальный компьютер, введите имя компьютера, localhost или точку (.).
Этот параметр не зависит от удаленного взаимодействия PowerShell. Параметр ComputerName Remove-Computer можно использовать, даже если компьютер не настроен для выполнения удаленных команд.
Этот параметр появился в PowerShell 3.0.
Type: String [ ] Position: Named Default value: None Accept pipeline input: True Accept wildcard characters: False Запрос подтверждения перед выполнением командлета.
Type: SwitchParameter Aliases: cf Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False Скрывает запрос к пользователю. По умолчанию Remove-Computer запрашивается подтверждение перед удалением каждого компьютера.
Type: SwitchParameter Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False Указывает учетную запись пользователя, которая имеет разрешение на подключение к компьютерам, которые указывает параметр ComputerName . По умолчанию используется текущий пользователь.
Введите имя пользователя, например User01 или Domain01\User01 введите объект PSCredential , например, созданный командлетом Get-Credential . При вводе имени пользователя командлет запрашивает пароль. Чтобы указать учетную запись пользователя, имеющую разрешение на удаление компьютера из текущего домена, используйте параметр UnjoinDomainCredential.
Этот параметр появился в PowerShell 3.0.
Type: PSCredential Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False Возвращает результаты выполнения команды. В противном случае командлет не формирует никаких выходных данных.
Type: SwitchParameter Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False Указывает, что этот командлет перезапускает удаленные компьютеры. Чтобы изменения вступили в силу, часто требуется перезагрузка.
Этот параметр появился в PowerShell 3.0.
Type: SwitchParameter Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False Указывает учетную запись пользователя, имеющую разрешение на удаление компьютеров из текущих доменов. Требуются явные учетные данные, как указано в этом параметре, для удаления удаленных компьютеров из домена, даже если это учетные данные текущего пользователя.
Введите имя пользователя, например User01 или Domain01\User01, или введите объект PSCredential , например, созданный пользователем Get-Credential . При вводе имени пользователя этот командлет запрашивает пароль.
Чтобы указать учетную запись пользователя, имеющую разрешение на подключение к удаленным компьютерам, используйте параметр LocalCredential.
Этот параметр появился в PowerShell 3.0.
Type: PSCredential Aliases: Credential Position: 0 Default value: None Accept pipeline input: False Accept wildcard characters: False Показывает, что произойдет при запуске командлета. Командлет не выполняется.
Type: SwitchParameter Aliases: wi Position: Named Default value: False Accept pipeline input: False Accept wildcard characters: False Указывает имя рабочей группы, в которую добавляются компьютеры после удаления из их доменов. Значение по умолчанию — WORKGROUP. При удалении компьютера из домена необходимо добавить его в рабочую группу.
Этот параметр появился в PowerShell 3.0.
Type: String Position: Named Default value: None Accept pipeline input: False Accept wildcard characters: False Имена компьютеров можно передать в thiscmdlet.
Выходные данные
При использовании параметра Remove-Computer PassThru возвращает объект ComputerChangeInfo. В противном случае командлет не формирует никаких выходных данных.
Читайте также: