'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
}
Solution 1:[1]
UNC path works as well with New-Item
$ComputerName = "fooComputer"
$DriveLetter = "D"
$Path = "fooPath"
New-Item -Path \\$ComputerName\$DriveLetter$\$Path -type directory -Force
Solution 2:[2]
For those who -ScriptBlock doesn't work, you can use this:
$c = Get-Credential -Credential
$s = $ExecutionContext.InvokeCommand.NewScriptBlock("mkdir c:\NewDir")
Invoke-Command -ComputerName PC01 -ScriptBlock $s -Credential $c
Solution 3:[3]
The following code will create a new folder on a remote server using server name specified in $server. The below code assumes credentials are stored in MySecureCredentials and setup beforehand. Simply call createNewRemoteFolder "<Destination-Path>" to create the new folder.
function createNewRemoteFolder($newFolderPath) {
$scriptStr = "New-Item -Path $newFolderPath -type directory -Force"
$scriptBlock = [scriptblock]::Create($scriptStr)
runScriptBlock $scriptBlock
}
function runScriptBlock($scriptBlock) {
Invoke-Command -ComputerName $server -Credential $MySecureCreds -ScriptBlock $scriptBlock
}
Solution 4:[4]
$Servers=Get-SPServer |?{ $_.Role -notlike "Invalid"}
foreach($Server in $Servers)
{
$Machine=$Server.Address
$Path= "SP Logs"
$NewFolder="Trace2"
$DL= "E"
#Write-Host "Server name is = " $Server
New-Item -Path \\$Machine\E$\$Path\$NewFolder -Force -ItemType Directory
}
Solution 5:[5]
If you need to provide a folder name from the client, @Freddie has given clever answer. But I find more easy to do following:
$cred = Get-Credential
$session = New-PSSession -ComputerName $server -Credential $credInvoke-
Command -Session $session -ScriptBlock { param ($folder) New-Item -Path $folder -ItemType Directory } -ArgumentList @("C:\temp\my_new_folder")
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Barry MSIH |
| Solution 2 | Mark Varnas |
| Solution 3 | Freddie |
| Solution 4 | Rose |
| Solution 5 | Roman Badiornyi |
