Powershell:Openfile对话框和Set-Content Issue。无法访问文件。正在使用

时间:2012-07-10 21:13:39

标签: powershell openfiledialog

我要做的是利用openfile对话框,选择一个ini文件,并使用set-content在此脚本的末尾对其进行行更改。但我不断收到Set-Content的错误:进程无法访问该文件,并且它正在使用中。

$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

1 个答案:

答案 0 :(得分: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