0

I am new to PowerShell from .Net world. I am trying to write some if statement like the blow

#1

if (((Get-Item $pf).Exist))
{
     $password = [xml]( Get-Content $pf)
}

#2

if (((Get-Item $pf) | Select-Object Exist))
{
     $password = [xml]( Get-Content $pf)
}

#3

$result=(Get-Item $pf).Exist
if($result)
{
     $password = [xml]( Get-Content $pf)
}

Questions: Both #2 and #3 will work as expected, however, I am also expecting #1 to work as in .Net, but it seems always evaluate to false, so the statement never get executed. I am a little confused here, can someone explain me why #1 is not working as what I would expect?

1 Answer 1

4

They are all wrong. It's Exists, not Exist.

Also I think you are up for disappointment, when you test your code when the file does NOT exist.

I think what you are looking for is

Test-Path $pf
Sign up to request clarification or add additional context in comments.

3 Comments

Since he wants to get the contents of the item, you could also verify that it is a file. It's as simple as including -PathType Leaf.
Sorry, it's my typo, I means Exists actually, I used autocomplete in the console, but just typed this in the post by myself, so I missed the s at the end. I actually ended up using Test-Path to do my job. However, it's just my wish to understand better why the #1 doesn't work as expected, as clearly I am with some wrong assumption from .Net world.
@JackyYuan You've done more errors when you typed, and I have no way of telling which those are. "Both #2 and #3 will work as expected, however, I am also expecting #1 to work as in .Net, but it seems always evaluate to false". This is not the case with the examples you are given, when you change Exist to Exists. Simply speaking I cannot reproduce your results. It's really hard getting a question answered when you get the crucial part of the question wrong. I would advise to spend more time on getting the questions exactly right, before posting them.

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.