As detailed in:
$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?
As detailed in:
$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?
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
.
$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
Test.psm1
file.Caller.ps1
file in a subfolder.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