Script Blocks and Invoke-Command

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Gorstag Gorstag 3 months, 2 weeks ago.

  • Author
    Posts
  • #63651
    Profile photo of Gorstag
    Gorstag
    Participant

    Am a bit confused as to why I am seeing the behavior I am seeing. If anyone can point me to some reading if it is not an easy explanation that would be great.

    Simple script block.

    $sb = {
    $DefaultFolder = "Test2"
    $DefaultPath = "C:\temp\FolderTest\"
    $date = Get-Date -format MM-yyyy
    $newname = $env:COMPUTERNAME + '-' + $date
    $folders = Get-ChildItem -Name
    Foreach ($folder in $folders){
    IF ($folder.Contains("$DefaultFolder") -eq $True ) {
    $final = Join-Path $DefaultPath $DefaultFolder
    Rename-Item $final $newname}
    }
    }
    

    If I execute it like:

    & $sb 

    Then it works fine on the local box. However, if I try to send it down an invoke-command (even to the same local system) either by doing computername or on a session nothing happens.

    Invoke-command -computername $hostname -scriptblock $sb 

    or

    $s = new-pssession -computername $hostname -crediential $cred
    Invoke-command -Session $s -scriptblock $sb 

    But If i do something simple like:

     Invoke-command -computername $hostname -scriptblock {get-process} 

    It works fine.

    What am I missing?

  • #63664
    Profile photo of Daniel Krebs
    Daniel Krebs
    Moderator

    I think below line is missing the parameter -Path or -LiteralPath. Get-ChildItem assumes the current working directory of your session if you don't specify -Path or -LiteralPath.

    $folders = Get-ChildItem -Name
    

    If you replace with below it should work:

    $folders = Get-ChildItem -Name -Path $DefaultPath
    
    • #63682
      Profile photo of Gorstag
      Gorstag
      Participant

      That was totally it. Hence why it was working locally because I was sitting in the path inside the shell.

      Thanks!

You must be logged in to reply to this topic.