tags:

views:

32

answers:

1

Hi there,

I have a script saved in a ps1 file in which I define 2 functions as such:

function Invoke-Sql([string]$query) {
  Invoke-Sqlcmd -ServerInstance $Server -Database $DB -User $User -Password $Password -Query $query
}

function Get-Queued {
  Invoke-Sql "Select * From Comment where AwaitsModeration = 1"
}

In the PowerShell console I then call the ps1 file by typing it in (it's in a folder in the path, and autocompletion works)

However, I cannot start using the functions. I am confused, because when I copy / paste the functions into the console, all is fine and they work. I also have a function defined in my profile, and it works. Where am I thinking wrong, why doesn't it work what I'm trying to do?

+4  A: 

You need to "dot source" the file. That is to say instead of:

PS> C:\PathTo\MyScript.ps1

Which executes the script (in your case the script only contains functions but nothing that uses those functions) but does not preserve the defined functions and variables in global state, you should instead do this:

PS> . C:\PathTo\MyScript.ps1

This will "load" your functions into the global scope so that they can be used later.

In PowerShell 2.0 you can also use Import-Module to load scripts in .psm1 files as "modules" which provide a better reuse and deployment story.

Josh Einstein
that's it, thx!
flq