2013-06-03 22 views
173

Sto scrivendo uno script PowerShell per creare diverse directory se non esistono.Crea directory se non esiste

Il file system è simile a questo Ogni progetto

D:\ 
D:\TopDirec\SubDirec\Project1\Revision1\Reports\ 
D:\TopDirec\SubDirec\Project2\Revision1\ 
D:\TopDirec\SubDirec\Project3\Revision1\ 
  • cartella ha revisioni multiple.
  • Ogni cartella di revisione necessita di una cartella Reports.
  • Alcune delle cartelle "revisioni" contengono già una cartella Reports; tuttavia, la maggior parte non lo fa.

Ho bisogno di scrivere uno script che viene eseguito ogni giorno per creare queste cartelle per ogni directory.

Sono in grado di scrivere lo script per creare una cartella, ma la creazione di più cartelle è problematica.

risposta

2

Dalla tua situazione sembra che sia necessario creare una cartella "Revisione #" una volta al giorno con una cartella "Rapporti". In tal caso, è sufficiente sapere qual è il prossimo numero di revisione. Scrivi una funzione che ottiene il numero di revisione successivo Get-NextRevisionNumber. Oppure si potrebbe fare qualcosa di simile:

foreach($Project in (Get-ChildItem "D:\TopDirec" -Directory)){ 
    #Select all the Revision folders from the project folder. 
    $Revisions = Get-ChildItem "$($Project.Fullname)\Revision*" -Directory 

    #The next revision number is just going to be one more than the highest number. 
    #You need to cast the string in the first pipeline to an int so Sort-Object works. 
    #If you sort it descending the first number will be the biggest so you select that one. 
    #Once you have the highest revision number you just add one to it. 
    $NextRevision = ($Revisions.Name | Foreach-Object {[int]$_.Replace('Revision','')} | Sort-Object -Descending | Select-Object -First 1)+1 

    #Now in this we kill 2 birds with one stone. 
    #It will create the "Reports" folder but it also creates "Revision#" folder too. 
    New-Item -Path "$($Project.Fullname)\Revision$NextRevision\Reports" -Type Directory 

    #Move on to the next project folder. 
    #This untested example loop requires PowerShell version 3.0. 
} 

PowerShell 3.0 installation

303

Hai provato il parametro -Force?

New-Item -ItemType Directory -Force -Path C:\Path\That\May\Or\May\Not\Exist 

È possibile utilizzare prima Test-Path -PathType Container.

Vedere l'articolo della guida MSDN New-Item per ulteriori dettagli.

+58

Per i più pigri, c'è una scorciatoia: md -Force c: \ foo \ bar \ baz –

+33

Per coloro che non vogliono alcun output quando la cartella viene creata, aggiungi "| Out-Null" alla fine – armannvg

7

Quando si specifica il flag -Force, PowerShell non si lamenterà se la cartella esiste già.

One-liner:

Get-ChildItem D:\TopDirec\SubDirec\Project* | ` 
    %{ Get-ChildItem $_.FullName -Filter Revision* } | ` 
    %{ New-Item -ItemType Directory -Force -Path (Join-Path $_.FullName "Reports") } 

BTW, per la pianificazione dell'attività si prega di consultare questo link: Scheduling Background Jobs.

11

Ho avuto lo stesso identico problema. Si può usare qualcosa di simile:

$local = Get-Location; 
$final_local = "C:\Processing"; 

