title: Powershell Rename file based on SQL query
body: <p>We take a lot of photograph's for product imagery . I have found a piece of software that will read a Barcode embeded in the image and rename the Image to the Barcode within the image , what i now want to do is rename the File again with the Productid using powershell with an SQL query within , </p>
  
  <pre><code>    declare @$CliRef nvarchar(max)
  set @$CliRef = '5015807416980'
  
  Select   convert(nvarchar(max), productid) as ID FROM products WHERE products.Barcode = @$CliRef
  </code></pre>
  
  <p>I Found a Powershell script online but I must be doing something wrong as its renaming the file blank rather than a productid , I'm really new to Powershell so a little stuck so any help appreciated </p>
  
  <pre><code>    $Database = "training"
  $Server = "ART-WM01"
  
  ##Not sure i need this bit 
  
  function Select-Info($CliRef) 
     {
  
    $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
  $SqlConnection.ConnectionString = "Data Source=$Server;Initial Catalog=$Database;Integrated Security = True"
  $SqlConnection.Open()
  
      $conn.open()
      $query = “Select convert(varchar,producdid )as ID FROM products WHERE barcode = '$CliRef'”
      $cmd = New-Object System.Data.SqlClient.SqlCommand($sql,$conn)
      $cmd.connection = $SqlConnection
      $cmd.commandtext = $query
      $result = $cmd.executenonquery()
      $SqlConnection.Close()
  
      return $query
      }
  
  ## Return ID from Database
   function Return-Info($CliRef)
  {
  
  $SqlConnection = New-Object System.Data.SqlClient.SqlConnection
  $SqlConnection.ConnectionString = "Data Source=$Server;Initial Catalog=$Database;Integrated Security = True"
  $SqlConnection.Open()
  $cmd = New-Object System.Data.SqlClient.SqlCommand
  $cmd.commandtext = “Select convert(varchar, productid) as ID FROM products WHERE barcode = '$CliRef'”
  $cmd.connection = $SqlConnection
  $result = $cmd.ExecuteScalar()
  $SqlConnection.Close()
  
  return $result
  
  }
  
   ## Collect the image names
   $FiNms = Get-ChildItem C:\JJC\Test_Dump -Name
  
   ## Loop through each Image name
   foreach ($FiNm in $FiNms)
  
  {
  
   ## Variable for current File path
   $file = “C:\JJC\Test_Dump\” + $FiNm
   ##  Variable for new File path
   $newFile = “C:\JJC\Test_Dump\renamed” + $FiNm
  
  $ID = Return-Info $FiNm
  
  $ID = $ID + “.tiff”
  
  ##Copy-Item $file -Destination $newFile 
  
  ##Copy-Item $file -Destination = “C:\JJC\\Test_Dump\renamed\”
  Rename-Item $file $ID -force
  
  }
  </code></pre>
  
  <p><a href="https://i.stack.imgur.com/FAoqp.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/FAoqp.png" alt="enter image description here"></a></p>