Steve Hobbs
Steve Hobbs

Reputation: 129

Powershell Variable shows us as command insted of value

When I run this script the result does not get inserted into the database only the command I used to get the result.

If I simply output the variables $Computername and $username to the screen they output correctly

$Computername = 'get-wmiobject -query "select csname from win32_operatingsystem" | select-object     csname | ft -hide'
$username = 'Get-Childitem env:username |select value | ft -hide'
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand 
$SqlInsert = @"

insert into info (computername,username)
Values ('$computername','$username')

"@
$Connection.open() 
$SqlCmd.CommandText = $SqlInsert
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$SqlCmd.Connection = $Connection
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$Connection.Close()

Any Ideas as to how to insert only the variables rather than the commands?

Upvotes: 0

Views: 736

Answers (2)

Nitesh
Nitesh

Reputation: 874

Three Things:

  1. You are passing Strings to $Computername and $username variable, rather than commands. Remove first and last single quote from those variable assignment.

  2. Format-Table Cmdlet is used to better format the output at PowerShell console.

    $Computername = get-wmiobject -query "select csname from win32_operatingsystem" | select-object csname | ft -hide

    Above command gives you a Format object which you can see using

    $computername | Get-Member

    This object is not what you want to insert into your Databse. Instead use -Expandproperty Parameter of Select-object to get the string value.

    $Computername = get-wmiobject -query "select csname from win32_operatingsystem" | select-object -ExpandProperty csname

    $username = Get-Childitem env:username |select -ExpandProperty value

  3. You are missing a SQLConnection object. OR may be use hid it on purpose :)

Upvotes: 1

notjustme
notjustme

Reputation: 2494

Skip the single quotes, like this.

$Computername = get-wmiobject -query "select csname from win32_operatingsystem" | select-object     csname | ft -hide
$username = Get-Childitem env:username |select value | ft -hide

Also, you'll find that your code for getting computername and username is the same as this;

$env:computername
$env:username

Upvotes: 1

Related Questions