Get values from two files and execute in PowerShell script

Administrators may need to execute a PowerShell script based on values inside two different files.

This task can be achieved by using arrays in PowerShell.

  • Consider a scenario in which you have a Computer Name and their respective MAC addresses in two different files.
  • Then you can create two variables to store the computer names and MAC addresses in each.
  • Then you can define a variable which will increment through the loop and corresponding data will be used in the script based on incremental number.
  • Refer below example
Clear-Host

# Import Active Directory PS-Module to run the AD commandlets
Import-Module ActiveDirectory

# Remove variables to avoid any unknown values
Remove-Variable -Name $MyCompany* -Force -ErrorAction SilentlyContinue

# Defining variables and their types as ARRAY
$MyCompanyCompNameList = [System.Collections.ArrayList]@()
$MyCompanyCompMACidList = [System.Collections.ArrayList]@()

# Importing values in variables
$MyCompanyCompNameList = @(Get-Content C:\Temp\ComputerList.txt)
$MyCompanyCompMACidList = @(Get-Content C:\Temp\MacIDList.txt)

# Auto-Correct MAC ID in standard format.
$MyCompanyCompMACidList = ($MyCompanyCompMACidList -replace ":","-")

$n = -1

foreach ($MyCompanyCompName in $MyCompanyCompNameList)
{
$n++
$MyCompanyCompName = $MyCompanyCompNameList["$n"]
$MyCompanyCompMACid = $MyCompanyCompMACidList["$n"]

# Write your powershell script below using the variables defined
# Sample
Write-Output "Computer object - $MyCompanyCompName assigned MAC ID : $MyCompanyCompMACid"
}