0

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?

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

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 :)

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.