Run a shell command with arguments from a powershell script

I need to extract and save some tables from a remote SQL database using bcp. I would like to write a powershell script to call bcp for each table and save the data. So far I have this script that creates the necessary arguments for bcp. However, I cannot figure out how to pass arguments to bcp. Every time I run the script, it just shows bcp help. It should be something really easy that I don't get.

#commands bcp database.dbo.tablename out c:\temp\users.txt -N -t, -U uname -P pwd -S <servername>
$bcp_path = "C:\Program Files\Microsoft SQL Server\90\Tools\Binn\bcp.exe"
$serverinfo =@{}
$serverinfo.add('table','database.dbo.tablename')
$serverinfo.add('uid','uname')
$serverinfo.add('pwd','pwd')
$serverinfo.add('server','servername')
$out_path= "c:\Temp\db\"
$args = "$($serverinfo['table']) out $($out_path)test.dat -N -t, -U $($serverinfo['uid']) -P $($serverinfo['pwd']) -S $($serverinfo['server'])"

#this is the part I can't figure out
& $bcp_path $args
+3
source share
2 answers

, $args - ; , $args = foo ( , ).

() . , , .

, , . - , $args:

$arguments = "$($serverinfo['table'])",
             'out',"$($out_path)test.dat",
             '-N','-t,',
             '-U',"$($serverinfo['uid'])",
             '-P',"$($serverinfo['pwd'])",
             '-S',"$($serverinfo['server'])"

& $bcp_path $arguments

, , , , :

$out_path = 'c:\Temp\db'
& $bcp_path $serverinfo['table'] out $out_path\test.dat -N '-t,' -U $serverinfo['uid'] -P $serverinfo['pwd'] -S $serverinfo['server']
+5

, , , , , , , , .

PowerShell, , . .cmd cmd.exe, :

echo $("Running command: " + $commandLine);

$rnd = $(([string](Get-Random -Minimum 10000 -Maximum 99999999)) + ".cmd");
$commandFilePath = $(Join-Path -Path $env:TEMP -ChildPath $rnd);
echo $commandLine | Out-File -FilePath $commandFilePath -Encoding ascii;

& cmd.exe /c $commandFilePath

, ASCII, Unicode cmd.exe( ).

+1

Source: https://habr.com/ru/post/1737717/


All Articles