循环并替换filename(字符串)中的反斜杠

时间:2016-09-22 09:57:19

标签: excel powershell str-replace

我正在尝试替换我从数据库中查询过的文件名中包含的\。我的脚本循环遍历包含项目代码的CSV。对于每个项目代码,将查询数据库并检索项目名称。

但是,项目名称包含我要替换的\

$startRow = 2
$col = 3 

$excel = New-Object -COM Excel.Application
$wb = $excel.Workbooks.Open("\myprojectfolder\projectcodes.csv")

$excel.Visible = $false

for ($i = 1; $i -le $wb.Sheets.Count; $i++){
    $sh = $wb.Sheets.Item($i)
    $endRow = $sh.UsedRange.Rows.Count
    $rangeAddress = $sh.Cells.Item($startRow,$col).Address() + ":" +
                    $sh.Cells.Item($endRow,$col).Address()

    $sh.Range($rangeAddress).Value2 | foreach {
        #GET PROJECT NAME TO APPEND TO FOLDER NAME
        $projectCode = $_

        $Server= "MYSERVER"
        $Database = "MYDATABASE"
        $SQLQuery = $("SELECT [description] FROM [dbo].[projects] WHERE [project] = '$projectCode'")

        $Connection = New-Object System.Data.SQLClient.SQLConnection
        $Connection.ConnectionString = "server='$Server';database='$Database';trusted_connection=true;"
        $Connection.Open()
        $Command = New-Object System.Data.SQLClient.SQLCommand
        $Command.Connection = $Connection
        $Command.CommandText = $SQLQuery
        $Reader = $Command.ExecuteReader()
        while ($Reader.Read()) {
            $projectName = $Reader.GetValue($1)

            #CHECK AND REPLACE '\' CHARACTER IN PROJECTNAME
            if ($projectName -like '*\\*') {
                Write-Debug "PROJECT NAME CONTAINS \"
                $projectName.Replace('\\', '_')
            }

            $folderPath = "\\myfolder\"
            $pathTogether = $folderPath + $projectCode + "_" + $projectName + "\"
            New-Item -Path $pathTogether -Type Directory -force

            #CHECK IF FILE EXISTS IN APPROPRIATE DIRECTORY
            $testFile = $pathTogether + $projectCode + "_" + $projectName + ".xlsm"
            $fileExist = Test-Path $testFile

            if ($fileExist -eq $false) {
                $templateFile = $folderPath + "my_template\my_template.xlsm"

                Copy-Item $templateFile $pathTogether

                $newPath = $pathTogether + "\my_template.xlsm"
                $saveFile = $projectCode + "_" + $projectName + ".xlsm"
                $renameToOLD = $projectCode + "_" + $projectName + "_RENAMED" + ".xlsm"

                #RENAME PROJECT FILE TO HAVE OLD IN FILENAME
                Rename-Item $newPath $saveFile

                $projectxlFile = New-Object -COM Excel.Application

                $projectxlFile.workbooks.open($pathTogether + "\" + $saveFile)
                $queryWS = $projectxlFile.worksheets.Item("Query")
                $queryWS.Cells.Item(8,2) = $projectCode

                $projectxlFile.DisplayAlerts = $False
                $projectxlFile.Visible = $False

                $savePath = $pathTogether + $saveFile

                #Add-Type -AssemblyName Microsoft.Office.Interop.Excel
                #$xlFixedFormat = [Microsoft.Office.Interop.Excel.XlFileFormat]::xlOpenXMLWorkbookMacroEnabled

                $projectxlFile.ActiveWorkbook.Save()
                $projectxlFile.Workbooks.Close()

                $projectxlFile.Quit()
                $ProcID = Get-Process |
                          Where-Object {$_.MainWindowHandle -eq $projectxlFile.HWND} |
                          Select -ExpandProperty ID
                Get-Process -Id $ProcID | Stop-Process -Force
                ##[System.Runtime.Interopservices.Marshal]::ReleaseComObject($projectxlFile)
            }
        }
        $Connection.Close()
    }
}
$excel.Workbooks.Close()
$excel.Quit()
$ProcID2 = Get-Process |
           Where-Object {$_.MainWindowHandle -eq $excel.HWND} |
           Select -ExpandProperty ID
Get-Process -Id $ProcID2 | Stop-Process -Force
###[System.Runtime.Interopservices.Marshal]::ReleaseComObject($excel)

1 个答案:

答案 0 :(得分:1)

$projectName.Replace('\\', '_')

默认情况下,Replace()方法执行常规字符串替换,因此上面只会用下划线替换双反斜杠。此外,它不会就地替换,因此您需要将修改后的字符串分配回变量:

$projectName = $projectName.Replace('\', '_')

-like运算符执行通配符匹配,因此您不能转义该表达式中的反斜杠,否则您甚至无法进行替换操作:

if ($projectName -like '*\*') {
    Write-Debug 'PROJECT NAME CONTAINS \'
    $projectName = $projectName.Replace('\', '_')
}