Créer un répertoire s’il n’existe pas

J’écris un script PowerShell pour créer plusieurs répertoires s’ils n’existent pas.

Le système de fichiers ressemble à ceci

D:\ D:\TopDirec\SubDirec\Project1\Revision1\Reports\ D:\TopDirec\SubDirec\Project2\Revision1\ D:\TopDirec\SubDirec\Project3\Revision1\ 
  • Chaque dossier de projet comporte plusieurs révisions.
  • Chaque dossier de révision nécessite un dossier Rapports.
  • Certains des dossiers “révisions” contiennent déjà un dossier Rapports; cependant, la plupart ne le font pas.

Je dois écrire un script qui s’exécute quotidiennement pour créer ces dossiers pour chaque répertoire.

Je suis capable d’écrire le script pour créer un dossier, mais créer plusieurs dossiers est problématique.

Avez-vous essayé le paramètre -Force ?

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

Vous pouvez utiliser Test-Path -PathType Container pour vérifier en premier.

Reportez -vous à l’article d’ aide Nouvel élément MSDN pour plus de détails.

 $path = "C:\temp\NewFolder" If(!(test-path $path)) { New-Item -ItemType Directory -Force -Path $path } 

Test-Path vérifie si le chemin existe. Si ce n’est pas le cas, cela créera un nouveau répertoire.

J’ai eu exactement le même problème. Vous pouvez utiliser quelque chose comme ceci:

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

Il y a 3 façons de créer un répertoire avec PowerShell

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

entrer la description de l'image ici

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

entrer la description de l'image ici

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

entrer la description de l'image ici

Lorsque vous spécifiez l’indicateur -Force , PowerShell ne se plaindra pas si le dossier existe déjà.

Bon mot:

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

BTW, pour planifier la tâche s’il vous plaît consulter ce lien: Planification des tâches en arrière-plan .

L’extrait de code suivant vous aide à créer un chemin complet.

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

La fonction ci-dessus divise le chemin que vous avez passé à la fonction et vérifie chaque dossier, qu’il existe ou non. S’il n’existe pas, il créera le dossier correspondant jusqu’à la création du dossier cible / final.

Pour appeler la fonction, utilisez l’instruction ci-dessous:

 GenerateFolder "H:\Desktop\Nithesh\SrcFolder" 

De votre situation, il semble que vous ayez besoin de créer un dossier “Révision #” une fois par jour avec un dossier “Rapports”. Si tel est le cas, il vous suffit de connaître le prochain numéro de révision. Ecrivez une fonction qui obtient le prochain numéro de révision Get-NextRevisionNumber. Ou vous pourriez faire quelque chose comme ça:

 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 ssortingng 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. } 

Installation de PowerShell 3.0

Je voulais être en mesure de permettre aux utilisateurs de créer facilement un profil par défaut pour PowerShell afin de remplacer certains parameters. ):

 cls; [ssortingng]$filePath = $profile; [ssortingng]$fileContents = ''; 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!' }; 

Pour plus de lisibilité, voici comment je le ferais dans un fichier ps1:

 cls; # Clear console to better notice the results [ssortingng]$filePath = $profile; # declared as ssortingng, to allow the use of texts without plings and still not fail. [ssortingng]$fileContents = ''; # 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"; }; 

Voici une simple qui a fonctionné pour moi. Il vérifie si le chemin existe et, si tel n’est pas le cas, il créera non seulement le chemin racine, mais également tous les sous-répertoires:

 $rptpath = "C:\temp\reports\exchange" if (!(test-path -path $rptpath)) {new-item -path $rptpath -itemtype directory} 
 $path = "C:\temp\" If(!(test-path $path)) {md C:\Temp\} 
  • La première ligne crée une variable nommée $path et lui assigne la valeur de chaîne “C: \ temp \”

  • La deuxième ligne est une instruction If qui repose sur l’applet de commande Test-Path pour vérifier si la variable $path n’existe pas. Le non existe est qualifié en utilisant le ! symbole

  • Third Line: Si le chemin stocké dans la chaîne ci-dessus n’est PAS trouvé, le code entre les accolades sera exécuté

md est la version courte de la saisie: New-Item -ItemType Directory -Path $path

Remarque: Je n’ai pas testé l’utilisation du paramètre -Force avec le paramètre ci-dessous pour voir s’il existe un comportement indésirable si le chemin existe déjà.

New-Item -ItemType Directory -Path $path