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: List Biggest Files and Folders on a Volume

# listBigFilesAndFolders-v0.01.ps1 # Set variables $parentDirectory="C:\" $depth=4 $topX=10 $excludeDirectories="C:\Windows","C:\Program Files","C:\Program Files (x86)" $clusterSizeOfNetworkShare=8192 # Sanitize…

Bash: How To Join Array With Comma Delimiter

# The following function joins an array of numbers # Limitation: the delimiter is expected…

PowerShell: Set DNS Server IPs on Default Network Interface

$dns1=.{ Import-Module ActiveDirectory $fsmoRoles=Get-ADDomainController -Filter *|Select-Object Name, Domain, Forest, OperationMasterRoles|Where-Object {$_.OperationMasterRoles}|select Name,OperationMasterRoles $pdcServer=($fsmoRoles|?{'PDCEmulator' -in $_.OperationMasterRoles}).Name…
Other project: DragonCoin.com