Add-Computer fails by not finding the domain - powershell

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.

Related

Powershell SSH credentials

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
```

For dotnetcore 3.1 Windows service how to stop, uninstall, install and start the service with a powershell script 5.1

For starters i made the below script for PS 5.1 (i know that PS 6.0 has the Remove-Service option but not 5.1).
I have all the required .exe, dll's and config's along with this script that is packaged as an artifact and will be deployed on the Headnode directory of the target.
Not sure if the below script will uninstall and install the service. But i can see that it is deleting and starting the new service when i run it.**
```
$acl = Get-Acl "C:\Program Files\Matt\Wservice"
$aclRuleArgs = "XYZ", "Read,Write,ReadAndExecute", "ContainerInherit,ObjectInherit", "None", "Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($aclRuleArgs)
$acl.SetAccessRule($accessRule)
if (Get-Service "Wservice" -ErrorAction 'SilentlyContinue')
{
Stop-Service -Name Wservice -ErrorAction SilentlyContinue -Force
(Get-WmiObject -Class Win32_Service -filter "Name='Wservice'").delete()
Write-Host "Please wait until removing the : Wservice "
Start-Sleep -s 30
}
$Username = 'xyz'
$Password = '123'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$MySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username,$pass
New-Service -Name Wservice -BinaryPathName "C:\Program Files\Matt\Wservice\Wservice.exe" -Credential $MySecureCreds -DisplayName "WserviceService" -StartupType Automatic
Start-Service -Name "Wservice"
```
Powershell core 6.0/7.0 dosent seem to have get-wmiobject, WMI is depreceated, then we have to use CIM using Get-CIMInstance.
Rest all seem OK. Coreected code:
$acl = Get-Acl "C:\Program Files\Matt\Wservice"
$aclRuleArgs = "XYZ", "Read,Write,ReadAndExecute", "ContainerInherit,ObjectInherit", "None", "Allow"
$accessRule = New-Object System.Security.AccessControl.FileSystemAccessRule($aclRuleArgs)
$acl.SetAccessRule($accessRule)
if (Get-Service "Wservice" -ErrorAction 'SilentlyContinue')
{
Stop-Service -Name Wservice -ErrorAction SilentlyContinue -Force
(Get-CIMInstance -Class Win32_Service -filter "Name='Wservice'").delete()
Write-Host "Please wait until removing the : Wservice "
Start-Sleep -s 30
}
$Username = 'xyz'
$Password = '123'
$pass = ConvertTo-SecureString -AsPlainText $Password -Force
$MySecureCreds = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $Username,$pass
New-Service -Name Wservice -BinaryPathName "C:\Program Files\Matt\Wservice\Wservice.exe" -Credential $MySecureCreds -DisplayName "WserviceService" -StartupType Automatic
Start-Service -Name "Wservice"

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.

A positional parameter cannot be found that accepts argument-System.Management.Automation.PSCredential'-Error

I have a script which needs to run from remote by passing on credentials in the script as as below:-
$UserName = Read-Host "Enter User Name:"
$Password = Read-Host -AsSecureString "Enter Your Password:"
$Credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $UserName , $Password
Set-Service -Name HiTrust -StartupType Automatic -ComputerName ServerName -credential $Credential
(Get-Service -Name "HiTrust" -credential $Credential -ComputerName ServerName).Start()
Exit
However I keep on getting error as below:-
Set-Service : A positional parameter cannot be found that accepts argument 'System.Management.Automation.PSCredential'.
At C:\Users\ucub\Desktop\Test.ps1:9 char:15
+ ... Set-Service -Name HiTrust -StartupType Automatic -Compute ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Set-Service], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.SetServiceCommand
If you are on this PSVersion and below, here is your root cause of why this fails on Set-Service...
$PSVersionTable.PSVersion
<#
Major Minor Build Revision
----- ----- ----- --------
5 1 17763 503
#>
(Get-Command -Name Set-Service).Parameters.Keys
# Results
ComputerName
Name
DisplayName
Description
StartupType
Status
InputObject
PassThru
Verbose
Debug
ErrorAction
WarningAction
InformationAction
ErrorVariable
WarningVariable
InformationVariable
OutVariable
OutBuffer
PipelineVariable
WhatIf
Confirm
You have unneeded stuff in the script as well.
I suggest refactoriung to this
(Get-Command -Name Invoke-Command).Parameters.Keys
# Results
Session
ComputerName
Credential
...
$ServerName = Read-Host 'Enter a target server name:'
$ServiceName = Read-Host 'Enter a target service name:'
Invoke-Command -ComputerName $ServerName -ScriptBlock {
"Executing service actions on $env:COMPUTERNAME"
Set-Service -Name $ServiceName -StartupType Automatic
Start-Service -Name $ServiceName
} -Credential (Get-Credential -Credential "$env:USERDOMAIN\$env:USERNAME")
The Problem is, that set-service doesn't have a credential parameter. Look here
Try something like this:
Enter-PSSession -ComputerName $computername -Credential $credentials
Set-Service -Name HiTrust -StartupType Automatic
or
Invoke-Command -ComputerName $computername -Credential $credential -ScriptBlock {Set-Service -Name HiTrust -StartupType Automatic}

Rename computer and add join domain powershell script

I am trying to rename a machine and add it to the domain with 1 restart from WORKGROUP (after the machine gets renamed and joined domain). I tried the code below but it's giving me an error:
$bios = (Get-WmiObject Win32_Bios).SerialNumber
$name = $bios
Rename-Computer -NewName "$name"
$domain = "DOMAINNAME"
$username = "USERNAME"
$password = "PASSWORD" | ConvertTo-SecureString -AsPlainText -Force
$Credential = New-Object System.Management.Automation.PSCredential($username,$password)
Add-Computer -DomainName $domain -Credential $credential -NewName $name
Read-Host "The computer will restart in 5..."
shutdown /r /t 5
The error I'm receiving is the account already exist. It does join the domain but not the "Renamed" name that I want.
This is how it has to be done.
Rename-Computer -NewName newserver -Force
Add-Computer -DomainName example.ne -Credential $credential -NewName newserver -Options JoinWithNewName
You could better read the full documentation of Add-Computer cmdelt. Get-Help Add-Computer -Online