【问题标题】:Creating a folder if it does not exists - "Item already exists" [duplicate]如果文件夹不存在则创建文件夹-“项目已存在”[重复]
【发布时间】:2013-06-24 03:29:27
【问题描述】:

如果文件夹不存在,我正在尝试使用 PowerShell 创建一个文件夹,所以我这样做了:

$DOCDIR = [Environment]::GetFolderPath("MyDocuments")
$TARGETDIR = "$DOCDIR\MatchedLog"
if(!(Test-Path -Path MatchedLog )){
   New-Item -ItemType directory -Path $DOCDIR\MatchedLog
}

这给了我文件夹已经存在的错误,它确实存在,但它不应该尝试创建它。

我不确定这里有什么问题

New-Item :具有指定名称 C:\Users\l\Documents\MatchedLog 的项目已经存在。在 C:\Users\l\Documents\Powershell\email.ps1:4 char:13 + 新项目

【问题讨论】:

  • 试试这个:New-Item -ItemType Directory -Force -Path C:\Path\That\May\Or\May\Not\Exist

标签: powershell


【解决方案1】:

我什至没有集中注意力,这是怎么做的

$DOCDIR = [Environment]::GetFolderPath("MyDocuments")
$TARGETDIR = '$DOCDIR\MatchedLog'
if(!(Test-Path -Path $TARGETDIR )){
    New-Item -ItemType directory -Path $TARGETDIR
}

【讨论】:

  • $TARGETDIR 的值应该用双引号括起来,单引号内的字符串扩展被禁用,你最终会得到无效的路径
  • 与您尝试创建的文件夹同名的现有文件也不会匹配 Test-Path -Path $TARGETDIR 吗? (考虑添加“-pathType 容器”)
【解决方案2】:

使用 New-Item 可以添加 Force 参数

New-Item -Force -ItemType directory -Path foo

或者ErrorAction参数

New-Item -ErrorAction Ignore -ItemType directory -Path foo

【讨论】:

  • PowerShell 2 不支持 JFI“-ErrorAction Ignore”
  • 另一个问题的答案。
  • 创建没有控制台打印输出的项目:New-Item -Force -ItemType directory -Path D:\yourpath\1 |外空
【解决方案3】:

使用-Not 运算符的替代语法,具体取决于您对可读性的偏好:

if( -Not (Test-Path -Path $TARGETDIR ) )
{
    New-Item -ItemType directory -Path $TARGETDIR
}

【讨论】:

  • 另外,甚至更简单: if (-Not (Get-Item C:\Temp)) { New-Item -ItemType dir "C:\Temp" } 假设您要创建 C:\Temp .
  • '(if((test-path \\$ServersList\d$\install\foldertocopy -eq $false) { New-Item -force -ErrorAction Ignore -ItemType directory -Path \\$ServersList \d$\install\foldertocopy)|out-null'
猜你喜欢
  • 2011-01-19
  • 2018-02-10
  • 2013-09-18
  • 2011-02-19
  • 2017-06-28
  • 2020-07-12
  • 2016-06-26
  • 2013-01-17
相关资源
最近更新 更多