How am I doing this wrong? I'm trying to dot source a script, I want to the variables outside of running the function so I have tried the following:
. "c:\scripts\test.ps1" When I try to look at the variables, I get nothing. I am using a dot, then a space, then the path to the ps1 file. I have tried it with quotes, without quotes, I have tried an explicit path, I also navigated to the directory of the script and tried . .\test.ps1. I have tried it in the powershell.exe, in the ISE, and in PowerGui. I have also started powershell as an administrator, and still nothing.
My execution policy is unrestricted, why isn't this working?
You seem to be doing the dot-sourcing correctly.
What is in the .ps1 file ? Just assignments to variables ?
Try a simple test:
$test = 123
. .\test.ps1
$test
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
Thanks for the reply
Arghhh, I thought I could also dot source a function, here is what I tried.
function SourceTest {
}
Then I dot sourced the file name, which is DS.ps1, which does not work. If I remove the function:
$DotATest = 1
$DotBTest = 2
$DotAnswer = $DotATest + $DotBTest
You should be able to dot-source a function.
Did you do a Get-Function after you did the dot-source of the .ps1 file ?
Is SourceTest in the list ?
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference
I just tried this, in this order
1. I closed out of every instance of Powershell
2 I opened PowerGUI
3. I did a file/open on the script/function to test, it's called DS.ps1
The contents are:
Function Source {
4. I hit F5 to run it in PowerGUI, and then in the Console, I called the Function "Source", it displayed "3". Just to check I tried a "$DotATest", it did not show the number "1".
5. I changed to the directory C:\PSscripts
6. Then I typed . .\DS.ps1 "Dot, space, .\DS.ps1
7. I looked for the variable $DotATest, and still nothing.
If it's not a function, then it works.
Ok, now I see what you mean.
The variable assignment inside a function is not executed when you dot-source that .ps1 file.
By doing a dot-source of the .ps1 file, the PS engine reads the function definition but it does not execute the function.
After the dot-source you will be able to call the function.
If you want to dot-source variable assignments, you will have to do them outside the function definition in the .ps1 file.
Then the variable will have the value from the .ps1 file after doing the dot-source.
Think of it as executing a regular script from the Gui.
If you have the following in the editor and do a F5
function Do-Test{
$test = 123
}
the function will not be executed. You didn't call the function.
For that, you would need to have
Function Do-Test{
$test = 123
}
Do-Test
in the editor
Blog: lucd.info Twitter: @LucD22 Co-author PowerCLI Reference