Skip to content

Instantly share code, notes, and snippets.

@stephengodbold
Created February 20, 2013 23:31
Show Gist options
  • Save stephengodbold/5000699 to your computer and use it in GitHub Desktop.
Save stephengodbold/5000699 to your computer and use it in GitHub Desktop.
Parse a CSV file with PowerShell in C#
using (var shell = PowerShell.Create(sessionState))
{
var parameters = new Dictionary<string, object>
{
{"Path", tempFilePath},
{"Delimiter", ','}
};
var command = shell.AddCommand("Import-Csv").AddParameters(parameters);
var results = command.Invoke();
foreach (dynamic result in results)
{
environment.LastReleaseDate = result.ReleaseDate;
environment.PreviousBuild = result.PreviousVersion;
environment.CurrentBuild = result.CurrentVersion;
}
}
@dfinke
Copy link

dfinke commented Feb 21, 2013

Another approach. Leveraging positional parameters for the Import-Csv cmdlet. Your approach does provide more control over what PowerShell executes. With this approach, tempFilePath can have arbitrary PS code injected.

            var script = string.Format("Import-Csv " + tempFilePath);

            var ps = PowerShell.Create().AddScript(script);

            foreach (dynamic item in ps.Invoke())
            {

                Console.WriteLine(new Details()
                {
                    ReleaseDate = item.ReleaseDate,
                    PreviousVersion = item.PreviousVersion,
                    CurrentVersion = item.CurrentVersion
                });
            }

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment