PowerShell Create Folder on Remote Server

The following script does not add the folder to my remote server. Instead, it places the folder on My machine! Why is he doing this? What is the correct syntax to 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 } 
+7
source share
3 answers

Enter-PSSession can only be used in interactive remote mode. You cannot use it as part of a script block. Use the Invoke-Command command instead:

 $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" } } 
+13
source

UNC path also works with New-Item

 $ComputerName = "fooComputer" $DriveLetter = "D" $Path = "fooPath" New-Item -Path \\$ComputerName\$DriveLetter$\$Path -type directory -Force 
+11
source

For those who -ScriptBlock does not work, you can use this:

 $c = Get-Credential -Credential $s = $ExecutionContext.InvokeCommand.NewScriptBlock("mkdir c:\NewDir") Invoke-Command -ComputerName PC01 -ScriptBlock $s -Credential $c 
+1
source

All Articles