Author Posts

February 7, 2017 at 12:13 am

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?

February 7, 2017 at 11:00 am

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

February 7, 2017 at 6:36 pm

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

Thanks!