Connecting to servers outside a domain using Powershell

From time to time you’ll find yourself running scripts to a server outside the domain. If you have the same credentials on that as on the domain there’s no problem. However in most cases you don’t. Normally you will have to encrypt the password as a secure string. However there are cases that such a solution costs to much time. Especially if you have multiple passwords for the same user account (eg. Administrator). So to get this done you might use a old trick to connect to the server using SMB en store the credentials session in the memory of the server running the script. I must admit that this is only if you’ll have to go quick and dirty. If’ve used it once and it may come in handy sometimes.

$Credentiallist = @()
$Credentiallist += "Password1"
$Credentiallist += "Password2"
$Credentiallist += "Password3"
$Credentiallist += "Password4"
$Errors = ".\Error.csv"
$Success = ".\Success.csv"
$net = new-object -ComObject WScript.Network
$ADComputers = Import-CSV ".\DNSNames.csv"
$Computers =@()
$ComputerSuccess =@()
$FailedComputers = @()
Foreach ($ADComputer in $AdComputers)
	{
	$ADComputer = $ADComputer.DNSHostName
	Foreach ($cred in $credentialList)
		{
		If ($ComputerSuccess -notcontains $ADComputer)
			{ 
			$net.MapNetworkDrive("u:", "\\$ADComputer\c$", $false, "localhost\Administrator", "$Cred")
			If((Test-Path "\\$ADComputer\C$\Windows" ) -eq $True)
				{
				$ComputerSuccess += $ADComputer
				#Do the code you want to run against the server
				}
			}
		}
	If ((get-psdrive -name "U" -Erroraction SilentlyContinue) -ne $null){$net.RemoveNetworkDrive("u:")}
	}