tags:

views:

618

answers:

2

Completely newbie simple powershell question I am trying to do the following - for each *.sql file in the current directory run

sqlplus username/password@connect_identifier_specified_in_argument @file_name

Here is what I have so far:

$scripts = dir *.sql
foreach($script in $scripts) {
    write-host sqlplus username/password"@"$args "@"$script.Name
}

(I know write-host outputs it to the screen, I'm just trying to debug for now)

However, there is something funky with how powershell treats the @ character and when I run this I always get something like

PS C:\code\scripts> C:\utils\run_sql_scripts_on.ps1 identifier
sqlplus username/password@identifier @ ALERTS.sql

See that space after the "@"? What gives?

+5  A: 

Escape the @ with a backtick (`).

write-host sqlplus username/password`@$args `@$script.Name
aphoria
What do the ` and @ symbols actually do?
George Mauer
The backtick is the escape character in PowerShell. The @ can be used in PS to create empty arrays, for example $a = @(). In this case, I don't think the @ was the problem, but rather the double-quotes. Replace the @'s with a letter and you'll still see the extra space. I think Write-Host automatically puts a space after a double-quoted string.
aphoria
The problem is that PowerShell saw "@" and $script.home as two separate arguments because the second is an expression and Write-Host joins all arguments with a space.
JasonMArcher
+2  A: 

PowerShell Community Extensions has a handy little utility (echoargs) for debugging this sort of problem:

5>echoargs username/password"@"$args "@"$script.Name
Arg 0 is <username/password@>
Arg 1 is <@>
Arg 2 is <test.txt>

Try escaping with a backtick:

6>echoargs "username/password`@$args" "`@$($script.Name)"
Arg 0 is <username/password@>
Arg 1 is <@test.txt>
Keith Hill