创建目录,如果它不存在。

时间:2021-09-07 16:23:44

I am writing a PowerShell script to create several directories if they do not exist.

我正在编写一个PowerShell脚本来创建多个目录,如果它们不存在的话。

The filesystem looks similar to this

文件系统与此类似。

D:\
D:\TopDirec\SubDirec\Project1\Revision1\Reports\
D:\TopDirec\SubDirec\Project2\Revision1\
D:\TopDirec\SubDirec\Project3\Revision1\
  • Each project folder has multiple revisions.
  • 每个项目文件夹都有多个版本。
  • Each revision folder needs a Reports folder.
  • 每个修订文件夹需要一个报告文件夹。
  • Some of the "revisions" folders already contain a Reports folder; however, most do not.
  • 一些“修订”文件夹已经包含一个报告文件夹;然而,大多数没有。

I need to write a script that runs daily to create these folders for each directory.

我需要编写一个每天运行的脚本,为每个目录创建这些文件夹。

I am able to write the script to create a folder, but creating several folders is problematic.

我可以编写脚本创建一个文件夹,但是创建几个文件夹是有问题的。

10 个解决方案

#1


312  

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.

您可以使用测试路径-PathType容器来检查。

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

有关更多细节,请参见新项目MSDN帮助文章。

#2


58  

$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.

测试路径检查路径是否存在。当它不存在时,它将创建一个新的目录。

#3


11  

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

#4


7  

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

当您指定-Force标志时,PowerShell将不会抱怨该文件夹已经存在。

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.

为了调度任务,请查看此链接:调度后台作业。

#5


6  

There are 3 ways I know to create directory using PowerShell

有3种方法可以使用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"

创建目录,如果它不存在。

#6


3  

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"

#7


2  

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:

从你的情况看来,你需要每天创建一个“修订#”文件夹,里面有一个“报告”文件夹。如果是这样,您只需要知道下一个修订号是什么。编写一个函数,该函数获得下一个修订号Get-NextRevisionNumber。或者你可以这样做:

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

PowerShell 3.0安装

#8


2  

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):

我希望能够轻松地让用户为PowerShell创建一个默认的概要文件,以覆盖一些设置,并以下面的一行程序结束(是的,但是可以将它粘贴到PowerShell中并立即执行,这是主要的目标):

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:

为了便于阅读,下面是我如何在ps1文件中这样做:

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

#9


1  

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}

#10


1  

$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\"

    第一行创建一个名为$path的变量,并将其赋值为“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

    第二行是一个If语句,它依赖于测试路径cmdlet来检查变量$path是否不存在。不存在是合格的使用!象征

  • 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

md是打印的短版本:新项目-ItemType目录-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.

注意:我没有使用下面的-Force参数进行测试,看看如果路径已经存在,是否存在不良行为。

New-Item -ItemType Directory -Path $path

新项目-ItemType目录-Path $path。

#1


312  

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.

您可以使用测试路径-PathType容器来检查。

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

有关更多细节,请参见新项目MSDN帮助文章。

#2


58  

$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.

测试路径检查路径是否存在。当它不存在时,它将创建一个新的目录。

#3


11  

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

#4


7  

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

当您指定-Force标志时,PowerShell将不会抱怨该文件夹已经存在。

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.

为了调度任务,请查看此链接:调度后台作业。

#5


6  

There are 3 ways I know to create directory using PowerShell

有3种方法可以使用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"

创建目录,如果它不存在。

#6


3  

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"

#7


2  

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:

从你的情况看来,你需要每天创建一个“修订#”文件夹,里面有一个“报告”文件夹。如果是这样,您只需要知道下一个修订号是什么。编写一个函数,该函数获得下一个修订号Get-NextRevisionNumber。或者你可以这样做:

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

PowerShell 3.0安装

#8


2  

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):

我希望能够轻松地让用户为PowerShell创建一个默认的概要文件,以覆盖一些设置,并以下面的一行程序结束(是的,但是可以将它粘贴到PowerShell中并立即执行,这是主要的目标):

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:

为了便于阅读,下面是我如何在ps1文件中这样做:

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

#9


1  

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}

#10


1  

$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\"

    第一行创建一个名为$path的变量,并将其赋值为“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

    第二行是一个If语句,它依赖于测试路径cmdlet来检查变量$path是否不存在。不存在是合格的使用!象征

  • 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

md是打印的短版本:新项目-ItemType目录-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.

注意:我没有使用下面的-Force参数进行测试,看看如果路径已经存在,是否存在不良行为。

New-Item -ItemType Directory -Path $path

新项目-ItemType目录-Path $path。