Home > Back-end >  Powershell DataTable,Select Filter does not accept single quote character
Powershell DataTable,Select Filter does not accept single quote character

Time:01-08

I'm writing a simple Name search against a datatable using Powershell. The code as following:

    $filter = "Name = '$aContact'"
    $arow = $dt_resources.Select($filter)

This works all fine except if $aContact contains a single quote (') character, like "O'Connor".

Any ideal how can I workaround this issue?

Thanks all in advance.

CodePudding user response:

Mathias R. Jessen already commented on the solution to the question but to put it as an answer, you can escape the ' by doubling them. I added a simple function that will also serve as workaround for possible $null input since both methods (.Contains and .Replace) would throw an exception in that case.

$dtt = [System.Data.DataTable]::new()
'Name', 'Value' | ForEach-Object{
    $dtt.Columns.Add([System.Data.DataColumn]::new($_))
}
$row = $dtt.NewRow()
$row.Name = "O'Connor"
$row.Value = [random]::new().Next()
$dtt.Rows.Add($row)
$row = $dtt.NewRow()
$row.Name = "Doe"
$row.Value = [random]::new().Next()
$dtt.Rows.Add($row)

function CheckQuery {
param(
    [parameter(ValueFromPipeline)]
    [string]$Value
)
    if($Value.Contains("'")) { return $Value.Replace("'","''") }
    return $Value
}

"O'Connor", "Doe", $null | ForEach-Object {
    $filter = "Name = '{0}'" -f ($_ | CheckQuery)
    $dtt.Select($filter)
}
  •  Tags:  
  • Related