PowerShell Create Folder on Remote Server

醉酒当歌 提交于 2019-12-09 05:32:48

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!