PowerShell: создание сценария для MSTSC по имени хоста, если DNS не работает, используйте IP - PullRequest
0 голосов
/ 09 октября 2018

Good Day All,

Я пишу сценарий, чтобы облегчить мою жизнь на работе (все причины для сценариев).Я новичок в PowerShell, но в настоящее время я самоучка.Прямо сейчас у меня есть текстовый скрипт меню.У меня есть выбор для удаленного доступа к компьютеру с помощью MSTSC по имени компьютера И выбор для удаленного доступа к компьютеру с помощью MSTSC по IP.

Это был мой оригинальный сценарий, чтобы мои идеи развивались, но теперь в режиме очистки ... Я хотел бы объединить их в один вариант и сделать так, чтобы в случае сбоя DNS по любой причине он попыталсяIP.Я предоставил свой сценарий (я знаю, что это, вероятно, беспорядок. Помните, я на 100% самоучка и работаю над выяснением того, как очистить это).Я открыт и для других предложений.

Заранее спасибо!

########################
## Get Computer Info ##
########################

<# 
Description: This script will provide remote computer info.

Put together by: Allen Scott
#>

<# Change Log
Modified: 10/9/2018
Cleaning Up Script:
#>

# Set Console Environment
$host.ui.RawUI.WindowTitle = "Tech Support"
$Host.UI.RawUI.BackgroundColor = ($bckgrnd = 'Black')
$Host.UI.RawUI.ForegroundColor = 'Cyan'
$Host.PrivateData.ErrorForegroundColor = 'DarkRed'
$Host.PrivateData.ErrorBackgroundColor = $bckgrnd
$Host.PrivateData.WarningForegroundColor = 'Red'
$Host.PrivateData.WarningBackgroundColor = $bckgrnd
$Host.PrivateData.DebugForegroundColor = 'Yellow'
$Host.PrivateData.DebugBackgroundColor = $bckgrnd
$Host.PrivateData.VerboseForegroundColor = 'blue'
$Host.PrivateData.VerboseBackgroundColor = $bckgrnd
$Host.PrivateData.ProgressForegroundColor = 'Gray'
$Host.PrivateData.ProgressBackgroundColor = $bckgrnd


cls
Write-host " "

"

  ______          __       _____                              __ 
 /_  __/__  _____/ /_     / ___/__  ______  ____  ____  _____/ /_
  / / / _ \/ ___/ __ \    \__ \/ / / / __ \/ __ \/ __ \/ ___/ __/
 / / /  __/ /__/ / / /   ___/ / /_/ / /_/ / /_/ / /_/ / /  / /_  
/_/  \___/\___/_/ /_/   /____/\__,_/ .___/ .___/\____/_/   \__/  
                                  /_/   /_/                      

"
Write-host -ForegroundColor green "*********************************************************************************************************************" 
Write-host  -ForegroundColor green "                                      Welcome to the Tech Support Computer Information Script.`n
                                      ----------------------------------------------------------`n
This Script is used for gathering remote computer information (Serial Number, MAC Address, IP, Windows Version, Etc).`n
Also, this script can be used to check connectivity and open the file explorer of the remote computer.`n
You can end this script at any time by pressing 'CTRL + C'. `n
After each process, it will also ask if you want to do another. `n  "
Write-host -ForegroundColor green "*********************************************************************************************************************"
Write-host -ForegroundColor green " "



#Set Window Title Bar
$computer = Read-Host "Enter Computer Name "    
cls
do {
cls
Write-host " "
Write-host " "

" 

  ______          __       _____                              __ 
 /_  __/__  _____/ /_     / ___/__  ______  ____  ____  _____/ /_
  / / / _ \/ ___/ __ \    \__ \/ / / / __ \/ __ \/ __ \/ ___/ __/
 / / /  __/ /__/ / / /   ___/ / /_/ / /_/ / /_/ / /_/ / /  / /_  
/_/  \___/\___/_/ /_/   /____/\__,_/ .___/ .___/\____/_/   \__/  
                                  /_/   /_/                      

"

    # Reset Window Title
    $host.ui.RawUI.WindowTitle = "Tech Support - $computer Menu"

    # Ask admin what process to start (Only allow the characters "1, 2, 3, 4, 5, 6, 7, 8"
    $process = Read-host "`nWhat would you like to do with $computer ? `n(1) Check Connectivity  (2) Sonar  (3) Get IP (4) Get MAC`n(5) Open Backdoor (6) Remote In (7) Full Computer Info (8) New Computer"

