我在SQL Server中执行查询并返回单列结果集。我需要遍历结果集并找到与结果集中的记录匹配的文件名。部分文件名是序列号。我需要按升序对文件进行排序,选择第一个文件,然后仅将该文件复制到子目录。结果集中的记录如下所示:
MEMBERS.net MEMBERS_COMMENTS1.net MEMBERS_COMMENTS2.net MEMBERS_LANGUAGE.net MEMBERS_COVER_OHC.net MEMBERS_PROBLEM_LIST.net
文件名具有以下结构:
00_1914330_MEMBERS.net
有人可以告诉我为什么这不能达到我的最终结果吗?
add-pssnapin sqlservercmdletsnapin100
add-pssnapin sqlserverprovidersnapin100
cd SQLSERVER:\SQL\LOCALHOST\DEFAULT\Databases\SYSDB\Tables\dbo.STG0_EXPORT_JOBS
$ds = Invoke-Sqlcmd -ServerInstance 'LOCALHOST' -Query "SELECT CASE WHEN SUBSTRING([EXPORT_NAME],1,3) = 'MHC' THEN SUBSTRING([EXPORT_NAME],5,(LEN([EXPORT_NAME])))+'.net' ELSE [EXPORT_NAME]+'.net' END AS export FROM [SYSDB].[dbo].[STG0_EXPORT_JOBS] WHERE [JOB_NAME] = 'MHC_STG0_MEMBERS'"
foreach ($files in $ds) {
$oldestfile = Get-ChildItem C:\Scripts |
where{!$_.PSIsContainer -and $_.Name.EndsWith("$($files.export)")} |
sort-object -property name | select-object -first 1 Name |
Copy-Item "C:\Scripts\" + $oldestfile.substring(7,$oldestfile.length - 8) `
C:\Scripts\MEMBERS
}
以下是我运行时的结果:
Windows PowerShell 版权所有(C)2009 Microsoft Corporation。保留所有权利。
PS H:> C:\ powershell_MoveKoreFiles.ps1 表达式或语句中出现意外的标记'in'。 在C:\ powershell_MoveKoreFiles.ps1:1 char:472 + add-pssnapin sqlserverprovidersnapin100 add-pssnapin sqlservercmdletsnapin100 Set-Location SQLSERVER:\ SQL \ LOCALHOST \ DEFAULT \ Databases \ SYSDB \ Tables \ dbo.STG0_ EXPORT_JOBS $ ds = Invoke-Sqlcmd -Query“选择子集时的情况([EXPORT_NAME], 1,3)='MHC'那么SUBSTRING([EXPORT_NAME],5,(LEN([EXPORT_NAME])))+'。net'ELSE [ EXPORT_NAME] +'。net'END AS export FROM [SYSDB]。[dbo]。[STG0_EXPORT_JOBS] WHERE [ JOB_NAME] ='MHC_STG0_MEMBERS'“ - ServerInstance”LOCALHOST“foreach($ files in <<<< $ ds){$ oldestfile = Get-ChildItem C:\ Scripts | where {!$ .PSIsContainer -and $ .Name.EndsWith(“$($ files.export)”)} | sort-object -property name -descending | se lect-object -first 1 Name | Copy-Item -path“C:\ Scripts \”+ $ oldestfile.substring(7 ,$ oldestfile.length - 8)-destination C:\ Scripts \ MEMBERS} + CategoryInfo:ParserError :( in:String)[],ParseException + FullyQualifiedErrorId:UnexpectedToken
PS H:>
答案 0 :(得分:0)
我认为脚本中可能有太多管道。在Select -first 1 Name之后删除一个,例如:
Add-PSSnapin sqlservercmdletsnapin100
Add-PSSnapin sqlserverprovidersnapin100
cd SQLSERVER:\SQL\LOCALHOST\DEFAULT\Databases\SYSDB\Tables\dbo.STG0_EXPORT_JOBS
$ds = Invoke-Sqlcmd -ServerInstance 'LOCALHOST' -Query "SELECT CASE WHEN " +
"SUBSTRING([EXPORT_NAME],1,3) = 'MHC' THEN " +
"SUBSTRING([EXPORT_NAME],5,(LEN([EXPORT_NAME])))+'.net' " +
"ELSE [EXPORT_NAME]+'.net' END AS export " +
"FROM [SYSDB].[dbo].[STG0_EXPORT_JOBS] " +
"WHERE [JOB_NAME] = 'MHC_STG0_MEMBERS'"
foreach ($files in $ds)
{
$oldestfile = Get-ChildItem C:\Scripts |
Where {!$_.PSIsContainer -and $_.Name.EndsWith("$($files.export)")} |
Sort name | Select Name -First 1
$oldName = "C:\Scripts\$($oldestfile.substring(7,$oldestfile.length - 8))"
Copy-Item $oldName C:\Scripts\MEMBERS
}