Reputation: 129
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
Reputation: 874
Three Things:
You are passing Strings to $Computername and $username variable, rather than commands. Remove first and last single quote from those variable assignment.
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
You are missing a SQLConnection object. OR may be use hid it on purpose :)
Upvotes: 1
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