Script Blocks and Invoke-Command

Welcome Forums General PowerShell Q&A Script Blocks and Invoke-Command

This topic contains 2 replies, has 2 voices, and was last updated by

 
Participant
2 years ago.

  • Author
    Posts
  • #63651

    Participant
    Points: 0
    Rank: Member

    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

    Moderator
    Points: 24
    Team Member
    Rank: Member

    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

      Participant
      Points: 0
      Rank: Member

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

      Thanks!

The topic ‘Script Blocks and Invoke-Command’ is closed to new replies.

denizli escort samsun escort muğla escort ataşehir escort kuşadası escort