开发者

PowerShell Create Folder on Remote Server

开发者 https://www.devze.com 2023-02-15 04:53 出处:网络
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?

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 SetupSoftwar开发者_StackOverflow社区eAndFiles Folder"

  New-Item -Path $setupFolder -type directory -Force 

  Write-Host "Exiting Session"

  Exit-PSSession

}


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


UNC path works as well with New-Item

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


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


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
}


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


If you need to provide a folder name from the client, @Freddie has given clever answer. But I find more easy to do following:

$cred = Get-Credential
$session = New-PSSession -ComputerName $server -Credential $credInvoke- 
Command -Session $session -ScriptBlock { param ($folder) New-Item -Path $folder -ItemType Directory } -ArgumentList @("C:\temp\my_new_folder")
0

精彩评论

暂无评论...
验证码 换一张
取 消