Search code examples
regexpowershellpowershell-cmdlet

Is there a way to extract only the value from "free" field of Get-PSDrive?


I'm trying to take the value of free space from a drive, this is necessary to do an automatict procedure in a database server.

I got this script:

    $query_drive_mount_point = @"
    select distinct
    convert(varchar(512), b.volume_mount_point) as [volume],
    convert(varchar(512), b.logical_volume_name) as [logical_volume]
    from sys.master_files as [a]
    CROSS APPLY sys.dm_os_volume_stats(a.database_id, a.[file_id]) as [b]
    "@

        [regex]$get_drive = '\w\:\\'
        [regex]$get_drive_name = '\w'
        [regex]$get_drive_space = '\d'
        $mount_point = Invoke-Sqlcmd -ServerInstance "$server_ip\$sql_engine,$sql_port" -Username "$sql_user" -Password "$sql_password" -Database Master -Query "$query_drive_mount_point" 

        $get_disk = $get_drive.Matches($mount_point) | Foreach-Object {$_.Value}
        $get_disk_name = $get_drive_name.Matches($get_disk) | Foreach-Object {$_.Value}

        $size_bytes_string = Get-PSDrive $get_disk_name | Select-Object -Property Free
        [int]$size_bytes = $get_drive_space.Matches($size_bytes_string) | ForEach-Object {$_.Value} 
        $size_giga = ( ( ( $size_bytes )/1024 )/1024 )/1024

This code runs without problem until this line:

[int]$size_bytes = $get_drive_space.Matches($size_bytes_string) | ForEach-Object {$_.Value} 

It throws this error:

There was not found overload for "Matches" and args numbers is "1".
En línea: 1 Carácter: 1
+ $size_bytes = $get_drive_space.Matches($size_bytes_string) | ForEach- ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodCountCouldNotFindBest

The last error is a traduction made by me, the os is in spanish.

Again, the objective is to store only the free space value.


Solution

  • You need to select the value from the property you need, so this line:

    $size_bytes_string = Get-PSDrive $get_disk_name | Select-Object -Property Free to 
    

    Should be changed to the following:

    $size_bytes_string = Get-PSDrive $get_disk_name | Select-Object -ExpandProperty Free
    

    Alternatively you can format it as follows:

    ($size_bytes_string = Get-PSDrive $get_disk_name).Free