PowerShell Create Folder on Remote Server


The following script does not add a folder to my remote server. Instead it places the folder on My machine! Why does it do it? What is the proper syntax to make it add it?

$setupFolder = "c:\SetupSoftwareAndFiles"

$stageSrvrs | ForEach-Object {
  Write-Host "Opening Session on $_"
  Enter-PSSession $_

  Write-Host "Creating SetupSoftwareAndFiles Folder"

  New-Item -Path $setupFolder -type directory -Force 

  Write-Host "Exiting Session"

  Exit-PSSession

}

Answers:


Enter-PSSession can be used only in interactive remoting scenario. You cannot use it as a part of a script block. Instead, use Invoke-Command:

$stageSvrs | %{
         Invoke-Command -ComputerName $_ -ScriptBlock { 
             $setupFolder = "c:\SetupSoftwareAndFiles"
             Write-Host "Creating SetupSoftwareAndFiles Folder"
             New-Item -Path $setupFolder -type directory -Force 
             Write-Host "Folder creation complete"
         }
}