PowerShell在远程服务器上创建文件夹

时间:2011-03-07 23:51:45

标签: powershell powershell-v2.0

以下脚本不会将文件夹添加到远程服务器。相反,它将文件夹放在我的机器上!它为什么这样做?添加它的正确语法是什么?

$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

}

5 个答案:

答案 0 :(得分:16)

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 :(得分:13)

UNC路径也适用于New-Item

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

答案 2 :(得分:1)

对于那些-ScriptBlock不起作用的人,可以使用:

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

答案 3 :(得分:0)

以下代码将使用$server中指定的服务器名称在远程服务器上创建新文件夹。以下代码假定凭据存储在MySecureCredentials并预先设置。只需致电createNewRemoteFolder "<Destination-Path>"即可创建新文件夹。

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
}

答案 4 :(得分:0)

$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
}