Skip to content

Instantly share code, notes, and snippets.

@brianbunke
Created January 1, 2016 16:56
Show Gist options
  • Save brianbunke/64c7aad8552691988565 to your computer and use it in GitHub Desktop.
Save brianbunke/64c7aad8552691988565 to your computer and use it in GitHub Desktop.
function Invoke-PowerCSV {
[CmdletBinding()]
param (
# Position 1 is implied here, and doesn't need to be specified
[Parameter(Mandatory = $true)]
[string[]]$ComputerName,
[Parameter(Mandatory = $true,
ValueFromPipeline = $true)]
$InputFile,
# Mandatory = $false is the default
[int]$UpdateValue
)
BEGIN {
$CSV = Import-Csv -Path $InputFile
}
PROCESS {
If (-not $UpdateValue) { ### This is the Part 1 block
# Use -contains for array matching, because I'm allowing more than one computer name to be defined
$CSV | Where {$ComputerName -contains $_.ComputerName} | Select * -ExcludeProperty ComputerName | ForEach-Object {
# Dynamically discover value columns; no need to assume there will always be five
ForEach ($Property in ($_ | Get-Member | Where MemberType -eq NoteProperty | Select -ExpandProperty Name)) {
Write-Output $_.$Property
}
}
} Else { ### This is the Part 2 block
# I think the challenge is asking me to:
# Match ComputerName
# Remove the value in first position
# Add UpdateValue in last position
# Dynamically discover value columns; no need to assume there will always be five
$Values = $CSV | Get-Member | Where MemberType -eq NoteProperty | Select -ExpandProperty Name | Where {$_ -ne 'ComputerName'}
# Defining empty array allows for appending objects/rows below (the +=)
$OverwriteCSV = @()
ForEach ($CSVRow in $CSV) {
If ($ComputerName -contains $CSVRow.ComputerName) {
# Loop through the row, value by value, moving them forward one column
For ($i=0; $i -lt ($Values.Count -1); $i++) {
$CSVRow.($Values[$i]) = $CSVRow.($Values[$i+1])
}
# That loop ignores the last row, so change the last row here
$CSVRow.($Values | Select -Last 1) = $UpdateValue
# With those value changes made, now the row can be appended
$OverwriteCSV += $CSVRow
} Else {
$OverwriteCSV += $CSVRow
}
}
$OverwriteCSV | Export-Csv -Path $InputFile -NoTypeInformation -Force
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment