0

I have a CSV file with data like this..

Data.csv

Name, Machine, Model, Wifi
User1, Machine1, Dell Lattitude, Connected
User2, Machine2, Dell Lattitude, disconnected
User3, Machine3, Dell Lattitude, Connected

I also have txt file with specific machines like this

desktops.txt

machine1
machine4
machine5

What i need to do is change the "WIFI" value from "connected' to "connected*" if the machine has a value of "connected" and its also in the desktops.txt file

Here is the code i have, but its not changing the WIFI value on any rows.

$ImportedCSV = Import-CSV data.csv

foreach($server in Get-Content .\desktops.txt) {
    $NewCSV = Foreach ($Entry in $ImportedCsv) {
        $SEL = Select-String -Path desktops.txt -Pattern "$server"
        if (($SEL -eq $True) -and ($Entry.WIFI -eq 'connected')) {
            $Entry.WIFI = 'connected*'
        }
        $Entry
    }
}

$NewCSV | Export-CSV data2.csv -NoTypeInformation

Desired CSV output is

Name, Machine, Model, Wifi
User1, Machine1, Dell Lattitude, Connected*
User2, Machine2, Dell Lattitude, disconnected
User3, Machine3, Dell Lattitude, Connected

thank you

1 Answer 1

1

You should not use Select-String on data you have imported with Import-Csv. Instead, just probe the properties on each item:

# read the machines as string array
$machines = Get-Content -Path 'D:\Test\desktops.txt'
# loop through the data and replace the Wifi property when needed
$csv = Import-Csv -Path 'D:\Test\data.csv' | ForEach-Object {
    if ($machines -contains $_.Machine -and $_.Wifi -eq 'Connected') {
        $_.Wifi = 'Connected*'
    }
    # now output the row changed or unchanged to build the $csv
    $_
}

# output on screen
$csv | Format-Table -AutoSize   # or $csv | Out-GridView 

# output to (new) csv file
$csv | Export-Csv -Path 'D:\Test\newdata.csv' -NoTypeInformation

Output on screen using Format-Table:

Name  Machine  Model          Wifi        
----  -------  -----          ----        
User1 Machine1 Dell Lattitude Connected*  
User2 Machine2 Dell Lattitude disconnected
User3 Machine3 Dell Lattitude Connected   
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.