Powershell noob - How do you return something from a funciton?
-
Thursday, October 07, 2010 11:37 PM
Hi,
I have the following code:
Function CreateWorkbook ([string]$wbName) { $xl=new-object -comObject Excel.Application $wb = $xl.Workbooks.Add() Write-Host $wb } #$bk = $xl.Workbooks.Open('sample.xls') $wbook = CreateWorkbook('name') $wbook.GetType()
When I run it I get an error:
You cannot call a method on a null-valued expression.
At :line:10 char:11
+ $wbook.GetType <<<< ()Basically all i want to do is return the object that the function creates and store it in $wbook. How do i do that?
Thanks
Jamie
http://sqlblog.com/blogs/jamie_thomson/ | @jamiet | About me

All Replies
-
Thursday, October 07, 2010 11:38 PM
No worries, figured it out!!
Function CreateWorkbook ([string]$wbName) { $xl=new-object -comObject Excel.Application $wb = $xl.Workbooks.Add() return $wb } $wbook = CreateWorkbook('name') $wbook.GetType()
http://sqlblog.com/blogs/jamie_thomson/ | @jamiet | About me

- Marked As Answer by Tiger LiModerator Friday, October 08, 2010 3:57 AM
-
Friday, October 08, 2010 1:11 AM
In this function either Return or Write-Output will produce the desired result. However, if you ever write a function that needs to return multiple objects, Return will exit the function after only returning the first object.
I think Jeff Hicks explains it well here: http://blog.sapien.com/index.php/2009/06/02/powershell-functions-return-vs-write/
- Marked As Answer by Jamie ThomsonMVP Friday, October 08, 2010 8:14 AM
-
Friday, October 08, 2010 8:14 AM
Interesting. Thanks very much.In this function either Return or Write-Output will produce the desired result. However, if you ever write a function that needs to return multiple objects, Return will exit the function after only returning the first object.
I think Jeff Hicks explains it well here: http://blog.sapien.com/index.php/2009/06/02/powershell-functions-return-vs-write/
http://sqlblog.com/blogs/jamie_thomson/ | @jamiet | About me


