Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 317
Sean Long Avatar asked May 01 '13 19:05

Sean Long


People also ask

How do I run an if statement in PowerShell?

The syntax of If statements in PowerShell is pretty basic and resembles other coding languages. We start by declaring our If statement followed by the condition wrapped in parentheses. Next, we add the statement or command we want to run if the condition is true and wrap it in curly brackets.

What does $() mean in PowerShell?

Subexpression operator $( ) For a single result, returns a scalar. For multiple results, returns an array. Use this when you want to use an expression within another expression. For example, to embed the results of command in a string expression. PowerShell Copy.

What is $_ used for in PowerShell?

$_ is an alias for automatic variable $PSItem (introduced in PowerShell V3. 0; Usage information found here) which represents the current item from the pipe.

Is the NOT operator in PowerShell?

PowerShell supports the following logical operators. Logical AND ( -and ) - TRUE when both statements are TRUE. Logical OR ( -or ) - TRUE when either statement is TRUE. Logical not ( -not ) or ( ! )


1 Answers

You should have:

if ($dir -eq $false) 

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

like image 169
x0n Avatar answered Sep 27 '22 21:09

x0n