【问题标题】:Powershell: Openfile dialog and Set-Content Issue. Cannot access file. In usePowershell:打开文件对话框和设置内容问题。无法访问文件。正在使用
【发布时间】:2012-07-10 10:41:08
【问题描述】:

我想要做的是利用 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

【问题讨论】:

    标签: powershell openfiledialog


    【解决方案1】:

    尝试销毁$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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-04-26
      • 2013-07-13
      • 1970-01-01
      • 1970-01-01
      • 2016-11-20
      • 1970-01-01
      相关资源
      最近更新 更多