Import-Module ActiveDirectory in Remote PS fails

This script I’m working on contains a piece that creates a new Pssession, then Enters it. Next step is an Import-Module to which it fails as Not Found. If I interactively run the same commands it obviously works. What am I doing wrong?

Here’s my script (it’s not finished)

(new-object Net.WebClient).DownloadString('https://raw.githubusercontent.com/FakeUserName/Powershell_functions/master/Get-PSWho.ps1') | Invoke-Expression; Get-PSWho

$newuser = read-host "Enter new username"
$adminuser = Get-pswho | Select-Object -ExpandProperty User

#Creates new remote PS Session on target
new-pssession -computername "server" -credential $adminuser | enter-pssession

Import-Module ActiveDirectory

#Queries AD for username
if (@(get-aduser -filter { SamAccountName -eq $newuser }).Count -eq 0) {
Write-Warning -Message "User $newuser does not exist."
}
#Asks user if they want to continue if the username already exists
write-host -nonewline "Continue? (Y/N) "
$response = read-host
if ( $response -ne "Y" ){exit}

Enter-PSSession cmdlet is not designed to be used in a script. You may use Invoke-Command instead or you could use
Implicit remoting.

$Session = New-PSSession -ComputerName “server” -Credential $adminuser
Import-Module ActiveDirectory -PSSession $Session

Another suggestion if I may, is using ADSI. Since it is built into PowerShell you don’t need to mess with importing additional modules. Here is a brief example.

[pre]

$user = ‘testUser’
$search = [adsisearcher]“objectcategory=user”
$search.Filter = “SamAccountName=$user”
$result = $search.FindOne().Properties
$result

[/pre]

More information about ADSI can be found here

https://devblogs.microsoft.com/scripting/use-the-powershell-adsisearcher-type-accelerator-to-search-active-directory/

Another thing to consider is the double-hop issue. If you remote into another computer then try to query AD you will run into issues unless you have taken steps to properly delegate.