2013-06-03 16 views
173

Piszę skrypt PowerShell, aby utworzyć kilka katalogów, jeśli nie istnieją.Utwórz katalog, jeśli nie istnieje

System plików wygląda podobnie do tego

D:\ 
D:\TopDirec\SubDirec\Project1\Revision1\Reports\ 
D:\TopDirec\SubDirec\Project2\Revision1\ 
D:\TopDirec\SubDirec\Project3\Revision1\ 
  • Każdy projekt folder ma wiele zmian.
  • Każdy folder wersji wymaga folderu Reports.
  • Niektóre foldery "wersji" zawierają już folder Reports; jednak większość nie.

Potrzebuję napisać skrypt, który działa codziennie, aby utworzyć te foldery dla każdego katalogu.

Jestem w stanie napisać skrypt, aby utworzyć folder, ale tworzenie kilku folderów jest problematyczne.

Odpowiedz

2

Z Twojej sytuacji wynika, że ​​musisz utworzyć folder "Wersja #" raz dziennie z folderem "Raporty". Jeśli tak jest, po prostu musisz wiedzieć, jaki jest następny numer wersji. Napisz funkcję, która otrzyma kolejny numer wersji Get-NextRevisionNumber. Czy można zrobić coś takiego:

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

próbowałeś parametr -Force?

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

Możesz użyć Test-Path -PathType Container, aby najpierw sprawdzić.

Zobacz artykuł pomocy MSDN New-Item, aby uzyskać więcej informacji.

+58

dla leniwych, jest skrótem: md -Force c: \ foo \ bar \ baz –

+33

Dla tych, którzy nie chcą żadnych wyjście kiedy folder zostanie utworzony, dodaj "| Out-Null" na końcu – armannvg

7

Po określeniu flagi -Force program PowerShell nie będzie narzekał, jeśli folder już istnieje.

One-liner:

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

BTW, do planowania zadań należy sprawdzić ten link: Scheduling Background Jobs.

11

Miałem dokładnie ten sam problem. Można użyć czegoś takiego:

$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 kontrole w celu sprawdzenia, czy istnieje ścieżka. Jeśli nie, utworzy nowy katalog.

+3

Proszę wyjaśnij swoje rozwiązanie, zamiast podawać tylko kod ... – andreas

+0

To nie działa! Dokonaj niewielkiej zmiany – Ram

+0

To działało dla mnie: New-Item -ItemType Directory -Force -path $ path –

6

Istnieją 3 sposoby wiem stworzyć katalog za pomocą 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

Chciałem móc w łatwy sposób pozwolić użytkownikom utworzyć domyślny profil dla PowerShell, aby zastąpić niektóre ustawienia, a skończyło się na następującym jednym liniowcu (wiele instrukcji tak, ale można wkleić do PowerShell i wykonać od razu, co było głównym cel):

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!' }; 

dla czytelności, oto jak zrobiłbym to w ps1 pliku zamiast:

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

Oto prosty, który pracował dla mnie. Sprawdza, czy ścieżka istnieje, a jeśli tak nie jest, to nie tylko stworzyć ścieżkę główną, ale wszystkie podkatalogi także:

$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\} 
  • Pierwsza linia tworzy zmienną o nazwie $path i przypisuje mu wartość ciągu „C: \ temp \”

  • Druga linia stanowi oświadczenie If która opiera się na test-Path cmdlet, aby sprawdzić, czy zmienna $path nie istnieje. Nie istnieje, jest kwalifikowana pomocą ! symbol

  • Trzecia linia: Jeśli ścieżka przechowywane w łańcuchu powyżej nie zostanie znaleziony, zostanie uruchomiony kod w nawiasach klamrowych

md jest wersja skrócona wpisywać się: New-Item -ItemType Directory -Path $path

Uwaga: nie testowano przy użyciu parametru -Force z poniżej, aby zobaczyć czy jest niepożądane zachowanie, jeśli ścieżka już istnieje.

New-Item -ItemType Directory -Path $path

2

Poniższy fragment kodu pomaga stworzyć pełną ścieżkę.

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

Powyższa funkcja dzieli ścieżkę, która została przekazana do funkcji, i sprawdzi każdy folder, czy istnieje, czy nie. Jeśli nie istnieje, utworzy odpowiedni folder do momentu utworzenia folderu docelowego/końcowego.

Aby wywołać funkcję, skorzystaj z poniższego zestawienia:

GenerateFolder "H:\Desktop\Nithesh\SrcFolder" 
Powiązane problemy