if(!$local.Equals("C:\")) 
{ 
    cd "C:\"; 
    if((Test-Path $final_local) -eq 0) 
    { 
     mkdir $final_local; 
     cd $final_local; 
     liga; 
    } 

    ## If path already exists 
    ## DB Connect 
    elseif ((Test-Path $final_local) -eq 1) 
    { 
     cd $final_local; 
     echo $final_local; 
     liga; (function created by you TODO something) 
    } 
} 
51
$path = "C:\temp\NewFolder" 
If(!(test-path $path)) 
{ 
     New-Item -ItemType Directory -Force -Path $path 
} 

Test-Path controlli per vedere se esiste il percorso. Quando non lo fa, creerà una nuova directory.

+3

Spiega la tua soluzione anziché fornire solo il codice ... – andreas

+0

Non funziona! Fai un piccolo cambiamento – Ram

+0

Questo ha funzionato per me: New-Item -ItemType Directory -Force -path $ path –

6

Ci sono 3 modi che conosco per creare directory utilizzando PowerShell

Method 1: PS C:\> New-Item -ItemType Directory -path "c:\livingston" 

enter image description here

Method 2: PS C:\> [system.io.directory]::CreateDirectory("c:\livingston") 

enter image description here

Method 3: PS C:\> md "c:\livingston" 

enter image description here

2

Volevo essere in grado di consentire agli utenti di creare un profilo predefinito per PowerShell per sovrascrivere alcune impostazioni e terminare con il seguente one-liner (più istruzioni sì, ma può essere incollato in PowerShell ed eseguito contemporaneamente, che era il principale obiettivo):

cls; [string]$filePath = $profile; [string]$fileContents = '<our standard settings>'; if(!(Test-Path $filePath)){md -Force ([System.IO.Path]::GetDirectoryName($filePath)) | Out-Null; $fileContents | sc $filePath; Write-Host 'File created!'; } else { Write-Warning 'File already exists!' }; 

per facilitare la lettura, ecco come lo farei in un file PS1 invece:

cls; # Clear console to better notice the results 
[string]$filePath = $profile; # declared as string, to allow the use of texts without plings and still not fail. 
[string]$fileContents = '<our standard settings>'; # Statements can now be written on individual lines, instead of semicolon separated. 
if(!(Test-Path $filePath)) { 
    New-Item -Force ([System.IO.Path]::GetDirectoryName($filePath)) | Out-Null; # Ignore output of creating directory 
    $fileContents | Set-Content $filePath; # Creates a new file with the input 
    Write-Host 'File created!'; 
} else { 
    Write-Warning "File already exists! To remove the file, run the command: Remove-Item $filePath"; 
}; 
1

Ecco un semplice uno che ha lavorato per me. Esso controlla se esiste il percorso, e se non lo fa, non sarà solo creare il percorso principale, ma tutte le sottodirectory anche:

$rptpath = "C:\temp\reports\exchange" 

if (!(test-path -path $rptpath)) {new-item -path $rptpath -itemtype directory} 
1
$path = "C:\temp\" 

If(!(test-path $path)) 

{md C:\Temp\} 
  • prima riga crea una variabile chiamata $path e assegna il valore di stringa di "C: \ temp \"

  • seconda linea è un'affermazione If che si basa su test-Path cmdlet per verificare se la variabile $path non esiste. Il non esiste è qualificato con il simbolo !

  • Terza riga: se il percorso memorizzato nella stringa di cui sopra non viene trovata, verrà eseguito il codice tra le parentesi graffe

md è la versione corta di digitare: New-Item -ItemType Directory -Path $path

Nota: non ho eseguito il test utilizzando il parametro -Force con il sotto per verificare se esiste un comportamento indesiderato se il percorso esiste già.

New-Item -ItemType Directory -Path $path

2

Il seguente frammento di codice consente di creare percorso completo.

Function GenerateFolder($path){ 
    $global:foldPath=$null 
    foreach($foldername in $path.split("\")){ 
      $global:foldPath+=($foldername+"\") 
      if(!(Test-Path $global:foldPath)){ 
      New-Item -ItemType Directory -Path $global:foldPath 
      # Write-Host "$global:foldPath Folder Created Successfully" 
      } 
    } 
} 

Sopra funzione di dividere il percorso è stato passato alla funzione, e controllerà ogni cartella se è esistito o no. Se non esiste, crea la rispettiva cartella fino alla creazione della cartella di destinazione/finale.

per chiamare la funzione, utilizzare sotto dichiarazione:

GenerateFolder "H:\Desktop\Nithesh\SrcFolder"