0

I have two below arrays in powershell $obj= ('Sales','Finance','config.ini') $objPath= ('D:\Project','D:\Element','D:\Project')

  1. now $obj can be a folder name or a file name
  2. $objPath is the path where the respective positional $obj will reside

I want to check if that folder or file exist in the respective $objPath

my code:

foreach($element in $obj){
    foreach($elementpath in $objPath){
    Test-Path $element+'\'+$elementpath
    }
}

But it is returning false everytime. Can anyone please suggest where I am doing wrong

2
  • $element+'\'+$elementpath? What are you trying to do? Single-quotes ' prevent variable expansion so if you want to check $element+\$elementpath use double quotes like "$element+\$elementpath". Commented Jun 14, 2020 at 17:07
  • I don't think single quotes are the issue here. I think the code highlighting is wrong in the sample, making it look like the quote wasn't closed. None of the variables are actually quoted. Though an expanding string approach would work, you'll still need to reverse the variables in the expression. I'll updated my answer to include a sample. Commented Jun 14, 2020 at 17:17

1 Answer 1

1

I think you've written the statement backwards. When you run it'll check for paths like:

Sales\D:\Project
Sales\D:\Element
Sales\D:\Project
Finance\D:\Project
Finance\D:\Element
Finance\D:\Project
config.ini\D:\Project
config.ini\D:\Element
config.ini\D:\Project

That obviously doesn't look right. You can try a minor re-write like:

Along with reversing the variable references you may want to entertain using Join-Path (as a best practice) like below:

foreach($element in $obj){
    foreach($elementpath in $objPath){
        Test-Path (Join-Path $elementpath $element)
    }
}

It will work with string concatenation like below:

foreach($element in $obj){
    foreach($elementpath in $objPath){
        Test-Path ($elementpath + '\' + $element)
    }
}

Per one of the comments string expansion will also work:

foreach($element in $obj){
    foreach($elementpath in $objPath){
        Test-Path "$elementpath\$element"
    }
}
Sign up to request clarification or add additional context in comments.

Comments

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.