Posted On December 26, 2019

PowerShell: Obtain Computer Account Parent Container from Invoke-Command

kimconnect 0 comments
blog.KimConnect.com >> Codes >> PowerShell: Obtain Computer Account Parent Container from Invoke-Command
# ObtainComputerAccountParentContainer.ps1
# This is a demonstration of how to pass function into an invoke-command as well as credentials toward such function

$servers="SHERVER007";
$adminCredential=get-credential;

function getContainer{
param(
$domainAdminCred
)
if ((gwmi win32_computersystem).partofdomain -eq $true){
if (!(Get-Module ActiveDirectory)){
try {
$voidOutput=[void](Import-Module ServerManager -ErrorAction SilentlyContinue)
$voidOutput=[void](Add-WindowsFeature RSAT-AD-PowerShell -Confirm:$false);

######## Error ######
#Error on some systems
#Add-WindowsFeature : The target of the specified cmdlet cannot be a Windows client-based operating system.
#At line:1 char:1
#+ Add-WindowsFeature RSAT-AD-PowerShell -Confirm:$false
#+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# + CategoryInfo : DeviceError: (localhost:String) [Install-WindowsFeature], Exception
# + FullyQualifiedErrorId : WindowsClient_NotSupported,Microsoft.Windows.ServerManager.Commands.AddWindowsFeatureCommand
#
#Get-ADComputer : Unable to contact the server. This may be because this server does not exist, it is currently down,
#or it does not have the Active Directory Web Services running.
#At line:1 char:1
#+ Get-ADComputer $env:computername
#+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
# + CategoryInfo : ResourceUnavailable: (SHERVER007:ADComputer) [Get-ADComputer], ADServerDownException
# + FullyQualifiedErrorId : ActiveDirectoryServer:0,Microsoft.ActiveDirectory.Management.Commands.GetADComputer
#
#
# Resolution:
# Get-ADComputer $env:computername -Server $DomainController -Credential (get-credential)
######################

$voidOutput=[void](Import-Module ActiveDirectory -ErrorAction SilentlyContinue)
}catch{Continue;}

##### Error when executing remotely ###
#WARNING: Error initializing default drive: 'Unable to contact the server. This may be because this server does not exist,
#it is currently down, or it does not have the Active Directory Web Services running.'.

}
[string]$nearestDc=(Get-ADDomainController -Discover).HostName
$result=[string](Get-ADComputer $env:computername -Server $nearestDc -Credential $domainAdminCred).DistinguishedName -Replace "^CN=[^,]+,",''
}else{
$result="This computer is not domain joined."
}
return $result
}

function executeFunctionRemotely{
param(
$remoteComputer,
$adminCredential
)

do{
$session = New-PSSession -ComputerName $remoteComputer
write-host "Connecting to remote computer $remoteComputer..."
sleep -seconds 5
#if ($session){write-host "Connected."}
} until ($session.state -match "Opened")

invoke-command -session $session -scriptblock{
param($importedFunc,$cred)
[ScriptBlock]::Create($importedFunc).invoke($cred);
} -args ${function:getContainer},$adminCredential
Remove-PSSession -id $session.Id
}

$servers|%{
$container=executeFunctionRemotely -remoteComputer $_ -adminCredential $adminCredential;
write-host $container
}
# Expected Output
Connecting to remote computer SHERVER007...
Connected.
WARNING: Error initializing default drive: 'Unable to contact the server. This may be because this server does not exist, it is currently down, or it does not have the Active Directory Web Services running.'.
OU=CLUSTER1,OU=LAB,OU=Servers,DC=intranet,DC=kimconnect,DC=com

Leave a Reply

Your email address will not be published. Required fields are marked *

Related Post

PowerShell: Add User To Group in Active Directory

$userId='kimconnect' $groupName='Remote Desktop Users' function addUserToGroup($userId,$groupName){ $userExists=Get-ADGroupMember $groupName|?{$_.SamAccountName -eq $userId} if(!$userExists){ Add-ADGroupMember -Identity $groupName -Members…

PowerShell: Automating Dynamics CRM Migration

This is the source code that has been used to move hundreds of Dynamics CRM…

PowerShell: Set ACL

# setAcl-v0.01.ps1# # What this script does:# 1. Set permissions on a set of "destination…