Command don't works when use an variable. RRS feed

  • Question

  • Hello Scripting guys :)

    Im trying to delete folders on a remote server. Before launch theRemove command i wanna see the folders to delete:

    If i launch this line, works correctly:

    Get-ChildItem "\\SERVER1\D$\FOLDER1" | Select-object -Property FullName, LastWriteTime

    If i use a variable $Server the command does not work:

    Get-ChildItem $Server$Folder | Select-object -Property FullName, LastWriteTime

    But if i use this other command it works again:

    Get-ChildItem $Server$Folder | % { $_.FullName }

    Why does this happen?

    I also need to see the LastWriteTime property but i do not know how to combine it with  % { $_.FullName }

    Many thanks

    • Edited by Pedro_A Friday, January 18, 2019 12:07 PM
    • Moved by Bill_Stewart Friday, March 15, 2019 6:18 PM This is not "scripts on demand"
    Friday, January 18, 2019 11:38 AM

All replies

  • $server = 'server1'
    $folder = 'myfolder'
    Get-ChildItem "\\$Server\D$\$Folder" | 
         Select-object -Property FullName, LastWriteTime


    • Edited by jrv Friday, January 18, 2019 1:21 PM
    Friday, January 18, 2019 1:19 PM
  • Your format seems to work for me ....?

    Get-ChildItem $Server$Folder | Select-object -Property FullName, LastWriteTime

    Friday, January 18, 2019 5:52 PM
  • Ok sorry, it works, the problem is because i call get-childitem before the Foreach loop

    This fails:

    $Server = Get-Content "D:\_SCRIPTS\servers.txt"

    $Path = "test"

    Get-ChildItem "\\$Server\S$\$Path" | Select-object -Property FullName, LastWriteTime

    Foreach ($Server in $Server)

    Get-ChildItem -Path "\\$Server\S$\$Path" -Include *.* -Recurse -Force | Remove-Item -Recurse -Force -Whatif }

    I just need see the folders before delete it, I thought I had to launch the command before the loop. I still do not understand the order of execution of scripts

    I going to try it 


    Monday, January 21, 2019 9:59 AM
  • Hi again,

    I am having several problems due to lack of knowledge about the structure of powershell script.

    I try with Invoke-Commnad instead Get-Childitem and the result are good, but i dont know if it is better to include it in the ForEach loop or execute it previously.

    $Servers = Get-Content 'D:\_SCRIPTS\servers.txt' $Path= 'D:\Test' Invoke-Command $Servers -ScriptBlock { Get-ChildItem "D:\Test" } | Select-object -Property PSComputerName, FullName, LastWriteTime Foreach ($Item in $Servers) { Invoke-Command $Item -ScriptBlock { Get-ChildItem "D:\Test" -Recurse -Force | Remove-Item -Recurse -Force }


    In the first invoke, i must use "S:\Test", if use $Path does not work.

    Any help?


    • Edited by Pedro_A Tuesday, January 22, 2019 10:48 AM
    Tuesday, January 22, 2019 10:46 AM
  • help invoke-command -full


    Tuesday, January 22, 2019 10:49 AM