0

As detailed in:

PowerShell-Import-Local-CSV

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

Is classed as an answer. This doesn't work for me when i run this code inside a function. How can i test this?

Royston
  • 433
  • 2
  • 9
  • 25

2 Answers2

0

You can test your Powershell version with $PSVersionTable.PSVersion. If it is below version 3.0 you can use:

Split-Path $script:MyInvocation.MyCommand.Path -Parent

to find the directory the current script is running from instead of $PSScriptRoot.

Theo
  • 57,719
  • 8
  • 24
  • 41
  • I'm having a problem importing the CSV using my import-csv $PSScriptRoot Folder\file.csv. It doesn't work. – Royston Oct 05 '18 at 13:19
  • Aha, but then please explain *what* exactly does not work. Do you get error messages? – Theo Oct 05 '18 at 13:23
0

$PSScriptRoot will provide the path for the currently running script/function, so if a script runs a function from another location, $PSScriptRoot will contain that other location.

If you want to get the path of the script that's calling the function, leverage $MyInvocation:

$empCsv = Import-Csv "$(Split-Path $MyInvocation.ScriptName)\addEmp.csv"

Demo

  • Create the Test.psm1 file.
  • Create the Caller.ps1 file in a subfolder.
  • Run Caller.ps1.
  • $PSScriptRoot will refer to Test.psm1 location, $MyInvocation will refer to Caller.ps1 location.

Test.psm1:

Function Test{
    Write-host "PSScriptRoot: $PSScriptRoot"
    Write-host "MyInvocation: $(Split-Path $MyInvocation.ScriptName)"
}

Caller.ps1:

Import-Module ..\Test.psm1 -Force
Test
G42
  • 9,791
  • 2
  • 19
  • 34