2016-09-22 118 views
0

我試圖替換包含在我從數據庫查詢的文件名中包含的\。我的腳本通過包含項目代碼的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) 
+0

你會得到什麼錯誤? –

+0

請不要修復您的問題中的代碼。它可以使答案失效,並使人們難以解決您的原始問題。 – Matt

回答

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

默認情況下,Replace()方法不正規的字符串替換,所以上面只會替換用下劃線雙反斜槓。此外,它不就地更換,所以你需要修改字符串分配回變量:

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

-like操作者通配符匹配,所以你不能逃脫在表達式中的反斜槓要麼,否則你甚至不會去更換操作:

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

Hi Ansgar,謝謝你的回覆。我剛剛嘗試過,但仍然無效。 – user3565164

+0

@ user3565164查看更新後的答案。 –

+0

嗨Ansgar,剛剛嘗試過你的答案,仍然沒有發生抱歉!基本上projectName會包含像'project \ subproject'這樣想改成'project_subproject' – user3565164

相關問題