2012-07-10 29 views
1

我想要做的是利用開放文件對話框,選擇一個ini文件,並使用set-content在該腳本的末尾對其進行行更改。但是我不斷收到Set-Content的錯誤:進程無法訪問該文件,並且它正在使用中。Powershell:打開文件對話框和設置內容問題。無法訪問文件。在使用

$a = $env:userprofile 
Function Get-FileName($InitialDirectory) 
{ 
Get-FileName -InitialDirectory "$a\AppData\Roaming\Milliman" 
}#end function Get-FileName 

[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms") | Out-Null 
$dialog = New-Object System.Windows.Forms.OpenFileDialog 
$dialog.DefaultExt = '.*' 
$dialog.Filter = 'All Files|*.*' 
$dialog.FilterIndex = 0 
$dialog.InitialDirectory = $InitialDirectory 
$dialog.Multiselect = $false 
$dialog.RestoreDirectory = $true 
$dialog.Title = "Select a file" 
$dialog.ValidateNames = $true 
$dialog.ShowHelp = $true 
$dialog.ShowDialog() 
$dialog.FileName 


##Folder Dialog 
$dir = new-object -com Shell.Application 
$aldir = $dir.BrowseForFolder(0, "AL Dir", 0, "C:\Program Files\Milliman\") 
if ($aldir.Self.Path -ne "") {write-host "You selected " $aldir.Self.Path} 


## Grid Integration Steps 

Copy-Item -path "\\ap102aric\alfaadmin$\Ver70andAbove\DataSynapse\*" -destination "C:\Program  Files\Common Files\Milliman\MG-ALFA Shared\DataSynapse" -Force 

Copy-Item -path "\\ap102aric\alfaadmin$\Ver70andAbove\JobOptions-RPRic\*" -destination "C:\Program Files\Common Files\Milliman\MG-ALFA Shared\DataSynapse" -Force 

Copy-Item -path "\\ap102aric\alfaadmin$\Ver70andAbove\GSDLL\dsdrv.dll" -Destination $aldir.Self.Path -Force 


## Set Environment Variable 
[Environment]::SetEnvironmentVariable("DSDRIVER_DIR","C:\Program Files\Common Files\Milliman\MG-ALFA Shared\DataSynapse\Config","Machine") 

## Edit Config UI.ini to set SDP LOGON for Datasynapse 
#Write-Host $dialog.FileName 
Get-Content $dialog.FileName | ForEach-Object { 
$_ -replace 'SDPAvailable=*','SDPAvailable=DataSynapse' 
    -replace 'SDPFolder=*','SDPFolder=C:\Program Files\Common Files\Milliman\MG-ALFA Shared\DataSynapse' 
    -replace 'SDPLogon=*','SDPAvailable=Yes' 
} | Set-Content $dialog.FileName 

回答

0

嘗試銷燬$aldir對象。它可能持有該文件的句柄。我不知道該怎麼做。在獲取用戶選擇的路徑後,可能將其設置爲$ null。

您也可以嘗試使用Process Monitor來確定哪個進程正在鎖定文件。

最後,您不能將輸出從Get-Content輸出到Set-Content,例如,

Get-Content $Path | Set-Content $Path 

項目會立即派人下來PowerShell管道,所以當Get-Content讀取一行時,它立即被設置爲Set-Content,這將無法工作,因爲Get-Content打開了該文件。請嘗試保存文件的內容:

$file = Get-Content $path 
# Modify $file 
$file | Set-Content $path