首页 > 解决方案 > Powershell 脚本停止并且无法按预期工作

问题描述

我编写了一个脚本来获取系统变量和多个文件夹的副本,我想为多个文件夹的副本创建一个目录,以防止文件夹重复,我们需要一个检查条件,所以每次运行脚本时它都不会创建文件夹。像一个例子

     $nfle=New-Item -ItemType "Directory" -Path "D:\Temp\" -Name "foo"
        [bool]$checkfle=Test-Path "D:\Temp\foo" -PathType Any
         if ( $checkfle -eq $True)
    {
      Write-Output "$nfle Exists"
    }
    else
    {
   $bnfle=New-Item -ItemType "Directory" -Path "D:\Temp\" -Name ("boo")
    }
  $cpypste=Copy-Item "D:\Temp\foo" -destination "D:\Temp\boo"
  Write-Host "Succesful Copy of Folders"

因此,当我们运行脚本时,它正在创建文件夹 foo,当我们再次运行脚本时,它显示 foo 存在,并且停止脚本不会进入下一行,甚至不会显示消息。powershell 中有没有办法找到找出脚本停止的原因,或者我应该添加更多信息语句。TIA

标签: debuggingpowershell-5.0

解决方案


最好从 test-path 开始,看看文件夹是否在那里。“容器”是一个文件夹/目录。然后检查是否需要写入文件夹。

 # This should allow your script to continue of error.
 $ErrorActionPreference = "Continue"

 # check if "C:\Temp\Foo" exist. if not make C:\Temp\foo"

 $nfle = 'C:\Temp\foo'

 [bool]$checkfle = Test-Path $nfle -PathType Container
 if ( $checkfle -eq $True)
    {
        Write-Output "$nfle Exists"
    }
 else
    {
        New-Item -ItemType "Directory" -Path "C:\Temp\" -Name "foo"    
    }

# check if "C:\Temp\boo" exist. if not make C:\Temp\boo"

$BooFilePath = "C:\Temp\boo"

[bool]$checkboo = Test-Path $BooFilePath -PathType Container

 if ( $checkboo -eq $True)
    {
        Write-Output " $BooFilePath Exists"
    }
 else
    {
        New-Item -ItemType "Directory" -Path "C:\Temp\" -Name "boo"    
    }

# This makes the folder C:\Temp\boo\foo.
# $cpypste = Copy-Item -Path "C:\Temp\foo\" -destination "C:\Temp\boo\"

# If you want copy the contents of foo into boo you will need * or -recurse
$cpypste = Copy-Item -Path "C:\Temp\foo\*" -destination "C:\Temp\boo\" -PassThru


Write-Host "Succesful Copy of Folders"
$cpypste.FullName

推荐阅读