Create directory if it does not exist

倾然丶 夕夏残阳落幕 提交于 2019-11-28 03:07:10
Andy Arismendi

Have you tried the -Force parameter?

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

You can use Test-Path -PathType Container to check first.

See the New-Item MSDN help article for more details.

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

Test-Path checks to see if the path exists. When it does not, it will create a new directory.

pykimera

I had the exact same problem. You can use something like this:

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

When you specify the -Force flag, PowerShell will not complain if the folder already exists.

One-liner:

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

BTW, for scheduling the task please check out this link: Scheduling Background Jobs.

There are 3 ways I know to create directory using 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"

The following code snippet helps you to create complete path.

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

Above function split the path you passed to the function, and will check each folder whether it has existed or not. If it is not existed it will create the respective folder until the target/final folder created.

To call the function, use below statement:

GenerateFolder "H:\Desktop\Nithesh\SrcFolder"

From your situation is sounds like you need to create a "Revision#" folder once a day with a "Reports" folder in there. If that's the case, you just need to know what the next revision number is. Write a function that gets the next revision number Get-NextRevisionNumber. Or you could do something like this:

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

Johny Skovdal

I wanted to be able to easily let users create a default profile for PowerShell to override some settings, and ended up with the following one-liner (multiple statements yes, but can be pasted into PowerShell and executed at once, which was the main goal):

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

For readability, here's how I would do it in a ps1 file instead:

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

Here's a simple one that worked for me. It checks whether the path exists, and if it doesn't, it will create not only the root path, but all sub-directories also:

$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\}
  • First line creates a variable named $path and assigns it the string value of "C:\temp\"

  • Second line is an If statement which relies on Test-Path cmdlet to check if the variable $path does NOT exist. The not exists is qualified using the ! symbol

  • Third Line: IF the path stored in the string above is NOT found, the code between the curly brackets will be run

md is the short version of typing out: New-Item -ItemType Directory -Path $path

Note: I have not tested using the -Force parameter with the below to see if there is undesirable behavior if the path already exists.

New-Item -ItemType Directory -Path $path

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!