I have a csv file with 2 columns ComputerName and Credssp.
Id like to identify certain computers by the ComputerName Column and change their value which is currently set to false and make it true.
I will be storing the computer names in an array.
Here is what I have so far
$credssp = $($s.ComputerName)
foreach ($c in $credssp ){
$computer = @()
$computer = $c
$value = 'true'
Import-Csv 'C:\TestComputers.csv'| ForEach-Object {
if ($_.computername -like "*$computer*") {
$_.credssp = "$value"
}
$_ | Export-Csv 'C:\TestComputers.csv' -NoTypeInformation -Append
}
}
Your method is not very efficient, as you are importing and exporting the CSV file for every computer name in the array.
It would be a better idea to only import and export once.
This is how I’d do it:
$credssp = $($s.ComputerName)
$value = 'true'
$Imported = Import-Csv 'C:\TestComputers.csv'
$Output = foreach ($i in $Imported) {
foreach ($c in $credssp) {
if ($i.ComputerName -like "*$c*") { $i.Credssp = $value }
}
$i
}
$Output
#$Output | Export-Csv 'C:\TestComputers.csv' -NoTypeInformation
If you’re happy with the output on screen, then uncomment the last line to overwrite the CSV.
question why is the last $i there … outside of the $Output = foreach ($i in $Imported) { } $i ,
That is to return the current line of the CSV file, which will go into the $Output array.
Basically the flow of the script is as follows:
- Import the CSV file.
- Loop through each line in the CSV file, and for each line create a new loop, which goes through each entry in the $credssp array.
- For each entry in the $credssp array, compare the entry with the ComputerName value from the current line in the imported CSV file.
- If they match, then change the Credssp value for that line.
- After checking all the matching, then output the line from the CSV (whether it was modified or not).
- At the end of the Import-CSV loop, capture all the output lines into the $Output array.
- Export the $Output array to a CSV file again, overwriting the original.
Hope that helps.
it realy did thanks again!