Search code examples
stringpowershellforeach

powershell - how to convert item in list to string?


I would like to replace variable $drive as 'D'. but it seems looks like that doesn't recognize 'D' as it is but something other format. when I run code, it shows blank only. Could you please check this code for me and advise to make it run?

$serverList = 'kr302vm', 'kr352fs', 'kr252py', 'kr101bu'

$driveList = 'D', 'E'
    
$output = foreach ($item in $serverList)    
{   
    
    foreach ($drive in $driveList)
    {

    $spaceObjects_D = Invoke-Command -ComputerName $item {Get-PSDrive | Where {$_.Name -eq $drive}} 
    $spaceObjects_D | Select-Object -Property PSComputerName, Name, @{Label='Used (GB)'; expression={($_.Used/1GB).ToString('F2')}}, @{Label='Free (GB)'; expression={($_.Free/1GB).ToString('F2')}}, @{Label='Free (%)'; expression={($_.Free/($_.Used + $_.Free)).ToString('P')}}

    }

}   
$output | Export-Csv -Path "C:\test\diskusage_A.csv" -NoTypeInformation 

Solution

  • The issue with your PowerShell script might be related to the scope of the variables inside the Invoke-Command script block. The variables $drive inside the Invoke-Command script block do not have access to the outer variables directly. This is because the script block is invoked on a remote computer, and it doesn’t have access to the local variables of your script.

    You can pass local variables to the Invoke-Command script block using the -ArgumentList parameter and the param keyword inside the script block. Here’s how you can modify your script:

    $serverList = 'kr302vm', 'kr352fs', 'kr252py', 'kr101bu'
    $driveList = 'D', 'E'
    
    $output = foreach ($item in $serverList)
    {
        foreach ($drive in $driveList)
        {
            $spaceObjects_D = Invoke-Command -ComputerName $item -ArgumentList $drive {
                param($drive)
                Get-PSDrive | Where {$_.Name -eq $drive}
            }
            $spaceObjects_D | Select-Object -Property PSComputerName, Name, @{Label='Used (GB)'; expression={($_.Used/1GB).ToString('F2')}}, @{Label='Free (GB)'; expression={($_.Free/1GB).ToString('F2')}}, @{Label='Free (%)'; expression={($_.Free/($_.Used + $_.Free)).ToString('P')}}
        }
    }
    $output | Export-Csv -Path "C:\test\diskusage_A.csv" -NoTypeInformation