Home > Back-end >  Choose which CSV to import when running a Powershell Script
Choose which CSV to import when running a Powershell Script

Time:07-04

So I get a csv every week that our finance team puts in a shared drive. I have a script for that csv that I run once I get it.

The first command of the script is is of course Import-Csv.

Problem is, the Finance team insist on naming the file differently each time plus they don't always put it in the same location within the drive.

As a result, I have to first hunt for the file, put it into the directory that the script points to and then rename the file.

I've tried talking to the team about putting it in the same location and making sure the filename is the same but they only follow the instructions for a couple weeks before just doing whatever.

Ideally, I'd like for it so that when I run the script, there would be a popup that would ask me to pick a csv (Similar to how it looks when you do "Save As" on an Office Document).

Anyway for this to be done within powershell?

CodePudding user response:

You can access .Net classes and interface with the forms library to instantiate and take input from the standard FileOpen dialog. Something like below:

Using Namespace System.Windows.Forms

$FileBrowser = [OpenFileDialog]::new()
$FileBrowser.InitialDirectory = 'c:\temp'
$FileBrowser.Filter = 'Comma Separated Values (*.csv) | *.csv'
[Void]$FileBrowser.ShowDialog()

$CsvFile = $FileBrowser.FileName

Then use $CsvFile int he Import-Csv command.

You can change the .InitialDirectory property to make navigating a little more convenient.

Use the .Filter property to limit the file open display to CSV files, to make things that much more convenient.

Also, use the [Void] class to prevent the status return (usually 'OK' or 'Cancel') from echoing to the screen.

Note: A simple Google search will turn up many examples. I refined some of the work from here. That will also document some of the other properties if you want to explore etc.

CodePudding user response:

Steven's response certainly satisfies your original question, but an alternative would be to let PowerShell do the work. If you know the drive, and you know the name of the file this week, you can pass the name to your script and let it search the drive filtering on the specific csv file you need. Make it recursive, and open the only file that matches.

  • Related