社内SEの話

日々起きたことの記録用

【Powershell】Check existence of files in folder

↓プログラミングで副業を考えたらこちら↓

Use Test-Path function for existence check.

An error will occur if the file does not actually exist when copying or moving the file.

If you execute the command after confirming the existence of the file before executing the command, the intended operation will be possible.

learn.microsoft.com

Commands

folder existence check

test-path -path c:\test

-path is optional

Check if there is a folder in the folder

Test-Path C:\test\*

Check if there is a specified extension in the folder

Test-Path C:\test\* -Exclude

the specified extension in the .txt folder Check if there are files other than children

Test-Path C:\test\* -Exclude *.txt

Check if the file is newer than the specified date

current time

$today = get-date

than $today Check if

test-path C:\test\test.txt -NewerThan $today

>False

Check if file is older than specified date

current time

$today = get-date

# Check if the file is older than $today

test-path C:\test\test.txt -OlderThan $today

>True

Check if there is a file newer than the specified date in the folder

# timeget

$today = get-date

# Check if there is a file newer than $today

test-path C:\test\* -NewerThan $today

use case

if(Test-Path C: \test\*){

copy-item C:\test\* C:\test2\*

}