问题
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
}
回答1:
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"
}
}
回答2:
UNC path works as well with New-Item
$ComputerName = "fooComputer"
$DriveLetter = "D"
$Path = "fooPath"
New-Item -Path \\$ComputerName\$DriveLetter$\$Path -type directory -Force
回答3:
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
回答4:
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
}
来源:https://stackoverflow.com/questions/5226772/powershell-create-folder-on-remote-server