Maak map als deze niet bestaat

Ik schrijf een PowerShell-script om verschillende mappen te maken als ze niet bestaan.

Het bestandssysteem lijkt op dit

D:\
D:\TopDirec\SubDirec\Project1\Revision1\Reports\
D:\TopDirec\SubDirec\Project2\Revision1\
D:\TopDirec\SubDirec\Project3\Revision1\
  • Elke projectmap heeft meerdere herzieningen.
  • Elke Revision-map heeft een map Rapporten nodig.
  • Enkele van de mappen “Revisions” bevatten al een map Rapporten; Meest niet.

Ik moet een script schrijven dat dagelijks wordt uitgevoerd om deze mappen voor elke map te maken.

Ik kan het script schrijven om een ​​map te maken, maar het maken van verschillende mappen is problematisch.


Antwoord 1, Autoriteit 100%

Probeer de -Forceparameter:

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

U kunt Test-Path -PathType Containerom eerst te controleren.

Zie de nieuw-item MSDN Help-artikel voor meer informatie.


Antwoord 2, Autoriteit 31%

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

Test-PathCheques om te zien of het pad bestaat. Wanneer het dat niet doet, maakt het een nieuwe map.


Antwoord 3, Autoriteit 3%

Het volgende codefragment helpt je om een compleet pad te maken.

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

De bovenstaande functie splitst het pad dat u aan de functie hebt doorgegeven en controleert elke map of deze bestaat of niet. Als het niet bestaat, zal het de respectievelijke map maken totdat de doel-/definitieve map is gemaakt.

Gebruik onderstaande instructie om de functie aan te roepen:

GenerateFolder "H:\Desktop\Nithesh\SrcFolder"

Antwoord 4, autoriteit 2%

Gebruik:

$path = "C:\temp\"
If (!(test-path $path))
{
    md $path
}
  • De eerste regel maakt een variabele met de naam $pathen wijst deze de tekenreekswaarde “C:\temp” toe

  • De tweede regel is een If-instructie die is gebaseerd op de Test-Pathcmdlet om te controleren of de variabele $pathnietbestaat. Het niet bestaat wordt gekwalificeerd met het !symbool.

  • Derde regel: als het pad dat in de bovenstaande tekenreeks is opgeslagen nietwordt gevonden, wordt de code tussen de accolades uitgevoerd.

mdis de korte versie van uittypen: New-Item -ItemType Directory -Path $path

Opmerking: ik heb niet getest met behulp van de -Forceparameter met de onderstaande om te zien of er ongewenst gedrag is als het pad al bestaat.

New-Item -ItemType Directory -Path $path

Antwoord 5, Autoriteit 2%

[System.IO.Directory]::CreateDirectory('full path to directory')

Deze intern controleert naar directory-bestaan, en creëert er een, als er geen map is. Slechts één lijn en inheemse .NET methode werkt perfect.


Antwoord 6, Autoriteit 2%

Ik had exact hetzelfde probleem. Je kunt zoiets gebruiken:

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

Antwoord 7, Autoriteit 2%

Wanneer u de -ForceFlag opgeeft, klagen PowerShell niet als de map al bestaat.

ONE-LINER:

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

BTW, bekijk deze link voor het plannen van de taak: Achtergrondtaken plannen.


Antwoord 8, autoriteit 2%

Er zijn drie manieren die ik ken om een map te maken met PowerShell:

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

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

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


Antwoord 9

Vanuit jouw situatie klinkt het alsof je één keer per dag een map “Revisie#” moet maken met daarin een map “Rapporten”. Als dat het geval is, hoeft u alleen maar te weten wat het volgende revisienummer is. Schrijf een functie die het volgende revisienummer krijgt, Get-NextRevisionNumber. Of je zou zoiets als dit kunnen doen:

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 two 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-installatie.


Antwoord 10

Ik wilde gebruikers gemakkelijk een standaardprofiel voor PowerShell kunnen laten maken om sommige instellingen te negeren, en eindigde met de volgende one-liner (meerdere instructies ja, maar kunnen in PowerShell worden geplakt en tegelijk worden uitgevoerd, wat was het hoofddoel):

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

Voor de leesbaarheid zou ik het als volgt doen in een .ps1-bestand:

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

Antwoord 11

Hier is een eenvoudige die voor mij werkte. Het controleert of het pad bestaat, en als dat niet het geval is, maakt het niet alleen het hoofdpad, maar alle submappen ook:

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

Antwoord 12

$mWarningColor = 'Red'
<#
.SYNOPSIS
    Creates a new directory. 
.DESCRIPTION
    Creates a new directory. If the directory already exists, the directory will
    not be overwritten. Instead a warning message that the directory already
    exists will be output.
.OUTPUT
    If the directory already exists, the directory will not be overwritten.
    Instead a warning message that the directory already exists will be output.
.EXAMPLE    
    Sal-New-Directory -DirectoryPath '.\output'
#>
function Sal-New-Directory {
    param(
        [parameter(mandatory=$true)]
        [String]
        $DirectoryPath
    )
    $ErrorActionPreference = "Stop"
    try {
        if (!(Test-Path -Path $DirectoryPath -PathType Container)) {
            # Sal-New-Directory is not designed to take multiple 
            # directories. However, we use foreach to supress the native output
            # and substitute with a custom message.
            New-Item -Path $DirectoryPath -ItemType Container | `
              foreach {'Created ' + $_.FullName}
        } else {
            Write-Host "$DirectoryPath already exists and" `
                        "so will not be (re)created." `
                        -ForegroundColor $mWarningColor
        }
    } finally {
        $ErrorActionPreference = "Continue"
    }
}

“Sal” is slechts een arbitrair voorvoegsel voor mijn eigen bibliotheek. U kunt het verwijderen of deze vervangen door uw eigen.

Nog een voorbeeld (plaats hier omdat het anderszins ruïneert Syntaxis-markering):

Sal-New-Directory -DirectoryPath ($mCARootDir + "private\")

Other episodes