Establishing a Connection
With the CData Cmdlets users can install a data module, set the connection properties, and start scripting. This section provides examples of using our xBase Cmdlets with native PowerShell cmdlets, like the CSV import and export cmdlets.
Installing and Connecting
If you have PSGet, installing the cmdlets can be accomplished from the PowerShell Gallery with the following command. You can also obtain a setup from the CData site.
Install-Module xBaseCmdlets
The following line is then added to your profile, loading the cmdlets on the next session:
Import-Module xBaseCmdlets;
You can then use the Connect-xBase cmdlet to create a connection object that can be passed to other cmdlets:
$conn = Connect-xBase -DataSource 'C:\\MyData'
The DataSource property must be set to the name of the folder that contains the .dbf files. Specify the IncludeFiles property to work with xBase table files having extensions that differ from .dbf. Specify multiple extensions in a comma-separated list. Specify the CodePage property to set correct encoding for text fields in .dbf tables.
Retrieving Data
The Select-xBase cmdlet provides a native PowerShell interface for retrieving data:
$results = Select-xBase -Connection $conn -Table "Orders" -Columns @("ShipName, ShipCity") -Where "ShipCountry='USA'"The Invoke-xBase cmdlet provides an SQL interface. This cmdlet can be used to execute an SQL query via the Query parameter.
Piping Cmdlet Output
The cmdlets return row objects to the pipeline one row at a time. The following line exports results to a CSV file:
Select-xBase -Connection $conn -Table Orders -Where "ShipCountry = 'USA'" | Select -Property * -ExcludeProperty Connection,Table,Columns | Export-Csv -Path c:\myOrdersData.csv -NoTypeInformation
You will notice that we piped the results from Select-xBase into a Select-Object cmdlet and excluded some properties before piping them into an Export-CSV cmdlet. We do this because the CData Cmdlets append Connection, Table, and Columns information onto each row object in the result set, and we do not necessarily want that information in our CSV file.
However, this makes it easy to pipe the output of one cmdlet to another. The following is an example of converting a result set to JSON:
PS C:\> $conn = Connect-xBase -DataSource 'C:\\MyData' PS C:\> $row = Select-xBase -Connection $conn -Table "Orders" -Columns (ShipName, ShipCity) -Where "ShipCountry = 'USA'" | select -first 1 PS C:\> $row | ConvertTo-Json { "Connection": { }, "Table": "Orders", "Columns": [ ], "ShipName": "MyShipName", "ShipCity": "MyShipCity" }