9

I am trying to emulate bash's source command in powershell. The intent is to make any change to my microsoft.powershell_profile.psl and source it into the existing instance of powershell.

The following command works in command-line

$profile_content = [string]::join([environment]::newline,(get-content $profile))
invoke-expression $profile_content

All is good; I put the same into microsoft.powershell_profile.psl and it does not work.

function source{
        $profile_content = [string]::join([environment]::newline,(get-content $args[0]))
        invoke-expression $profile_content
}

Am I overlooking something?

3
  • Can you share what values are being passed as $profile and $args[0]? Commented Aug 30, 2013 at 17:25
  • $profile is from the powershell environment. The value in my system is C:\Users\<name>\Documents\WindowsPowerShell\Microsoft.PowerShell_profile.ps1. I invoke the source command as 'source $profile' Commented Aug 30, 2013 at 17:29
  • UPDATE: trying to re-invent the wheel in a wrong way. better use '.' as answered. Commented Aug 30, 2013 at 18:40

3 Answers 3

23

What you want is already built into PowerShell:

. C:\path\to\some.ps1

See about_Operators:

. Dot sourcing operator
Runs a script in the current scope so that any functions, aliases, and variables that the script creates are added to the current scope.

. c:\scripts.sample.ps1
Sign up to request clarification or add additional context in comments.

2 Comments

This won't work for .env files
Note that modules with .psm1 extension must use Import-Module MyModule.psm
1

Following should be enough:

function source { . $args }

1 Comment

Unfortunately I think this only executes the script in the scope of the function, which means variable declarations etc. aren't visible to the caller.
0

Try changing your Microsoft.PowerShell_profile.ps1 to look like this:

function source{
        $profile_content = [string]::join([environment]::newline,(get-content $args[0]))
        invoke-expression $profile_content
}

source $profile

Basically, you can't just define the function, you need to call it in the file as well. HOWEVER, the way your function is set up, it will result in an infinite loop. Replace your function source() with something else.

1 Comment

I don't quite get it. why would I want to include the call to the function as part of the function definition in 'Microsoft.PowerShell_profile.ps1'? I will call the function from command-line.And why the infinite loop? those two lines of code work in command-line.

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.