简体   繁体   中英

IF Statement not working in Powershell

I've been trying to get an IF-ELSE clause to work within my little powershell v2 script, and I think I'm having some problems with my parsing. Here's the code I have currently:

$dir = test-path C:\Perflogs\TestFolder 

IF($dir -eq "False") 
{
New-Item C:\Perflogs\TestFolder -type directory
get-counter -counter $p -Continuous | Export-Counter  C:\PerfLogs\TestFolder\Client_log.csv -Force -FileFormat CSV -Circular -MaxSize $1GBInBytes
}
Else
{
get-counter -counter $p -Continuous | Export-Counter  C:\PerfLogs\TestFolder\Client_log.csv -Force -FileFormat CSV -Circular -MaxSize $1GBInBytes
}

So basically I want it to establish the $dir variable as testing to see if the path I want exists. If it doesn't, it should create that folder and run the counters. If it does, it should not create the folder but should still run counters.

I've got $p defined elsewhere, and the get-counters statement works fine. Right now, whether the folder exists or not I'm getting an error about new-item not working.

Am I using the wrong operator for -eq after doing that test?

You should have:

if ($dir -eq $false) 

because the string "False" is not equal to the boolean value $false .

Try changing this:

IF($dir -eq "False") 

to this:

IF($dir -eq $false) 

x0n already answered, so I wont repeat that, but I noticed another "Gotcha" you should be aware of.

Your code is trying to test for the existence of a directory "TestFolder", however you test-path command is not restricted to checking only for directories. Meaning, if you actually happen to have a file by the same name "TestFolder" it will still return true.

To be more careful, you should add the "-PathType Container" switch so that it will fail if there is a file by that name and only pass if there is a directory by that name.

$dir = test-path C:\\Perflogs\\TestFolder -PathType Container

In addition to the other answers about $false , I've had syntax issues with v3. Specifically

if($dir -eq $false)
{

didn't work.

if($dir -eq $false){

did work. YMMV, but you've been warned.

It might work If($? -ne 0)

if the given condition is false, which is defined in earlier variables(This is not for the above question)

If($dir -contains 'False')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM