Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- param( [Parameter(Mandatory=$true)] [String] $TargetHost ,
- [Parameter(Mandatory=$true)] [String] $TargetUserName ,
- [String] $User ,
- [String] $Password)
- # Set up a trap to properly exit on terminating exceptions
- trap [Exception] {
- write-error $("TRAPPED: " + $_)
- exit 1
- }
- function DeactivateAccount($TargetHost , $TargetUserName ,$User , $Password){
- $TargetHost = $TargetHost #Target Host on which windows account deactivation will be done.
- $TargetUserName = $TargetUserName #User Name of Target.
- $Domain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain() #Domain name of the localhost.
- $localHost = [System.Net.Dns]::GetHostName()
- $localIP = [System.Net.Dns]::GetHostAddresses("$localHost")
- #if TargetHost and LocalHost are same.
- if($localHost -like $TargetHost -OR $localIP -like $TargetHost) {
- if($Domain -eq [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()){
- $process = net user $TargetUsername /domain /active:no #Performs the operation on the domain controller in the computer's primary domain.
- } else {
- $process = net user $TargetUsername /active:no
- }
- Write-host " $TargetUsername account deactivated "
- }
- #If TargetHost is remote Host.
- else {
- $User = $User #Creds to perform admin function.
- $Password = $Password
- $SecurePassword = new-Object System.Security.SecureString #Convert password into secure string.
- $Password.ToCharArray() | % { $SecurePassword.AppendChar($_) }
- $Cred = New-Object -typename System.Management.Automation.PSCredential -argumentlist "$User",$securePassword
- $newSession = New-PSSession -ComputerName "$TargetHost" -credential $Cred #Used PSSession for persistent connection and credentials to Specify a user account that has permission to perform this action.
- $export_username = Invoke-Command -Session $newSession -ScriptBlock {$username=args[1]} # Invoke-Command command uses the Session parameter(here newSession) to run the commands in same session.
- if($Domain -eq [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()){
- $process = Invoke-Command -Session $newSession -ScriptBlock {net user $username /domain /active:no}
- } else {
- $process = Invoke-Command -Session $newSession -ScriptBlock {net user $username /active:no}
- }
- Write-host " $TargetUsername account deactivated "
- Remove-PSSession $newSession # Closes Windows PowerShell sessions.
- }
- if(-not $?) { # Returns true if last command was successful.
- Write-Error "Windows Deactivation Failed!!"
- exit 1
- }
- }
- DeactivateAccount($TargetHost , $TargetUserName ,$User , $Password)
Add Comment
Please, Sign In to add comment