【问题标题】:PowerShell: Create and Delete Folders Based on SQL DataSetPowerShell:基于 SQL 数据集创建和删除文件夹
【发布时间】:2010-09-23 19:35:30
【问题描述】:

我正在尝试编写一个 PowerShell 脚本来执行以下操作:

  1. 执行存储过程或运行返回值列表的 t-SQL 命令。
  2. 将步骤 1 中的数据与现有文件目录结构进行比较。
  3. 为步骤 1 中不在现有目录结构中的值创建目录。
  4. 删除现有目录结构中不在步骤 1 中的值的目录。

我已经使用 SSIS 构建了一个类似的过程,但我想尝试将其移动到 PowerShell 脚本中,因为我怀疑它的性能会比我当前的 SSIS 包好得多。我最终自己想通了,代码如下。

如果有人发布一种更快的方法来删除丢失的文件夹,而不必遍历每个文件夹的数据集,那就太好了,但我一直找不到方法。我尝试了 -contains 和 Compare-Object,但我找不到实现目标的方法。

$SqlConnection = New-Object System.Data.SqlClient.SqlConnection
$SqlConnection.ConnectionString = "Server = ServerName; Database = DatabaseName; Integrated Security = True"
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = "SELECT DISTINCT folder = CONVERT(VARCHAR(MAX), id) FROM Some.Table (NOLOCK);"
$SqlCmd.Connection = $SqlConnection
$SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter
$SqlAdapter.SelectCommand = $SqlCmd
$DataSet = New-Object System.Data.DataSet
$SqlAdapter.Fill($DataSet)
$SqlConnection.Close()

$RootDirectory = "\\Some\Root\Directory\Over\There\"

# Delete folders if they shouldn't exist.
$RootDirectoryChildItems = Get-ChildItem $RootDirectory
foreach ($i in $RootDirectoryChildItems)
{
    $Matched = 0
    $TargetDirectory = $RootDirectory + $i.Name

    $DataSetTableRows = $DataSet.Tables[0].Rows
    foreach ($Row in $DataSetTableRows)
    {
        if ($Row.folder -eq $i.Name)
        {
            $Matched = 1
        }
    }

    if ($Matched -eq 0)
    {
        Write-Output 'Deleted folder' $TargetDirectory; Remove-Item $TargetDirectory -Recurse | Out-Null
    }
}

# Create folders if they don't exist.
$DataSetTableRows = $DataSet.Tables[0].Rows
foreach ($Row in $DataSetTableRows)
{  
    $TargetDirectory = $RootDirectory + $Row.folder
    if (!(Test-Path $TargetDirectory))
    {
        Write-Output 'Created folder' $TargetDirectory '.'; New-Item $TargetDirectory -type directory | Out-Null
    }
}

【问题讨论】:

    标签: powershell


    【解决方案1】:

    我可能会根据目录和存储过程结果构建几个集合,并将它们与比较对象进行比较。结果上的“SideIndicator”字段应该告诉您需要做什么。

    【讨论】:

      【解决方案2】:

      我在星期五自己解决了这个问题,并添加了问题的答案。

      【讨论】:

        猜你喜欢
        • 2015-04-05
        • 2021-12-18
        • 2016-11-21
        • 1970-01-01
        • 1970-01-01
        • 2014-05-08
        • 1970-01-01
        • 2018-09-26
        • 1970-01-01
        相关资源
        最近更新 更多