Reputation: 2301
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?
Upvotes: 6
Views: 12401
Reputation: 31
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')
Upvotes: 0
Reputation: 1618
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
Upvotes: 1
Reputation: 3311
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.
Upvotes: 0
Reputation: 37820
Try changing this:
IF($dir -eq "False")
to this:
IF($dir -eq $false)
Upvotes: 3
Reputation: 52480
You should have:
if ($dir -eq $false)
because the string "False"
is not equal to the boolean value $false
.
Upvotes: 13