0

I swear I'm missing something easy here...

Here's a simple script to get disk info:

function get-disks {
try { $disks = gwmi win32_logicaldisk -co $server}
catch { write "$server : Can't connect"}
}
get-disks
$disk.deviceid

The gwmi command alone works perfectly. The "$disks = gwmi..." command alone works perfectly. The try {...}catch{...} lines run alone work perfectly.

But as soon as I load the function and call 'get-disks' I receive no errors, but $disks is empty.

2
  • Incidentally, I removed the try-catch out of the function and into the main body of the script and got the same non-results. Commented Jan 30, 2015 at 20:55
  • Good catch on that. But my original script has $disks.deviceid. I mis-copied it when posting this question. And now I'll edit it. Commented Jan 30, 2015 at 20:58

1 Answer 1

5

The $server parameter, and the $disks variable are local to the inside function and not visible (not defined) outside of the function.

You need to provide the server name as a function parameter (from the outside in), and you need to return the $disks variable value from the function (from the inside out) and capture it's value.

function Get-Disks {
    param(
        [Parameter(Mandatory = $true)]
        [string] $Server
    )

    try { 
      $result = gwmi win32_logicaldisk -co $Server;
      return $result    # <--
    }
    catch { write "$Server : Can't connect"}
}

$disks = Get-Disks -Server "localhost"

Note that the $result variable inside the function is another variable the the $disks variable outside of the function.

For simplicity, you can write the function as follows:

function Get-Disks {
    param(
        [Parameter(Mandatory = $true)]
        [string] $Server
    )

    # just return the output of gwmi directly 
    gwmi win32_logicaldisk -co $Server;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Yes, this. Also when you call the function use $disk = get-disks if you want to reference the properties of it afterward (your existing code doesn't assign anything to $disk).
I presume returning the $disks variable changes it from a local variable in the function to a global variable the rest of the script can use, correct?
@James No, you are returning a value from the function, and catching that value in the external variable. If you didn't catch the result value, it would be caught by the console, and displayed there.
The variable inside the function can have any name you like, it won't change the mechanics. For good measure, it is advisable to not reuse variable names like this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.