Powershell SSH credentials - powershell

I have this script for automation execute command on multiple machines but appear one problem when I try to force user to enter credential:
Write-Host "Enter credentials!" -ForegroundColor Green
$user1 = Read-Host "user"
$pwd1 = Read-Host "pass" -AsSecureString
Write-Host "type command" -ForegroundColor Cyan
Write-Host "--------------" -ForegroundColor Cyan
Write-Host "example: shutdown -f -r -t 0" -ForegroundColor Cyan
$Command1 = Read-Host -Prompt "Comanda"
$Computers = Get-Content -Path C:\Users\Meo\Desktop\ipMachine.txt | Where-Object { $_ -match '\S' }
foreach($Computer in $Computers){
Write-Host $Computer
$User = "$user1"
$pwd1_text = [Runtime.InteropServices.Marshal]::PtrToStringAuto([Runtime.InteropServices.Marshal]::SecureStringToBSTR($pwd1))
$secpasswd = ConvertTo-SecureString $pwd1 -AsPlainText -Force
$Credentials = New-Object System.Management.Automation.PSCredential ($User, $secpasswd)
$Command1 = "$Command"
Write-Host $Command
Get-SSHTrustedHost | Remove-SSHTrustedHost
$SessionID = New-SSHSession -ComputerName $Computer -Credential $Credentials -AcceptKey:$true
Invoke-SSHCommand -Index $sessionid.sessionid -Command $Command
}
return ( if I put credential in script it works very well.. any ideea? thx)
New-SSHSession : Permission denied (keyboard-interactive).
At line:26 char:14
+ ... SessionID = New-SSHSession -ComputerName $Computer -Credential $Crede ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : SecurityError: (Renci.SshNet.SshClient:SshClient) [New-SSHSession], SshAuthenticationException
+ FullyQualifiedErrorId : SSH.NewSshSession
Invoke-SSHCommand : Cannot bind argument to parameter 'SessionId' because it is null.
At line:28 char:26
+ Invoke-SSHCommand -Index $sessionid.sessionid -Command $Command
+ ~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-SSHCommand], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Invoke-SSHCommand
```

Related

Powershell Script - Re-Prompt Password Screen If PW is İncorrect

I have a script that will change all local administrator passwords with the below script. Script will prompt password for each server. (all servers have different passwords)
I want to re-prompt the credential screen if user enters wrong password but I couldn't handle it.
$servers = Get-Content "C:\Users\Administrator\Desktop\Scripts\TestServers.txt"
foreach($server in $servers)
{
$pingtest = Test-Connection -ComputerName $server -Quiet -Count 1 -ErrorAction SilentlyContinue
if($pingtest)
{
Write-Host($server + " is online")
try
{
$ServerSessions = New-PSSession -ComputerName $server -Credential 'Administrator'
}catch [System.UnauthorizedAccessException]
{
Write-Host("Credential is incorrect! Try again")
$ServerSessions = New-PSSession -ComputerName $server -Credential 'Administrator'
}
Invoke-Command -Session $ServerSessions -ScriptBlock {
# Windows Server Versiyonunu check edip parolayı ona göre set etmek için
Get-ComputerInfo | select WindowsProductName, WindowsVersion, OsHardwareAbstractionLayer
$Password = Read-Host -AsSecureString
$UserAccount = Get-LocalUser -Name "Administrator"
$UserAccount | Set-LocalUser -Password $Password
}
else
{
Write-Host($server + " is offline, nothing to do")
}
}
}
I got this error when running the script:
<IP_Address> is online
New-PSSession : [<IP_Address>] Connecting to remote server <IP_Address> failed with the following error message : Access is denied. For more information, see the
about_Remote_Troubleshooting Help topic.
At line:12 char:31
+ ... rSessions = New-PSSession -ComputerName $server -Credential 'Administ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTransportException
+ FullyQualifiedErrorId : AccessDenied,PSSessionOpenFailed
Invoke-Command : Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an argument that is not null or empty, and then try the command again.
At line:22 char:37
+ Invoke-Command -Session $ServerSessions -ScriptBlock {
+ ~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
else : The term 'else' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path
is correct and try again.
At line:30 char:9
+ else
+ ~~~~
+ CategoryInfo : ObjectNotFound: (else:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Write-Host($server + " is offline, nothing to do")
If I use correct password, the script works fine.
Update
Solution
Below method works but I couldn't be able to handle catch statement with catch [System.UnauthorizedAccessException]. Instead I used catch [Exception]. It is not a good solution but it works fine for me now.
$servers = Get-Content "C:\Users\Administrator\Desktop\Scripts\TestServers.txt"
foreach($server in $servers)
{
$pingtest = Test-Connection -ComputerName $server -Quiet -Count 1 -ErrorAction SilentlyContinue
if($pingtest)
{
Write-Host($server + " is online")
$Creds = Get-Credential 'Administrator'
do{
try
{
$ServerSessions = New-PSSession -ComputerName $server -Credential $Creds -ErrorAction Stop
Write-Host ("$ServerSessions")
}catch [Exception]
{
Write-Host("Credential is incorrect! Try again")
$Creds = Get-Credential 'Administrator'
}
}while(!$ServerSessions)
Invoke-Command -Session $ServerSessions -ScriptBlock {
# Windows Server Versiyonunu check edip parolayı ona göre set etmek için
Get-ComputerInfo | select WindowsProductName, WindowsVersion, OsHardwareAbstractionLayer
$Password = Read-Host -AsSecureString
$UserAccount = Get-LocalUser -Name "Administrator"
$UserAccount | Set-LocalUser -Password $Password
}
}
else {
Write-Host($server + " is offline, nothing to do")
}
}
Try/catch doesn't work if it is not a stopping error, so add the -ErrorAction Stop parameter to your session, and then wrap that try/catch inside a Do/While loop based on if you have a session or not and get new creds in the Catch part.
$Creds = Get-Credentials 'Administrator'
Do{
try
{
$ServerSessions = New-PSSession -ComputerName $server -Credential $Creds -ErrorAction Stop
}catch [System.UnauthorizedAccessException]
{
Write-Host("Credential is incorrect! Try again")
$Creds = Get-Credentials 'Administrator'
}
}While(!$ServerSessions)
Your curly braces for the if statement were incorrect. This is why properly indenting your code is of importance.
To retry the authentication, use a while loop that will keep looping until a new session is established. For example:
$servers = Get-Content "C:\Users\Administrator\Desktop\Scripts\TestServers.txt"
foreach($server in $servers)
{
$pingtest = Test-Connection -ComputerName $server -Quiet -Count 1 -ErrorAction SilentlyContinue
if($pingtest)
{
Write-Host "$server is online"
while ($True) {
try
{
$Cred = Get-Credential -UserName 'Administrator'
$ServerSession = New-PSSession -ComputerName $server -Credential $Cred
break
}catch [System.UnauthorizedAccessException]
{
Write-Host "Credential is incorrect! Try again"
}
}
try {
Invoke-Command -Session $ServerSession -ScriptBlock {
# Windows Server Versiyonunu check edip parolayı ona göre set etmek için
Get-ComputerInfo | select WindowsProductName, WindowsVersion, OsHardwareAbstractionLayer
$Password = Read-Host -AsSecureString
$UserAccount = Get-LocalUser -Name "Administrator"
$UserAccount | Set-LocalUser -Password $Password
}
finally {
Remove-PSSession $ServerSession
}
}
else {
Write-Host "$server is offline, nothing to do"
}
}

Check/read registry key value on remote computer with local admin credential

How to check registry key value on computer which is not in domain??
I think that I must use local admin credential for this but I dont know how
I tried this:
$user = "admin"
$password = "pass" | ConvertTo-SecureString -asPlainText -Force
$computer = "computer"
$domain=$computer
$username = $domain + "\" + $user
$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $username,$password
$key = '\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters'
$valuename = 'DiskSpaceThreshold'
$wmi = Get-Wmiobject -list "StdRegProv" -namespace root\default -Computername $computer -Credential $Credential
$value = $wmi.GetStringValue($HKEY_Local_Machine,$key,$valuename).svalue
$wmi
$value
But the result:
Get-Wmiobject : Could not get objects from namespace root\default. Serwer RPC jest niedostępny. (Wyjątek od HRESULT: 0x800706BA) At line:12 char:8
+ $wmi = Get-Wmiobject -list "StdRegProv" -namespace root\default -Comp ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [Get-WmiObject], COMException
+ FullyQualifiedErrorId : INVALID_NAMESPACE_IDENTIFIER,Microsoft.PowerShell.Commands.GetWmiObjectCommand You cannot call a method on a null-valued expression. At line:13 char:1
+ $value = $wmi.GetStringValue($HKEY_Local_Machine,$key,$valuename).sva ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
__GENUS : 2
__CLASS : __PARAMETERS
__SUPERCLASS :
__DYNASTY : __PARAMETERS
__RELPATH :
__PROPERTY_COUNT : 2
__DERIVATION : {}
__SERVER :
__NAMESPACE :
__PATH : ReturnValue : 6 uValue : PSComputerName :
So I tried something else
# file with computer name
$computers = Get-Content F:\IT\!Set_NTP_Time\ReadRegistry\servers.txt | ?{$_ -notmatch "^#"};
#Registry Hives
[long]$HIVE_HKROOT = 2147483648
[long]$HIVE_HKCU = 2147483649
[long]$HIVE_HKLM = 2147483650
[long]$HIVE_HKU = 2147483651
[long]$HIVE_HKCC = 2147483653
[long]$HIVE_HKDD = 2147483654
# registry
$HKLM = 2147483650
$main = "Localmachine"
$keyPath = "System\CurrentControlSet\Services\W32Time"
$keyName = "Start"
#$computer ='.'
$reg = [WMIClass]"ROOT\DEFAULT:StdRegProv"
$Key = "W32Time"
#$Value = "HistoryBufferSize"
#$results = $reg.GetDWORDValue($HKEY_LOCAL_MACHINE, $Key, $keyName)
#"Current History Buffer Size: {0}" -f $results.uValue
<#
Param($computer)
$HKEY_Local_Machine = 2147483650
$reg = [WMIClass]"\\$computer\ROOT\DEFAULT:StdRegProv"
$Key = "SOFTWARE\Wow6432Node\Symantec\Symantec Endpoint Protection\CurrentVersion\SharedDefs"
$ValueName = "DEFWATCH_10"
$results = $reg.GetStringValue($HKEY_LOCAL_MACHINE, $Key, $ValueName)
write $results.sValue
#>
# credentials
$user = "admin"
$user1 = "admin1"
$password = "pass" | ConvertTo-SecureString -asPlainText -Force
# Start processing
foreach($computer in $computers) {
$domain=$computer
$username = $domain + "\" + $user
$username1 = $domain + "\" + $user1
$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $username,$password
$Credential1 = New-Object System.Management.Automation.PSCredential -ArgumentList $username1,$password
try {
if (($computer -eq "comp1") -or ($computer -eq "comp2") -or ($computer -eq "name_of_computer") -or ($computer -eq "other_computer")) {
#$wmi = Get-Wmiobject -list "StdRegProv" -namespace root\default -Computername $computer -Credential $Credential1
#$value = $wmi.GetStringValue($HKLM,$keyPath,$keyName).svalue
#Write-Host -ForegroundColor DarkYellow $computer $value
#$value = Invoke-Command -Scriptblock {Get-Item $HKLM,$keyPath,$keyName} -Computername $computer -Credential $Credential1
$reg = Get-WmiObject -List -Namespace root\default -ComputerName $Computer -Credential $Credential1 | Where-Object {$_.Name -eq "StdRegProv"}
#$HKLM = 2147483650
#$value = $reg.GetStringValue($HKLM,$keyPath,$keyName).sValue
$value = $reg.GetDWORDValue($HKEY_LOCAL_MACHINE, $Key, $keyName)
Write-Host -ForegroundColor DarkYellow $computer $reg $value
} else {
#$wmi = Get-Wmiobject -list "StdRegProv" -namespace root\default -Computername $computer -Credential $Credential
#$value = $wmi.GetStringValue($HKLM,$keyPath,$keyName).svalue
#Write-Host -ForegroundColor DarkYellow $computer $value
#$value = Invoke-Command -Scriptblock {Get-Item $HKLM,$keyPath,$keyName} -Computername $computer -Credential $Credential
$reg = Get-WmiObject -List -Namespace root\default -ComputerName $Computer -Credential $Credential | Where-Object {$_.Name -eq "StdRegProv"}
#$HKLM = 2147483650
#$value = $reg.GetStringValue($HKLM,$keyPath,$keyName).sValue
$value = $reg.GetDWORDValue($HKEY_LOCAL_MACHINE, $Key, $keyName)
Write-Host -ForegroundColor DarkYellow $computer $reg $value
}
<#
if($value -eq 2)
{
Write-Host -ForegroundColor DarkYellow $computer "YES"
} else {
Write-Host -ForegroundColor Red $computer "NO"
}
#>
} catch {
Write-Host -ForegroundColor Red "$computer access denied.$_";
}
}
Result for this script
comp1 \COMP1\ROOT\default:StdRegProv System.Management.ManagementBaseObject
comp2 \COMP2\ROOT\default:StdRegProv System.Management.ManagementBaseObject
comp3 \COMP3\ROOT\default:StdRegProv System.Management.ManagementBaseObject
Personally, as I am used to use powershell remoting to gather information from remote machines, I would proceed like this:
Establish remote PS session
Run script on remote machine
Profit
So in your case, something like (If you are retrieving a value named DiskSpaceThreshold inside of HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters)
$user = "admin"
$password = "pass" | ConvertTo-SecureString -asPlainText -Force
$computer = "computer"
$domain=$computer
$username = $domain + "\" + $user
$Credential = New-Object System.Management.Automation.PSCredential -ArgumentList $username,$password
$session = New-PSSession $computer -Credential $Credential
$r = Invoke-Command -Session $session -ScriptBlock { Get-ItemProperty -Path HKLM:\SYSTEM\CurrentControlSet\Services\LanmanServer\Parameters -Name "DiskSpaceThreshold" }
Remove-PSSession $session
Write-Host $r.DiskSpaceThreshold
The effect of trying to run the script from P-L user post
New-PSSession : [computer] Connecting to remote server computer failed with the following error message : WinRM cannot process the
request. The following error with errorcode 0x80090311 occurred while using Kerberos authentication: There are currently no
logon servers available to service the logon request.
Possible causes are:
-The user name or password specified are invalid.
-Kerberos is used when no authentication method and no user name are specified.
-Kerberos accepts domain user names, but not local user names.
-The Service Principal Name (SPN) for the remote computer name and port does not exist.
-The client and remote computers are in different domains and there is no trust between the two domains.
After checking for the above issues, try the following:
-Check the Event Viewer for events related to authentication.
-Change the authentication method; add the destination computer to the WinRM TrustedHosts configuration setting or use HTT
PS transport.
Note that computers in the TrustedHosts list might not be authenticated.
-For more information about WinRM configuration, run the following command: winrm help config. For more information, see
the about_Remote_Troubleshooting Help topic.
At line:9 char:12
+ $session = New-PSSession $computer -Credential $Credential
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OpenError: (System.Manageme....RemoteRunspace:RemoteRunspace) [New-PSSession], PSRemotingTran
sportException
+ FullyQualifiedErrorId : AuthenticationFailed,PSSessionOpenFailed
Invoke-Command : Cannot validate argument on parameter 'Session'. The argument is null or empty. Provide an argument that is
not null or empty, and then try the command again.
At line:10 char:30
+ $r = Invoke-Command -Session $session -ScriptBlock { Get-ItemProperty -Path HKLM ...
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Invoke-Command], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.InvokeCommandCommand
Remove-PSSession : Cannot validate argument on parameter 'Id'. The argument is null. Provide a valid value for the argument,
and then try running the command again.
At line:11 char:18
+ Remove-PSSession $session
+ ~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Remove-PSSession], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.RemovePSSessionCommand
The username and password are good.

Setting Windows local admin password remotely using PowerShell & [ADSI]

So close but so far...
I am trying to change a local administrator password on a Windows server using [ADSI] & PowerShell but I cannot find a way to pass a string variable when invoking and get the following error:
Exception calling "Invoke" with "2" argument(s): "Number of parameters specified does not match the expected number."
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodTargetInvocation
+ PSComputerName : vmdeploytest1
This works, with the string in the statement:
$vmName = "vmdeploytest1"
Invoke-Command -ComputerName $vmName -Credential $creds -ScriptBlock {
$account = [ADSI]("WinNT://localhost/Administrator,user")
$account.psbase.invoke("setpassword","Password123")
}
This doesn't:
$vmName = "vmdeploytest1"
$password = '"Password123"'
$invoke = '"setpassword",'
$invokeStr = $invoke + $password
Invoke-Command -ComputerName $vmName -Credential $creds -ScriptBlock {
$account = [ADSI]("WinNT://localhost/Administrator,user")
$account.psbase.invoke($invokeStr)
}
This doesn't
$vmName = "vmdeploytest1"
$password = '"Password123"'
Invoke-Command -ComputerName $vmName -Credential $creds -ScriptBlock {
$account = [ADSI]("WinNT://localhost/Administrator,user")
$account.psbase.invoke("setpassword",$password)
}
This doesn't:
$vmName = "vmdeploytest1"
$password = 'Password123'
Invoke-Command -ComputerName $vmName -Credential $creds -ScriptBlock {
$account = [ADSI]("WinNT://localhost/Administrator,user")
$account.psbase.invoke("setpassword",$password)
}
All giving the same error. I need to be able to use a variable because I am going to generate a random password.
Jeroen Mostert is Correct
When you pass variables into a ScriptBlock you need to prefix them with $using:
For example:
$vmName = "vmdeploytest1"
$password = 'Password123'
Invoke-Command -ComputerName $vmName -Credential $creds -ScriptBlock {
$account = [ADSI]("WinNT://localhost/Administrator,user")
$account.psbase.invoke("setpassword",$using:password)
}

Invoke-Command Cannot Bind Argument Error

Is Invoke-Command not pulling my variables?
Im caught on this one. I could use an xtra set of eyes!
Im pulling services from a remote machine and assigning them by number then passing a stop / start to the remote machine based off user input. Im getting a argument on my variable.
Please forgive the code setup Im new and I write then I clean. Some services and names have been removed for privacy.
Code::
$prepend = "ssssssssss"
$append = "sss"
$Fprepend = "tttttttt"
$Fappend = "tt"
$sitenumber = Read-Host 'What is the site number? ex. 1111'
$name = $prepend + $sitenumber + $append
$Fname = $Fname = $Fprepend + $sitenumber + $Fappend
$global:i=0
Get-service -Name Service,Instance,Server,Integration,Data,Message,FTP,Provider -ComputerName $name |
Select #{Name="Item";Expression={$global:i++;$global:i}},Name -OutVariable menu | Format-Table -AutoSize
$r = Read-Host "Select a service to restart by number"
$svc = $menu | where {$_.item -eq $r}
Write-Host "Restarting $($svc.name)" -ForegroundColor Green
Invoke-Command -ComputerName $Fname -ScriptBlock {Stop-Service -Name $svc.name -Force}
sleep 3
Invoke-Command -ComputerName $Fname -ScriptBlock {Start-Service -Name $svc.name -Force}
Get-service -Name $svc.name -Computername $name
Error::
Cannot bind argument to parameter 'Name' because it is null.
+ CategoryInfo : InvalidData: (:) [Stop-Service], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.StopServiceCommand
Cannot bind argument to parameter 'Name' because it is null.
+ CategoryInfo : InvalidData: (:) [Start-Service], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.StartServiceCommand
I have modified the code and now its working fine.
The issue what you are facing is because inside the script block , $svc is not holding any value because its not in the scope even. To make it within the scope you have to pass as an ArgumentList and it has to be initiated inside the block as param. Thats why ou are getting as Null
Use the below code. I just modified the Invoke part
$prepend = "ssssssssss"
$append = "sss"
$Fprepend = "tttttttt"
$Fappend = "tt"
$sitenumber = Read-Host 'What is the site number? ex. 1111'
$name = $prepend + $sitenumber + $append
$Fname = $Fname = $Fprepend + $sitenumber + $Fappend
$global:i=0
Get-service -Name Service,Instance,Server,Integration,Data,Message,FTP,Provider -ComputerName $name |
Select #{Name="Item";Expression={$global:i++;$global:i}},Name -OutVariable menu | Format-Table -AutoSize
$r = Read-Host "Select a service to restart by number"
$svc = $menu | where {$_.item -eq $r}
Write-Host "Restarting $($svc.name)" -ForegroundColor Green
# You have to pass the $svc as an argumentlist and the same has to be initiated as param inside the script block.
Invoke-Command -ComputerName $Fname -ScriptBlock {param($svc)Stop-Service -Name $svc.name -Force} -ArgumentList $svc
sleep 3
Invoke-Command -ComputerName $Fname -ScriptBlock {param($svc)Start-Service -Name $svc.name -Force} -ArgumentList $svc
Get-service -Name $svc.name -Computername $name
Hope you understand the issue now.

Add-Computer fails by not finding the domain

I'm working an a script to autoconfigure my VMs. The idea is, that the VM automatic configures its netadapter and the joins a domain via default credentials. It's supposed to work with 2012r2, so PoShv4 is in use.
It works perfect until it comes to the point of working with Add-Computer
$vmName = (Get-ItemProperty –path 'HKLM:\SOFTWARE\Microsoft\Virtual Machine\Guest\Parameters').VirtualMachineName
$vmName = $vmName -replace '\w+\s+(.+)' , '$1'
$ip = $vmName -replace '\D+(\d+)' , '$1'
switch -Regex ($vmName) {
'dc' {$Ip = '10.18.0.{0}0' -f $ip}
'srv' {$Ip = '10.18.1.{0}0' -f $ip}
'CL' {$Ip = '10.18.2.{0}0' -f $ip}
}
#Configure IP-Settings
$netadapter = Get-NetAdapter -Name Ethernet
$netadapter | Set-NetIPInterface -DHCP Disabled | Out-Null
$netadapter | New-NetIPAddress -IPAddress $ip -PrefixLength 16 -DefaultGateway 10.18.0.10 | Out-Null
Set-DnsClientServerAddress -InterfaceAlias Ethernet -ServerAddresses 10.18.0.10 | Out-Null
#Create Credentials for Domainjoin
$username = 'domain\administrator'
$password = ConvertTo-SecureString 'Passw0rd' -AsPlainText -Force
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $username, $password
Start-Sleep -Seconds 5
#Check if Domainjoin possible
if ($vmName -eq 'DC1')
{
Install-WindowsFeature AD-Domain-services -IncludeAllSubFeature -IncludeManagementTools
Rename-Computer $vmName -Restart
}
elseif ($vmName -match 'DC')
{
Install-WindowsFeature AD-Domain-services -IncludeAllSubFeature -IncludeManagementTools
-DomainCredential $cred -NewName $vmName -Restart
}
else
{
$null = [net.dns]::Resolve('domain.tld')
Add-Computer -DomainName 'domain.tld' -DomainCredential $cred -NewName $vmName -Restart -Server 'dc1.domain.tld'
}
Add-Computer fails with the following error:
Add-Computer : Der angegebene Servername "dc1.domain.tld" kann nicht aufgelöst werden.
In C:\VMAutoConfig.ps1:42 Zeichen:5
+ Add-Computer -DomainName 'domain.tld' -DomainCredential $cred -NewName $ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (dc1.domain.tld:String) [Add-Computer], InvalidOperationException
+ FullyQualifiedErrorId : AddressResolutionException,Microsoft.PowerShell.Commands.AddComputerCommand
Any known issues with that?
Timedelay of up to 5 secs between netadapter config and Add-Computer does not help at all.
If I run the script a second time, everthing's ok and works.