2011-03-07 101 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 
相关问题