Powershell - Import local CSV

2019-08-22 21:14发布

问题:

I have a powershell script that imports a CSV file using this command:

$empCsv = Import-Csv "addEmp.csv"

I have the csv sitting in the same directory as the script but I'm getting a FileNotFoundException. If I use the command with a path to the CSV like this:

$empCsv = Import-Csv .\Desktop\createUser\addEmp.csv

It works fine.

I want to be able to give this script to someone to use and let them run the script from any location and be able to import the .csv that's sitting in the same directory.

Why can't my first command find the csv?

Thanks!

回答1:

To import a CSV in the same directory, I suggest:

$empCsv = Import-Csv "$PSScriptRoot\addEmp.csv"

PSScriptRoot gives you the path of the currently executing script.