James Brown
James Brown

Reputation: 347

Powershell function failure

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.

Upvotes: 0

Views: 190

Answers (1)

oɔɯǝɹ
oɔɯǝɹ

Reputation: 7625

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;
}

Upvotes: 5

Related Questions