2

I want to check a file exist or not in the folder, if exist it will create a new folder. I tried my code, but Its not working. I can not create a new folder, but I already make sure that I have the file that I check.

$WKFD = "$b-$timestamp"
$Path_2 = "C:\Users\Documents\Convert\$WKFD"

if([System.IO.File]::Exists("$Path_2\t.txt")-ne $true)
{
    New-Item -ItemType Directory -Force -Path $Path_2+2
}
1
  • New-Item with -Force creates the folder if it doesn't exists, no need of if statement. Commented Jun 12, 2019 at 8:38

5 Answers 5

4

As an example to test if a given item exist you can check for the path.

if(Test-Path 'C:\Program Files\JetBrains\PyCharm Community Edition 
   2018.3.5\bin\pycharm.exe'){
    New-Item -ItemType Directory -Force -Path $yourPath
}

Hope it helps! BR

Sign up to request clarification or add additional context in comments.

Comments

2

Use this to check if the folder exists:

$folderName = "something"
$path = "C:\Users\user\Desktop\" + $folderName

if (Test-Path -Path $path){
    #Folder exists, check for existance of file
}else{
    #Folder doesn't exist, create it
    New-Item -ItemType Directory -Path $path
}

Comments

1

New-Item with -Force creates the folder if it doesn't exists, no need of if statement. If you want to check, use Test-Path to check the folder availability.

$WKFD = "$b-$timestamp"
$Path_2 = "C:\Users\Documents\Convert\$WKFD"

if(Test-Path -Path "$Path_2\t.txt"){
    New-Item -ItemType Directory -Force -Path $NewFolder
}

What do you meant by $Path_2+2 ?

Comments

1

You can use the following:

If file test1.txt exists then a folder named newDir is created, else no action is performed.

if(Test-Path C:\Users\Username\Desktop\test\test1.txt -PathType Leaf)
{
    Write-Output "File exists"
    New-Item -ItemType directory -Path C:\Users\Username\Desktop\test\newDir
}
else {
    Write-Output "File does not exist"
}

Comments

0

You can Use

Test-Path 'pathToFile/FileName'

It returns True or False depending on whether the file exits or not

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.