In Powershell Script Set IP address, subnet mask, Default Gateway & Taking system into Domain both commands not working one after another

  Kiến thức lập trình

I am new in PowerShell. I created a CSV file and inside this CSV file I stored Computer Type, Is this system used nor not, Ip Address, Subnet Mast DNS1, DNS2, Domain Name, username, password, time zone.

[CSV File photo] (https://i.stack.imgur.com/neiiO.png)

Using PowerShell I import this file & stored all information of this csv file into Variables.

When I am changing the IP address of client using PowerShell & after that renaming the computer and taking into domain this both commands didn’t work one after another.

if I run both commands, it will give error this is the error “Error: Computer ‘zx’ failed to join domain ‘pritam.ugale’ from its current workgroup ’12’ with following error message: The specified domain either does not exist or could not be contacted.”

if I remove the changing IP address code from script and run the script then it will take system into domain without any issue. I dont understand why both commands didnt work.

here is my code:
`# Define the path to the CSV file
$csvFilePath = “C:tempkiran.csv”

#—————————————————————————————————————————
#Checking the path is correct or not start here.
Write-Host “nGreetings, sir. How may I be of assistance to you today?n”
Write-Host “???? ” -ForegroundColor DarkCyan -nonewline
Write-Host “Jarvis, let’s ensure all prerequisites are checked before firing up this program.  `n”

do
{
    if(Test-Path $csvFilePath)
    {
        
        Write-Host "`n   Sir, File location check finished : " -nonewline        
        write-host " ????" -f green
        break
    }else
    {
        Write-Host "`n   Understood, sir. It seems the file ???? was not found." -nonewline       
        write-host "$csvfilepath " -f red         
        $csvFilePath = Read-Host "`n   Please provide the correct path"  # Prompt user for correct path
    
    }

} while($true) #loop this code until correct location is provided.

#Checking the path is correct or not End   here.

#—————————————————————————————————————————

#—————————————————————————————————————————
# Read the CSV file
$csvData = Import-Csv -Path $csvFilePath
# Specify the row index (0-based) where the subnet mask is located
$rowIndex = 0 # Example row index
#Read the computer Name & Interface alias
#$computername = hostname ; $PrefixLength = $csvData[$rowIndex].PrefixLength # Access the subnet mask value$current_DG = (get-netroute -InterfaceAlias $InterfaceAlias -DestinationPrefix 0.0.0.0/0).NextHop
$InterfaceAlias = Get-NetAdapter | Select-Object -ExpandProperty InterfaceAlias
$Subnet_mask = $csvData[$rowIndex].Subnet_mask # Access the Subnet Mastk
$DG = $csvData[$rowIndex].default_gateway # Access the Default Gateway

$PrimaryDNS = $csvData[$rowIndex].DNS1 # Access the DNS 1   
$SecondaryDNS = $csvData[$rowIndex].DNS2# Access the DNS 2    

$DOMAIN = $csvData[$rowIndex].DOMAIN # Access the DOMAIN NAME 

$USERNAME = $csvData[$rowIndex].USERNAME # Access the User Name    
$PASSWORD = ConvertTo-SecureString $csvData[$rowIndex].PASSWORD -AsPlainText -Force   # Access the Password
$credential = New-Object System.Management.Automation.PSCredential($USERNAME, $PASSWORD)    
$time_zone = $csvData[$rowIndex].time_zone # Access the timezon      

#—————————————————————————————————————————
#—————————————————————————————————————————
# Checking all computer name is not more than 16 characters in lenght start here
foreach ($crowz in $csvData)
{
$compu = $crowz.cname ; $lenght = $compu.Length
if($compu.length -lt 15)
{
Write-Host “n Computer $compu Char Length $lenght is ok : " -nonewline write-host " ????" -f green }else { Write-Host "n Sir, Computer Lenth check failed : ” -nonewline
write-host $compu -f red
exit
}
}
# Checking all computer name is not more than 16 characters in lenght end here
#—————————————————————————————————————————
#—————————————————————————————————————————
# Checking all computer IP is CORRECT START here
function Test-IPAddress {
param (
[string]$IPAddress
)
$IPAddress -match ‘b(?:d{1,3}.){3}d{1,3}b’ -and [IPAddress]::TryParse($IPAddress, [ref]$null)
}
# Initialize a flag to track if all IP addresses are correct
$allIPsCorrect = $true
# Loop through each row in the CSV data
foreach ($iprow in $csvdata) {
# Check if IP address is correct
if (-not (Test-IPAddress -IPAddress $iprow.IP_address)) {
Write-Host “n IP address '$($iprow.IP_address)' for computer '$($iprow.CNAME)' is incorrect." -f Red; exit 2 $allIPsCorrect = $false } } # creating array for DG,DNS & dns2 for check ip address. $otherip = @($DG,$PrimaryDNS,$SecondaryDNS) # Loop through array foreach ($ipdns in $otherip) { # Check if IP address is correct if (-not (Test-IPAddress -IPAddress $ipdns)) { Write-Host "n IP address $ipdns is incorrect.” -f red; exit 3
$allIPsCorrect = $false
}
}
# Check if all IP addresses are correct and display the message accordingly
if ($allIPsCorrect) {
Write-Host “`n All IP addresses are correct.” -nonewline; write-host ” ????” -f green
}
# Checking all computer IP is CORRECT END here
#—————————————————————————————————————————
#—————————————————————————————————————————
#(User Account Control) has been adjusted to Never Notify Mode start here
try
{
Set-ItemProperty -Path REGISTRY::HKEY_LOCAL_MACHINESoftwareMicrosoftWindowsCurrentVersionPoliciesSystem -Name ConsentPromptBehaviorAdmin -Value 0

    Write-Host "`n   The" -NoNewline 
    Write-Host "  UAC" -ForegroundColor Green -NoNewline
    Write-Host " (User Account Control) has been adjusted to Never Notify Mode." -nonewline; write-host " ????" -f green
} catch { Write-Host "Failed to set the UAC setting. Error: $_" -f red}
#(User Account Control) has been adjusted to Never Notify Mode End here

#—————————————————————————————————————————
#—————————————————————————————————————————
# Set Time Zone Start Here *********
try
{

$nettimeset = "net time \$PrimaryDNS /set /yes"
$nettimeset;

Set-TimeZone -Id $time_zone

write-host "`n   The computer Timezone is set to " -nonewline 
write-host "$time_zone." -nonewline ; write-host " ???? `n" -f green
# Configure Windows to synchronize time with a specific internet time server   
Start-Service w32time
w32tm /config /manualpeerlist:$PrimaryDNS /syncfromflags:manual /reliable:yes /update
# Restart the Windows Time service to apply the changes
    Restart-Service w32time
}catch { Write-Host "Failed to set TimeZone setting. Error: $_" -f Red}
# Set Time Zone End Here *****************

#—————————————————————————————————————————
#—————————————————————————————————————————

Disabling the Firelall Start Here*

try
{
Set-NetFirewallProfile -Profile Domain,Private,Public -Enabled False

  write-host "`n   The computer " -NoNewline      
  Write-Host "filrewall " -ForegroundColor Green -NoNewline
  Write-Host "is off now "-NoNewline ; write-host " ???? `n" -f green

}
catch { Write-Host “Failed to set firewall setting. Error: $_” -F Red }

Disabling the Firelall End Here *

#———————————————————————————————————————————————————

Get input from user

$selection = Read-Host “nnPlease select your choice nn1. Cal n2. Noncal n3. Aria nnEnter Choice(Eg: Enter 1 for cal Enter 2 for non cal) “

Checking what input user given here

if($selection -eq 1 -or $selection -eq 2 -or $selection -eq 3 )
{
# If user select one ” 1 ” means user selected Cal
if($selection -eq 1)
{
$selection1 = ‘cal’
Write-Host “nnGreat!! you selected $selection1nn ” -ForegroundColor Green

    # Iterate through each row in the CSV data
    foreach ($row in $csvData)
    {
        # Check if the computername is "cal" and the used value is "no"
        if ($row.ctype -eq "cal" -and $row.used -eq "no") 
        {

            #----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
            # Changing IP address start here 
            try
            {                
                # Set IP address, subnet mask, and default gateway                       
                     netsh interface ip set address name = $InterfaceAlias static $row.IP_address $Subnet_mask $DG

                # Set DNS servers
                    Set-DnsClientServerAddress -InterfaceAlias $InterfaceAlias -ServerAddresses ($PrimaryDNS, $SecondaryDNS)

                    Write-Host "1. Hmmm The IP Address ( " -NoNewline #.....................................................No 1 One
                    Write-Host $row.IP_address -ForegroundColor Green -NoNewline
                    Write-Host " ) & DNS has been assign to this computer "$row.CNAME
                
            }catch { Write-Host "Failed to set the IP setting or DNS Setting. Error: $_" -f Red }
            # Changing IP address END here 
            #----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
            # Taking system into domain Start here
            try
            {
               $rowcname =  $row.CNAME
               Add-Computer -DomainName $DOMAIN -credential $credential -NewName $rowcname -ErrorAction Stop
               Write-Host "`n2. Computer rename & inside of this domain " -NoNewline #......................................................No 5 
               Write-Host $DOMAIN -ForegroundColor Green
            }
            catch
            {
                Write-Host "`nFailed to take system into domain. Error: $_"
            }                
            # Taking system into domain End here
            #----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------   
            #----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
            # Collecting Serial Number here.
            try
            {                
               $serialNumber = Get-WmiObject -Class Win32_BIOS | Select-Object -ExpandProperty SerialNumber
                $pcname = hostname
                if($row.CNAME -eq $pcname){
                $row.sr = $serialNumber  
                }
            }catch { Write-Host "Failed collect the serial number: $_" -f Red }
            # Collecting Serial Number End here. 
            #----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------            
            
            # Change the used value to "yes"****               
            $row.used = "yes"                
            # Break out of the loop after the first match
           break 
        } 
        
    }         
} # user slection one finished here *
                            #----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------    


   

}
else{write-host “`n$selection Mission Abort” -ForegroundColor Red}

Export the modified CSV data back to the file

$csvData | Export-Csv -Path $csvFilePath -NoTypeInformation

#———————————————————————————————————————————————————————————-

            <# Rename comamnd Start here                              
              Rename-Computer -NewName $row.CNAME -Force -passthru
              if($?){write-host "`n4. The computer rename is completed.`n"}                
            else
            {
                Write-Host "Failed to Rename Computer. Error: $_" 
            }
            # Rename comamnd End here*******************#>

#———————————————————————————————————————————————————————————-
`

I am trying to take input from csv file and perform this activity. 1.Checking all computer name is not more than 16 characters.
2. Checking all computer IP is CORRECT
3. (User Account Control) has been adjusted to Never Notify Mode
4. Set Time Zone
5. Disabling the Firewall
6. Set IP address, subnet mask, and default gateway
7. Taking system into domain
8. Collecting Serial Number

New contributor

Gene Slouka is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.

LEAVE A COMMENT