I’ve run into an issue with PowerShell functions that I don’t understand. I guess my confusion is most of the examples I’ve found online and in books don’t work the way the authors explained (at least not for me).
The problem is when I define a parameter inside a function, that parameter is not accessible when running the script.
1 2 3 4 5 6 7 | function Get-CPUInfo { Param ($ComputerName) Get-WmiObject -Class Win32_Processor -ComputerName $ComputerName | Select-Object SystemName, CurrentClockSpeed, Manufacturer | Format-Table -AutoSize } Get-CPUInfo |
When I move the parameter outside of the function, it’s accessible and it works without issue. I’m guessing this is because of the scope of the variable?
1 2 3 4 5 6 7 | Param ($ComputerName) function Get-CPUInfo { Get-WmiObject -Class Win32_Processor -ComputerName $ComputerName | Select-Object SystemName, CurrentClockSpeed, Manufacturer | Format-Table -AutoSize } Get-CPUInfo |
Is this how parameters are suppose to work or am I doing something wrong? Any comments on clarifying this would be appreciated.
Update – March 21, 2012
One thing I have figured out is that a parameter defined inside a function can be called from within the script (just not outside the script like in the first example).
Update #2 – March 21, 2012
I think I finally understand what’s going on after discussing with a developer friend of mine and running the function as shown below.
µ
I’m at a loss. Your code looks perfect, so I copied it into ISE and saved it with the same name. I ran the same command lines as you and it worked great everytime.
Drop the code into a new file and give it another try.
BTW, here’s my results:
PS C:_DevelopmentPowershell> .Get-CPUInfo.ps1 -computername daltfcwds01
SystemName CurrentClockSpeed Manufacturer
———- —————– ————
DALTFCWDS01 2659 GenuineIntel
You are missing one key thing . . .
You shoud have the param inside the function. Then you load the script which contains the function using the following format.
. .Get-CPUInfo.ps1
The dot and then the path to the script. This is known as dot sourcing.
Modules will have all of the internal scripts dot sourced automatically which is why modules become the next logical progression from writing functions.
So anyway to finish off, one you have dot sourced the script into memory (which has to be done every session OR when ever you modify the function in anyway), then you just call the function by name
Get-CpuInfo -ComputerName client123
I hope this helps.
sorry one more thing. remove the call to the function from within your script.