# Ensures only 1-8 are inputted
    while("1","2","3","4","5","6","7","8" -notcontains $Process)
        {
            Write-host -ForegroundColor red "Invalide Response. Please choose 1,2,3,4,5,6,7,8"
            $Process = Read-host "`nWhat would you like to do with $computer ? `n(1) Check Connectivity  (2) Sonar  (3) Get IP (4) Get MAC`n(5) Open Backdoor (6) Remote In (7) Full Computer Info (8) New Computer"
        }

    #If [1] is selected, Start check Connectivity
    If ($process -eq 1) 
        {

            Write-host -ForegroundColor green "`nStarting Check Connectivty`n"
            # Set new title
            $host.ui.RawUI.WindowTitle = "Tech Support - Check Connectivity"


            # Start Connectivity Check
             If (Test-Connection -ComputerName $computer -Count 1 -Quiet)
                {
                    Write-Host "$computer is Online" -ForegroundColor Green
                } 
                else 
                {
                    Write-Host "$computer is offline" -ForegroundColor Red
                }

            #Pause for Display
            write-host " "
            pause
            $goToStart = "y"
        } 

    #If [2] is selected, Start Sonar
    If ($process -eq 2) 
        {

            Write-host ""
            Write-host -ForegroundColor green "`nStarting Sonar Process`n"

            $host.ui.RawUI.WindowTitle = "Tech Support -  Sonar"

            #Start SONAR

            Write-Host "Pinging $computer by sonar . . . "
            do
                { 
                    if (Test-Connection -count 1 -quiet -computer $computer)
                        {

                            [console]::beep(800,800)
                            Write-Host "$computer is Online!" -ForegroundColor Green
                            Start-Sleep -s 2
                        } 
                    else
                        {
                        [console]::beep(500,60)
                        Write-Host "$computer is Offline!" -ForegroundColor Red            
                        }
                }
            until (Test-Connection -count 1 -quiet -computer $computer)

            #Pause for Display
            write-host " "
            pause
            $goToStart = "y"

        }

    #If [3] is selected, Get IP Address     
    If ($process -eq 3) 
        {

            Write-host ""
            Write-host -ForegroundColor green  "`nStarting Get IP Address Process`n"
            $host.ui.RawUI.WindowTitle = "Tech Support -  Checking IP Address "

            Write-host ""
            $ip = Test-Connection $computer -count 1 | select Address,Ipv4Address

            Write-host $ip

            #Pause for Display
            write-host " "
            pause
            $goToStart = "y"
        }
    #If [4] is selected, Get Mac.  
    If ($process -eq 4) 
        {

            Write-host ""
            Write-host -ForegroundColor green "`nStarting Get MAC Process`n"
            $host.ui.RawUI.WindowTitle = "Tech Support -  Get MAC "

            $computerMAC = Get-WmiObject -ClassName Win32_NetworkAdapterConfiguration -Filter "IPEnabled='True'" -ComputerName $Computer | Select-Object -Property MACAddress
            Write-Host $computerMAC

            #Pause for Display
            write-host " "
            pause
            $goToStart = "y"

        }
    #If [5] is selected, open remote file explorer
    If ($process -eq 5) 
        {
            Write-host ""
            Write-host -ForegroundColor green "`nStarting remote file explorer Process`n"
            $host.ui.RawUI.WindowTitle = "Tech Support -  Open remote file explorer "

            start \\$computer\c$

            #Pause for Display
            write-host " "
            pause
            $goToStart = "y"                
        }

    #If [6] is selected, set new computer name
    If ($process -eq 6) 
        {
            $User="admUser"
            cmdkey /generic:TERMSRV/$Computer /user:$User
            mstsc /v:$computer
            $goToStart = "y"
        }  

    #If [7] is selected, display full Computer information
    If ($process -eq 7) 
        {

            Write-host ""
            Write-host -ForegroundColor green "`nFull Computer Info Process`n"
            $host.ui.RawUI.WindowTitle = "Tech Support -  Full Computer Info "

            #Set Variables
            $computerSystem = get-wmiobject Win32_ComputerSystem -Computer $Computer
            $computerMAC = Get-WmiObject -ClassName Win32_NetworkAdapterConfiguration -Filter "IPEnabled='True'" -ComputerName $Computer | Select-Object -Property MACAddress
            $computerBIOS = get-wmiobject Win32_BIOS -Computer $Computer
            $computerOS = get-wmiobject Win32_OperatingSystem -Computer $Computer
            $computerVersion = If ($computerOS.BuildNumber -eq "16299") {
                '1709'
                 } ElseIf ($computerOS.BuildNumber -eq "15063") {
                    '1703'
                 } ElseIf ($computerOS.BuildNumber -eq "14393") {
                    '1607'
                 }Else {
                    'Need to Update If Table for ' + $computerOS.BuildNumber
                }
            $computerCPU = get-wmiobject Win32_Processor -Computer $Computer
            $computerHDD = Get-WmiObject Win32_LogicalDisk -ComputerName $Computer -Filter drivetype=3

            #Output Details
            write-host "System Information for: " $computerSystem.Name -BackgroundColor Black -ForegroundColor Green
            "-------------------------------------------------------"
            "Manufacturer: " + $computerSystem.Manufacturer 
            "Model: " + $computerSystem.Model
            "Serial Number: " + $computerBIOS.SerialNumber
            "   " + $computerMAC
            "CPU: " + $computerCPU.Name
            "HDD Capacity: "  + "{0:N2}" -f ($computerHDD.Size/1GB) + "GB"
            "HDD Space: " + "{0:P2}" -f ($computerHDD.FreeSpace/$computerHDD.Size) + " Free (" + "{0:N2}" -f ($computerHDD.FreeSpace/1GB) + "GB)"
            "RAM: " + "{0:N2}" -f ($computerSystem.TotalPhysicalMemory/1GB) + "GB"
            "Operating System: " + $computerOS.caption + ", Service Pack: " + $computerOS.ServicePackMajorVersion + ", OS Version: " + $computerVersion
            "User logged In: " + $computerSystem.UserName
            "Last Reboot: " + $computerOS.ConvertToDateTime($computerOS.LastBootUpTime)
            ""
                "-------------------------------------------------------"

            #Pause for Display
            write-host " "
            pause
            $goToStart = "y"

        }

    #If [8] is selected, set new computer name
    If ($process -eq 8) 
        {

        $computer = Read-Host "Enter Computer Name: "
        $goToStart = "y"


    }

    } while ($goToStart -eq "Y") cls

1 Ответ

0 голосов
/ 11 октября 2018

Что бы я сделал в этом случае после $ computer = Read-Host "Введите имя компьютера" (строка 58).Я бы добавил: $ ipaddress = [System.Net.DNS] :: GetHostAddresses ($ computer).В дальнейшем, если вы захотите использовать IP-адрес, скажем, после сбоя if (Test-Connection) {}, вы просто вызовете $ ipaddress.IPaddressToSTring для IP-адреса.- jrider

Спасибо за вашу помощь!

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...