# Unable to use Array Item in invoke-sqlcmd

**URL:** <https://forums.powershell.org/t/unable-to-use-array-item-in-invoke-sqlcmd/18902>\
**Category:** PowerShell Help\
**Created:** [March 25, 2022, 2:31am UTC](https://forums.powershell.org/t/unable-to-use-array-item-in-invoke-sqlcmd/18902 "2022-03-25T02:31:30Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![PardhaGanta](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/pardhaganta/32/2227_2.png) [@PardhaGanta](https://forums.powershell.org/u/PardhaGanta)\
**Post date:** [March 25, 2022, 2:31am UTC](https://forums.powershell.org/t/unable-to-use-array-item-in-invoke-sqlcmd/18902/1 "2022-03-25T02:31:30Z")

</div>

I am trying to retrieve records from a sql server table using below query. I do not get any error. I will post both the working and non-working parts of code , so that you could tell me why the non-working code failed ( syntax ?)  
Non-Working code  
$sql=“select \* from tablename where colname=‘$ArrayVar[$index].propertyname’”  
invoke-sqlcmd -query $sql -serverinstance xxx -database xxxx  
Working code  
$var=ArrayVar[$index].propertyname  
$sql=“select \* from tablename where colname=‘$var’”  
invoke-sqlcmd -query $sql -serverinstance xxx -database xxxx

---

<div class="post-metadata">

**Author:** ![Olaf](https://sea1.discourse-cdn.com/flex019/user_avatar/forums.powershell.org/olaf/32/992_2.png) [@Olaf](https://forums.powershell.org/u/Olaf)\
**Post date:** [March 25, 2022, 7:39am UTC](https://forums.powershell.org/t/unable-to-use-array-item-in-invoke-sqlcmd/18902/2 "2022-03-25T07:39:35Z")

</div>

Pardha,  
Welcome to the forum. 👋🏽

When you post code, sample data, console output or error messages please format it as code using the _preformatted text_ button ( **\</\>** ). Simply place your cursor on an empty line, click the button and paste your code.  
Thanks in advance

> [@Welcome to the new PowerShell Forums](https://forums.powershell.org/t/welcome-to-the-new-powershell-forums/7/6):
>
> How to format code in [PowerShell.org](http://PowerShell.org) forums. [Codeformatting\_1]

I’m not sure if it’s a typo or a copy and paste error and you don’t share the relevant code and I’m not familiar with SQL queries but you could try to use the subexpression operator for the variable inside your query string.

```auto
$sql = "select * from tablename where colname='$($ArrayVar[$index].propertyname)'"
invoke-sqlcmd -query $sql -serverinstance xxx -database xxxx

```

---

<div class="post-metadata">

**Author:** ![dotnVo](https://avatars.discourse-cdn.com/v4/letter/d/4af34b/32.png) [@dotnVo](https://forums.powershell.org/u/dotnVo)\
**Post date:** [May 16, 2024, 8:18pm UTC](https://forums.powershell.org/t/unable-to-use-array-item-in-invoke-sqlcmd/18902/3 "2024-05-16T20:18:09Z")

</div>


