【问题标题】:creating directories, but not doing it how i want it to do创建目录,但没有按照我想要的方式进行
【发布时间】:2015-09-10 00:19:23
【问题描述】:

我创建了一个将创建目录的 powershell 脚本:

function Create-C:Directory{
md C:\DATA
}

function Create-C:DirectoryLOG{
md C:\Log
}

$TestCDrive = Test-Path C:\DATA
IF ($TestCDrive  = "False")
        {Create-C:Directory}
ELSE
        {Write-Host "C Data Directory Exists"}

$TestCDriveLOG = Test-Path C:\Log
IF ($TestCDriveLOG = "False")
        {Create-C:DirectoryLOG}
ELSE
        {Write-Host "C LOG Directory Exists"}

我相信我已经告诉代码,如果测试路径为假,则创建 else write-host。我相信这段代码能按我的预期做吗?

结果: 当我第一次运行时,它会为我创建目录。 但是出于测试目的,当我再次运行它时,我希望它告诉我该目录已经存在,但它给了我一条红色错误消息:

md: An item with the soecified name C:\DATA already exists.

C:\Log 也是如此。我真的不明白如何处理这个问题,我花了很多时间来弄清楚但没有运气。希望有人可以帮忙

【问题讨论】:

  • = 是分配。 -eq 是测试。
  • 是的,我尝试了 -eq 而不是 '=' 不幸的是它仍然是相同的输出。这是完整的错误代码: md : 具有指定名称 C:\DATA 的项目已存在。在 line:2 char:5 + md C:\DATA + ~~~~~~~~~~ + CategoryInfo : ResourceExists: (C:\DATA:String) [New-Item], IOException + FullyQualifiedErrorId : DirectoryExist,Microsoft .PowerShell.Commands.NewItemCommand
  • if (Test-Path C:\DATA) {Create-C:Directory} else {Write-Host "C Data Directory Exists"}?
  • 就我而言,这种临时变量和一次性函数的使用一开始真的很奇怪。
  • 所以只是为了确认。该代码意味着如果测试路径为 True 则执行该函数?我试过了,它会打印语句

标签: powershell powershell-ise


【解决方案1】:

试试这个,你的逻辑有点不对:

function Create-C:DirectoryLOG{
md C:\Log
}

IF (!(Test-Path C:\DATA))
        {Create-C:Directory}
ELSE
        {Write-Host "C Data Directory Exists"}

IF (!(Test-Path C:\log))
        {Create-C:DirectoryLOG}
ELSE
        {Write-Host "C LOG Directory Exists"}

【讨论】:

  • 只是一个问题伙伴。你在 IF 语句中的那个感叹号,它有什么作用?
  • 感叹号与“不”相同。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-11-12
  • 2020-10-25
  • 2015-06-16
  • 1970-01-01
  • 2010-10-27
  • 2011-12-09
  • 1970-01-01
相关资源
最近更新 更多