2011-03-07 186 views
7

以下腳本不會將文件夾添加到遠程服務器。相反,它將文件夾放在我的機器上!它爲什麼這樣做?什麼是適當的語法,使其添加?PowerShell在遠程服務器上創建文件夾

$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 

} 

回答

13

Enter-PSSession只能用於交互式遠程方案。您不能將其用作腳本塊的一部分。相反,使用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" 
     } 
} 
1

對於那些誰-ScriptBlock不起作用,你可以使用這個:

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

UNC路徑工程,以及與新建項目

$ComputerName = "fooComputer" 
$DriveLetter = "D" 
$Path = "fooPath" 
New-Item -Path \\$ComputerName\$DriveLetter$\$Path -type directory -Force 
相關問題