我有一个脚本,我想使用PowerShell来bcp
输出数据。我需要启动多个bcp
命令,并希望从文本文件中读取1.表名和2.字段名以填充bcp
命令字符串。
目前这不起作用,但我不确定如何合并2个变量。
文本文件如下所示:
table: table1 table: table2 field: field1 field: field2
# Log file time stamp:
$LogTime = Get-Date -Format "MM-dd-yyyy_hh-mm-ss"
# Log file name:
$LogFile = "C:\Administration\Logs\BCPEXPORTLOG_" + $LogTime + ".log"
$database = "database"
$schema = "dbo"
$table = "TableName"
$tablename = Get-Content 'C:\Administration\Scheduled Tasks\CUBTableList.txt' |
? { $_ -match '^\s*table:\s*' } |
select -First 1 |
% { ($_ -split ':\s*', 2)[1] }
$fieldname = Get-Content 'C:\Administration\Scheduled Tasks\CUBTableList.txt' |
? { $_ -match '^\s*field:\s*' } |
select -First 1 |
% { ($_ -split ':\s*', 2)[1] }
foreach ($line in Get-Content 'C:\Administration\Scheduled Tasks\CUBTableList.txt') {
$bcp_command = "bcp 'SELECT * FROM $database.$schema.$tablename WHERE ($fieldname <= DATEADD(ms, -3, GETDATE()))' QUERYOUT 'D:\BCPOut\$database`_$tablename.txt' -c -U 'user' -P 'password'"
Tee-Object -FilePath $LogFile -InputObject $bcp_command -Append
$bcp_results = Invoke-Expression $bcp_command
Tee-Object -FilePath $LogFile -InputObject $bcp_results -Append
}
我修好了我狡猾的剧本。
使用import-csv代替。
# Log file time stamp:
$LogTime = Get-Date -Format "MM-dd-yyyy_hh-mm-ss"
# Log file name:
$LogFile = "C:\Administration\Logs\BCPEXPORTLOG_"+$LogTime+".log"
$database = "database"
$schema = "dbo"
$table = "TableName"
Import-CSV 'C:\Administration\Scheduled Tasks\CUBList.csv' | ForEach{
$bcp_command = "bcp 'SELECT * FROM $database.$schema." + $_.tablename + " WHERE (" + $_.fieldname + " <= DATEADD(ms, -3, GETDATE()))' QUERYOUT 'D:\BCPOut\$database`_" + $_.tablename + ".txt' -c -U 'user' -P 'password'"
Tee-Object -FilePath $LogFile -InputObject $bcp_command -Append
$bcp_results = Invoke-Expression $bcp_command
Tee-Object -FilePath $LogFile -InputObject $bcp_results -Append
}
试试这段代码:
$LogFile = "c:\temp\BCPEXPORTLOG_{0:MM-dd-yyyy_hh-mm-ss}.log" -f (Get-Date)
$database = "database"
$schema = "dbo"
#split with 'table:'
$Split1=(Get-Content c:\temp\CUBTableList.txt) -split 'table:'
#split fields and take only tablename <>'' and table have field
$Elements=$Split1 | %{
$Split2=$_ -split 'field:'
$table=$Split2[0];
[pscustomobject]@{TableName=$Split2[0].Trim(); Fields=$Split2[1..$($Split2.Length)] | %{$_.Trim()}} | where {$_.TableName -ne '' -and $_.Fields -ne $null}
}
$bcp_command=@()
#build bcp commands
$Elements | %{
$TableName=$_.TableName
$_.Fields | %{
$bcp_command+="bcp 'SELECT * FROM {0}.{1}.{2} WHERE {3} <= DATEADD(ms, -3, GETDATE())' QUERYOUT 'D:\BCPOut\{0}_{2}_{3}.txt' -c -U 'user' -P 'password'" -f $database, $schema, $TableName, $_
}
}
#run commands
$bcp_command | %{
$_ | out-file $LogFile -Append
try
{
$result=Invoke-Expression $_
}
catch
{
$result=$_.Exception.Message
}
finally
{
$result | Out-File $LogFile -Append
}
}