aditya pratti
aditya pratti

Reputation: 35

Powershell script halting and not working as expected

I have written a script to get system variables and copy of several folders ,I wanted to create a directory for copy of several folders,to prevent duplication of folders we wanted a check condition so each time we run the script it is not creating folders. Like an example

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

So when we run the script it is creating folder foo,again when we run the script , it is displaying foo exists, and stopping the script is not going to next line, not even displaying the message.Is there a way in powershell to find out why the script is stopping or shall i add more information statements. TIA

Upvotes: 0

Views: 43

Answers (2)

Aaron
Aaron

Reputation: 573

It best to start with test-path to see if the folder is there. A "Container" is a folder/directory. Then check if you need to write the folder.

 # 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

Upvotes: 1

Ivan Mirchev
Ivan Mirchev

Reputation: 839

I have tried the demo provided and it works from my side, multiple times, so I was not able to re-create the problem.

If you would like to debug scripts in PowwerShell, you may follow this link: https://learn.microsoft.com/en-us/powershell/scripting/components/ise/how-to-debug-scripts-in-windows-powershell-ise?view=powershell-6

I am not sure, why you are storing the result of Copy-Item into a variable, as it is null?

Hope it helps!

Upvotes: 0

Related Questions