Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Foreach loops Always runs the last object results

I’m still new with the powershell, there’s a questions with my script, my intention is to import the CSV data under column Name
then do a split() for each object with "computername" and "username", however it can catch the arrays with two results, but after the loop in Foreach it only runs the last object. Can someone help Thanks!

whole code

$ImportPath ="C:\data.csv"
$ComputerArray= @()

Import-Csv -Path $ImportPath |ForEach-Object{$ComputerArray+= $_.Name}

Foreach($Hostname in $ComputerArray){
$CharArray =$Hostname.Split("\")
$ComputerName = $CharArray[0]
$Username = $CharArray[1] 

}

CSV date looks like
CSV data

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

$ComputerArray results
----------------------
Computer1\Local User
Computer2\Remote User

Hopes to look like

$ComputerName results
---------------------
Computer1
Computer2

$Username results
---------------------
Local User
Remote User

>Solution :

It’s not running the last object only, it’s running all the objects but you’re only capturing the last one. Both variables $computerName and $userName are getting re-assigned on each iteration.

Below will give you an array of objects with the Computer and User properties for each line of your CSV.

$ImportPath = "C:\data.csv"
$ComputerArray = (Import-Csv -Path $ImportPath).Name

$result = foreach($Hostname in $ComputerArray)
{
    $ComputerName, $Username = $Hostname.Split("\")
    [pscustomobject]@{
        Computer = $ComputerName
        User = $Username
    }
}

$result | Format-Table

If you want to get the computers on one array and the users on other array like in your expected output you can do $result.Computer and $result.User.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading