2

So i have this simple function that return my current script location:

function Get-CurrentDir
{
    $MyInvocation.MyCommand.Path
}

And i want to print this, so i try from PowerShell ISE after the function declaration:

Write-Host $(Get-CurrentDir)
Write-Host (Get-CurrentDir)
Write-Host Get-CurrentDir

And this is my output:

Write-Host $(Get-CurrentDir) --> Write-Host $(Get-CurrentDir)
Write-Host (Get-CurrentDir) --> Write-Host (Get-CurrentDir)
Write-Host Get-CurrentDir --> Write-Host Get-CurrentDir

What i am doing wrong ?

1 Answer 1

5

Ok, you would need to get the variable from the script scope, like so:

function Get-CurrentDir
{
    $script:MyInvocation.MyCommand.Path
}

also this won't work interactively. you would want to read more about_scopes in PowerShell.

Sign up to request clarification or add additional context in comments.

3 Comments

This is not return anything
What does this $script doing ?
its calling the variable from the script scope, i've updated my answer with a link to explain scopes in powershell

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.