Can't get folders list with Invoke-command

Hello

I am new to PowerShell.
I try to list all the folders in all drives except drive C in few servers ,
If I use Invoke-command (for computerName ) , I get folders from my C:\Users\userName folder only

The code:

$Params = Get-Content “D:\temp\Serverlist.txt”

foreach ($Server in $Params) {

    $Drives = get-wmiobject win32_volume -computer $Server | ? { $_.DriveType -eq 3 -and $_.DriveLetter -and $_.DriveLetter -ne “C:” } | Select -Expand Name

    Foreach ($Drv in $Drives) {
        Invoke-command -computer $Server -ScriptBlock { Get-ChildItem -Path $Drv -Depth 1 -Recurse -Directory -ErrorAction SilentlyContinue -Force | Where-Object FullName -notlike *RECYCLE* | select root, FullName }
    }
}

Any Idea?

Thank you for your help

I think the problem is you’re using $drv variable which doesn’t exist on the remote computer, because it’s not defined inside the script block of invoke-command. So when running Get-ChildItem on the remote computer, it defaults to the current path.

To tell powershell to use the $drv variable which exists on the local computer running the script, you can do this:

Get-ChildItem -Path $using:Drv

 

 

Another way would be to run all the code in the Invoke-Command script block, therefore the $drv variable would exist on the remote machine. See example:

$Params = Get-Content “D:\temp\Serverlist.txt”

foreach ($Server in $Params) {    
    Invoke-command -computer $Server -ScriptBlock {
        $Drives = get-wmiobject win32_volume | ? { $_.DriveType -eq 3 -and $_.DriveLetter } | Select -Expand Name
        Foreach ($Drv in $Drives) {
            Get-ChildItem -Path $Drv -Depth 1 -Directory -Recurse -ErrorAction SilentlyContinue -Force | Where-Object FullName -notlike *RECYCLE* | select root, FullName
        }
    } 
}

Thank you for your help - Its work now.