I am running a vsts build inline PowerShell script task to create package for Azure cloud service. It works fine and create package file from my local machine, but when I try to run from VSTS PowerShell inline task it gives error :
##[error]Cannot find path ‘D:\a_tasks\InlinePowershell_31f040e5-e040-4336-878a-59a493355534\1.1.6\ServiceConfiguration.Cloud.Test.cscfg’ because it does not exist.
Here is my PowerShell inline script below, It fails on the following line:
Copy-Item $serviceConfigurationPath $packageOutDir
I really appreciate your help on this.
Thanks,
# This is the VSTS repository path
$workingDirectory = “$/DevCodeBase/ToolDevBranch1.33”
$webProjectName = “WebRole1”
$cloudProjectName = ‘ProjAzureDeployment’
$evv =’Test’
$cppack = ‘C:\Program Files\Microsoft SDKs\Azure\.NET SDK\v2.9\bin\cspack.exe’
$solutionDir = [string]::Format(“{0}”, $workingDirectory)
$webDir = [string]::Format(“{0}\{1}”, $workingDirectory, $webProjectName)
$packageOutDir = [string]::Format(“{0}\{1}”, $workingDirectory, $cloudProjectName)
$rolePropertyFile = [string]::Format(“{0}\{1}\{2}”, $workingDirectory, $cloudProjectName, “roleproperties.txt”)
# Create Role Properties File – This property file specifies the .Net framework against which webrole is going to run.
New-Item $rolePropertyFile -Type file -Force -Value “TargetFrameWorkVersion=v4.5” | Out-Null
New-Item $packageOutDir -Type directory -Force | Out-Null
# CSPack command Definition
$serviceDefinitionPath = [string]::Format(“{0}\{1}\ServiceDefinition.csdef”, $solutionDir, $cloudProjectName)
if ($evv -eq “Test”){
$serviceConfigurationPath = “ServiceConfiguration.Cloud.Test.cscfg”
}
else
{
$serviceConfigurationPath = [string]::Format(“{0}\{1}\ServiceConfiguration.Cloud.cscfg”, $solutionDir, $cloudProjectName)
}
$serviceRole = [string]::Format(“/role:{0};{1}”, $webProjectName, $webDir)
$rolePropertiesFile = [string]::Format(“/rolePropertiesFile:{0};{1}”, $webProjectName, $rolePropertyFile)
$sites = [string]::Format(“/sites:{0};Web;{1}”, $webProjectName, $webDir)
$packageOutput = [string]::Format(“/out:{0}\{1}.cspkg”, $packageOutDir, $cloudProjectName)
# $packageOutput = [string]::Format(“{0}\{1}.cspkg”, $packageOutDir, $cloudProjectName)
Write-Host $packageOutput
Write-Host $serviceConfigurationPath
# Build CSPKG file
& “C:\Program Files\Microsoft SDKs\Azure\.NET SDK\v2.9\bin\cspack.exe” $serviceDefinitionPath $serviceRole $rolePropertiesFile $sites $packageOutput /useCtpPackageFormat | Out-Null
Write-Host $serviceDefinitionPath
Write-Host $serviceRole
Write-Host $rolePropertiesFile
Write-Host $sites
Write-Host $packageOutput
Write-Host ‘before copy’
# Copy configuration file
Copy-Item $serviceConfigurationPath $packageOutDir
# Remove Role Properties File
Remove-Item -Path $rolePropertyFile -Force | Out-Null
In the VSTS task you'll have to specify an absolute path, otherwise the script will look in the temporary directory created for your inline powershell script.
For instance, you could supply the path to the file as a parameter like
-filepath "$(System.DefaultWorkingDirectory)\Solution\config.json"
(For a list of the variables you can use, have a peek here)
If you want to keep using a relative path, you can move to a file based (ie non-inline) script and use a relative path to that.
Related
I'm trying to create a Powershell script that will setup a brand new workspace in a temporary location, do a GetLatest on selected solutions/projects, and download the source code so that I can then trigger further build/versioning operations.
I think I have the script more or less right, but the problem is every time I run this, it tells me there were 0 operations... i.e. I already have the latest versions. This results in nothing at all being downloaded.
Can anyone see what I'm doing wrong?
$subfolder = [System.Guid]::NewGuid().ToString()
$tfsServer = "http://tfsserver:8080/tfs"
$projectsAndWorkspaces = #(
#("$/Client1/Project1","D:\Builds\$subfolder\Client1\Project1"),
#("$/Client1/Project2","D:\Builds\$subfolder\Client1\Project2"),
)
$tfsCollection = [Microsoft.TeamFoundation.Client.TfsTeamProjectCollectionFactory]::GetTeamProjectCollection($tfsServer)
$tfsVersionCtrl = $tfsCollection.GetService([type] "Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer")
$tfsWorkspace = $tfsVersionCtrl.CreateWorkspace($subfolder, $tfsVersionCtrl.AuthorizedUser)
Write-Host "Operations:"
foreach ($projectAndWs in $projectsAndWorkspaces)
{
if (-not(Test-Path $projectAndWs[1]))
{
New-Item -ItemType Directory -Force -Path $projectAndWs[1] | Out-Null
}
$tfsWorkspace.Map($projectAndWs[0], $projectAndWs[1])
$recursion = [Microsoft.TeamFoundation.VersionControl.Client.RecursionType]::Full
$itemSpecFullTeamProj = New-Object Microsoft.TeamFoundation.VersionControl.Client.ItemSpec($projectAndWs[0], $recursion)
$fileRequest = New-Object Microsoft.TeamFoundation.VersionControl.Client.GetRequest($itemSpecFullTeamProj, [Microsoft.TeamFoundation.VersionControl.Client.VersionSpec]::Latest)
$getStatus = $tfsWorkspace.Get($fileRequest, [Microsoft.TeamFoundation.VersionControl.Client.GetOptions]::Overwrite)
Write-Host ("[{0}] {1}" -f $getStatus.NumOperations, ($projectAndWs[0].Substring($projectAndWs[0].LastIndexOf("/") + 1)))
}
Write-Host "Finished"
The $tfsServer = "http://tfsserver:8080/tfs" should be $tfsServer = "http://tfsserver:8080/tfs/nameOfACollection"
The "$/Client1/Project1" string smells. I would add a backtick before the dollar sign so it is not read as a variable or use single quotes.
Backtick
"`$/Client1/Project1"
Single quote
'$/Client1/Project1'
I have a PowerShell script that is intended to modify a web config transform as a pre-build event in a build definition. I've gotten it working for the most part, however when it goes to save the updated file I am getting access denied.
Is there a way to give the right access, without opening a window as this is done via the TFS build agent?
Here is the script:
param(
[string]$buildTarget="Dev",
[string]$projectName="SalesTools"
)
$VerbosePreference = "continue"
Write-Verbose "Params: buildTarget = '$($buildTarget)', projectName = '$($projectName)'"
# Make sure path to source code directory is available
if (-not $Env:TF_BUILD_SOURCESDIRECTORY)
{
Write-Error ("TF_BUILD_SOURCESDIRECTORY environment variable is missing.")
exit 1
}
elseif (-not (Test-Path $Env:TF_BUILD_SOURCESDIRECTORY))
{
Write-Error "TF_BUILD_SOURCESDIRECTORY does not exist: $Env:TF_BUILD_SOURCESDIRECTORY"
exit 1
}
Write-Verbose "TF_BUILD_SOURCESDIRECTORY: $Env:TF_BUILD_SOURCESDIRECTORY"
$webConfig = "$($Env:TF_BUILD_SOURCESDIRECTORY)\$($buildTarget)\SalesTools.Web\$($projectName)\web.$($buildTarget).config"
#$webConfig = "$($Env:TF_BUILD_SOURCESDIRECTORY)\$($buildTarget)\SalesTools.Web\ARCTools\web.$($buildTarget).config"
Write-Verbose "File Path: $($webConfig)"
$doc = (gc $webConfig) -as [xml]
$versionNumber = $doc.SelectSingleNode('//appSettings/add[#key="versionNumber"]/#value').'#text'
Write-Verbose "Current Version Number: $($versionNumber)"
if (($versionNumber))
{
$versionInfo = $versionNumber.Split(".")
$versionIteration = $versionInfo[1]
$minorVersion = $versionInfo[2] -as [int]
$minorVersion = $minorVersion + 1
$currentIteration = Get-Iteration
$newVersionInfo = ("v: 1.$($currentIteration).$($minorVersion)")
}
else
{
Write-Error "Could not get version info from config."
exit 1
}
$doc.SelectSingleNode('//appSettings/add[#key="versionNumber"]/#value').'#text' = $newVersionInfo
$doc.Save($webConfig)
Before you read & update the web.config, try to change the "Read-Only" attribute of web.config file. Because by default, all the source files are "Read-Only".
Add this line before "$doc = ....":
attrib -R $webConfig /S
My build server is doing all the steps necessary to build a zip of the new website. I would like to add a step to checkin zipfile to TFS. I have created a ps1 file to perform the checkin. I am running it in ISE so there is no dependency on having TeamCity. Here are the errors that I am seeing.
No matter how I do workspace.GET, it does not get the latest code
from the server.
Even when I change a file on the hard drive it
does not see changes.
Because no changes are detected the zip is
not checked in to TFS.
Here is the code....
#============================================================================
# Method to check in all zip files
#
# Example of WorkingDir passed in
# "D:\TeamCity\buildAgent\work\281509782e84e723\Powershell"
#
# Example of where freshly created zips live
# "D:\TeamCity\buildAgent\work\281509782e84e723\Zips"
#
# this script is based on
# From https://github.com/mmessano/PowerShell/blob/master/TFSCheckIn.ps1
# From http://stackoverflow.com/questions/25917753/check-a-file-into-tfs-using-powershell
# from http://lennartjansson2.wordpress.com/2011/10/13/setting-tfs-vcs-security-with-ps-2/
#
#============================================================================
function StackOverflow {
Param( [Parameter(Mandatory=$true)][string]$WorkingDir )
Write-BuildLog "Inside StackOverflow"
# Get the direcory where new zips where built
$NewZipFiles = $WorkingDir + "\..\Zips\*"
# This is the url to the TFS server + Project collection
$tfsServer = "YourServerAndCollection";
# this is the full path on server where zips live
# You need to start description with $
$tfsServerPath = "$/MyProject/FullPathToDirwithZips"
# Where on local hard drive should files from TFS be placed
$LocalCkoutDir = "D:\MyLocalHDPath"
# Debug print var to verify correct
Write-BuildLog "NewZipFiles => $NewZipFiles"
Write-BuildLog "tfsServer => $tfsServer"
Write-BuildLog "tfsServerPath => $tfsServerPath"
Write-BuildLog "LocalCkoutDir => $LocalCkoutDir"
# Get the TeamCity build number
#$VarName = "BUILD_NUMBER"
#$TeamCityVersionNbr = (get-item env:$VarName).Value
$TeamCityVersionNbr = "MyProject_03_02_81"
Write-BuildLog "Version Nbr $TeamCityVersionNbr"
$CheckInComment = "Check in zips for $BuildNumber"
# Load the assemblies needed for TFS:
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.Client") | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.VersionControl.Common") | out-null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.TeamFoundation.VersionControl.Client") | out-null
#Set up connection to TFS Server and get version control
$tfs = [Microsoft.TeamFoundation.Client.TeamFoundationServerFactory]::GetServer($tfsServer)
$versionControlType = [Microsoft.TeamFoundation.VersionControl.Client.VersionControlServer]
$versionControlServer = $tfs.GetService($versionControlType)
#check to see if workspace already exists. If it does delete it.
$WorkSpaceNameForCheckIn = "TeamCityWorkspace"
$ThisBoxName = [System.Environment]::MachineName
$test = $versionControlServer.QueryWorkspaces( $WorkSpaceNameForCheckIn, $versionControlServer.AuthenticatedUser, $ThisBoxName )
if ( $test.length -eq 1 )
{
$test[0].Delete()
}
# Generate a workspace
$workspace = $versionControlServer.CreateWorkspace($WorkSpaceNameForCheckIn);
# Map Server path to local path
$workspace.Map($tfsServerPath, $LocalCkoutDir)
# DEBUG: build filename of a zip.
# We will overwrite this file to test the get
$file = "AZipFileThatExists.zip"
$filePath = $LocalCkoutDir + "\" + $file
"hello world" | Out-File $filePath
# I tried the simple get but it does not get
# Get the zip files from the server to local directory
$getstatus = $workspace.Get()
# Csharp way of doing it
#workspace.Map(projectPath, workingDirectory);
# var myItemSpec = new ItemSpec(projectPath, RecursionType.Full);
#GetRequest request = new GetRequest(myItemSpec, VersionSpec.Latest);
#GetStatus status = workspace.Get(request, GetOptions.GetAll | GetOptions.Overwrite); // this line doesn't do anything - no failures or er
# This does not work either
# Powershell checkout the file. Overwrite if file exists. Get even if TFS thinks it is up to date.
$NewItemSpec = New-Object Microsoft.TeamFoundation.VersionControl.Client.ItemSpec ( $tfsServerPath, [Microsoft.TeamFoundation.VersionControl.Client.RecursionType]::Full)
$NewRequest = New-Object Microsoft.TeamFoundation.VersionControl.Client.GetRequest( $NewItemSpec, [Microsoft.TeamFoundation.VersionControl.Client.VersionSpec]::Latest)
$getstatus = $workspace.Get( $NewRequest, [Microsoft.TeamFoundation.VersionControl.Client.GetOptions]::GetAll -bOr [Microsoft.TeamFoundation.VersionControl.Client.GetOptions]::Overwrite )
# I have not tested the rest of this since the "get" does not work.
# Mark the files before we refresh them with new zips
$result = $workspace.PendEdit($LocalCkoutDir)
# Copy zips that where built by TeamCity to checkin direcory
Copy-Item $NewZipFiles $LocalCkoutDir -force -recurse
# check if we have some pending changes. If we do checkin changes
$pendings = $workspace.GetPendingChanges();
if($pendings.Count -gt 0){
$result = $workspace.CheckIn($pendings, $CheckInComment);
Write-BuildLog "Changes where checked in";
}
else
{
Write-BuildLog "No changes found";
}
# delete the workspace
$result = $workspace.Delete()
}
#============================================================================
# Write to the build log
#============================================================================
function Write-BuildLog {
param( [Parameter( Mandatory=$true)] $Message
)
write-host $Message
#write-host "##teamcity[message text='" + $Message + "']"
}
$myDir = Split-Path -Parent $MyInvocation.MyCommand.Path
StackOverflow $myDir
use the tf command line
Example for checkin:
cd C:\TFS\Arquitectura
%ProgramFiles%\Microsoft Visual Studio 9.0\Common7\IDE\TF.exe checkin $/Arquitectura/Main /recursive
On Windows x64
"%ProgramFiles(x86)%\Microsoft Visual Studio 10.0\Common7\IDE\TF.exe" checkin $/Arquitectura/Main /recursive
See for more information on the tf commandline: http://msdn.microsoft.com/en-us/library/z51z7zy0(v=VS.90).aspx
Only learning curve about use tf.exe with Powershell. Maybe source code sample is required.
Source: Scripting TFS Command Line for Get Latest Version, Check Out and Check in, programmatically
I am trying to write a PowerShell script that automatically deletes empty directories on our FTP server. I don't have any direct access to the server on which the directories reside - I can only access them via FTP. For this reason, I have written a PowerShell script that uses WinSCP .NET assembly to (try to) delete the empty directories. However, I have a problem, in that many of the directories on the server have square brackets in the directory name.
For example, the directory name might be called: [a]153432
There are lots of these directories, hence my desire to write a script to delete them. This occurs because they've been created by a program that uses a number to create the directories it requires. In order to work on this program, I created an empty directory
/latest/[b]test
My program goes like this:
# program to test deletion of directories with square-brackets in the name.
$HOSTNAME="myftpservername"
$USERNAME="myftpusername"
$PASSWORD="myftppassword"
$DLL_LOCATION="C:\Program Files (x86)\WinSCP\WinSCPnet.dll"
$LOCAL_DIRECTORY="C:\testdir\extended\baseroot"
# Load WinSCP .NET assembly
[Reflection.Assembly]::LoadFrom($DLL_LOCATION) | Out-Null
# Session.FileTransferred event handler
try
{
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.Protocol = [WinSCP.Protocol]::ftp
$sessionOptions.HostName = $HOSTNAME
$sessionOptions.UserName = $USERNAME
$sessionOptions.Password = $PASSWORD
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
$remoteFileWithUnixPath = "/latest/[b]test"
$removalResult = $session.RemoveFiles($remoteFileWithUnixPath)
if ($removalResult.IsSuccess)
{
Write-Host ("Removal of remote file {0} succeeded" -f $remoteFileWithUnixPath)
}
else
{
Write-Host ("Removal of remote file {0} failed" -f $remoteFileWithUnixPath)
}
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
exit 0
}
catch [Exception]
{
Write-Host $_.Exception.Message
exit 1
}
When I run it, it displays the following message:
PS C:\Users\dbuddrige\Documents\dps> .\delete-squarebracket-dir.ps1
Removal of remote file /latest/[b]test succeeded
However, the directory is not deleted.
I have also tried specifying the directory name with delimiters such as:
$remoteFileWithUnixPath = "/latest/\[b\]test"
But this also fails (but at least it says so):
PS C:\Users\dbuddrige\Documents\dps> .\delete-squarebracket-dir.ps1
Removal of remote file /latest/\[b\]test failed
BUT, if I change the directory name [and the variable $remoteFileWithUnixPath] to something like
/latest/foo
And then re-run the program, it deletes the directory /latest/foo just fine.
Does anyone have any ideas what I need to do to get this to work?
The answer to this question was pointed out by Martin Prikryl [Thanks!]
The fully working code follows:
# program to test deletion of directories with square-brackets in the name.
$HOSTNAME="myftpservername"
$USERNAME="myftpusername"
$PASSWORD="myftppassword"
$DLL_LOCATION="C:\Program Files (x86)\WinSCP\WinSCPnet.dll"
$LOCAL_DIRECTORY="C:\testdir\extended\baseroot"
# Load WinSCP .NET assembly
[Reflection.Assembly]::LoadFrom($DLL_LOCATION) | Out-Null
# Session.FileTransferred event handler
try
{
$sessionOptions = New-Object WinSCP.SessionOptions
$sessionOptions.Protocol = [WinSCP.Protocol]::ftp
$sessionOptions.HostName = $HOSTNAME
$sessionOptions.UserName = $USERNAME
$sessionOptions.Password = $PASSWORD
$session = New-Object WinSCP.Session
try
{
# Connect
$session.Open($sessionOptions)
$remoteFileWithUnixPath = "/latest/[b]test"
$removalResult =
$session.RemoveFiles($session.EscapeFileMask($remoteFileWithUnixPath))
if ($removalResult.IsSuccess)
{
Write-Host ("Removal of remote file {0} succeeded" -f $remoteFileWithUnixPath)
}
else
{
Write-Host ("Removal of remote file {0} failed" -f $remoteFileWithUnixPath)
}
}
finally
{
# Disconnect, clean up
$session.Dispose()
}
exit 0
}
catch [Exception]
{
Write-Host $_.Exception.Message
exit 1
}
Some methods of the WinSCP .NET assembly, including the the Session.RemoveFiles, accept a file mask, not a simple path.
Square brackets have special meaning in the file mask.
You should always use the RemotePath.EscapeFileMask method on file paths, before passing them to assembly methods.
I'd use the escape sequence in the commandline:
Remove-Item 'C:\Scripts\Test`[1`].txt'
Or use the -LiteralPath parameter.
Remove-Item -LiteralPath C:\scripts\test[1].txt
The -LiteralPath parameter does not try to convert the string.
Using in PowerShell, how can I check if an application is locking a file?
I like to check which process/application is using the file, so that I can close it.
You can do this with the SysInternals tool handle.exe. Try something like this:
PS> $handleOut = handle
PS> foreach ($line in $handleOut) {
if ($line -match '\S+\spid:') {
$exe = $line
}
elseif ($line -match 'C:\\Windows\\Fonts\\segoeui\.ttf') {
"$exe - $line"
}
}
MSASCui.exe pid: 5608 ACME\hillr - 568: File (---) C:\Windows\Fonts\segoeui.ttf
...
This could help you: Use PowerShell to find out which process locks a file. It parses the System.Diagnostics.ProcessModuleCollection Modules property of each process and it looks for the file path of the locked file:
$lockedFile="C:\Windows\System32\wshtcpip.dll"
Get-Process | foreach{$processVar = $_;$_.Modules | foreach{if($_.FileName -eq $lockedFile){$processVar.Name + " PID:" + $processVar.id}}}
You should be able to use the openfiles command from either the regular command line or from PowerShell.
The openfiles built-in tool can be used for file shares or for local files. For local files, you must turn on the tool and restart the machine (again, just for first time use). I believe the command to turn this feature on is:
openfiles /local on
For example (works on Windows Vista x64):
openfiles /query | find "chrome.exe"
That successfully returns file handles associated with Chrome. You can also pass in a file name to see the process currently accessing that file.
You can find a solution using Sysinternal's Handle utility.
I had to modify the code (slightly) to work with PowerShell 2.0:
#/* http://jdhitsolutions.com/blog/powershell/3744/friday-fun-find-file-locking-process-with-powershell/ */
Function Get-LockingProcess {
[cmdletbinding()]
Param(
[Parameter(Position=0, Mandatory=$True,
HelpMessage="What is the path or filename? You can enter a partial name without wildcards")]
[Alias("name")]
[ValidateNotNullorEmpty()]
[string]$Path
)
# Define the path to Handle.exe
# //$Handle = "G:\Sysinternals\handle.exe"
$Handle = "C:\tmp\handle.exe"
# //[regex]$matchPattern = "(?<Name>\w+\.\w+)\s+pid:\s+(?<PID>\b(\d+)\b)\s+type:\s+(?<Type>\w+)\s+\w+:\s+(?<Path>.*)"
# //[regex]$matchPattern = "(?<Name>\w+\.\w+)\s+pid:\s+(?<PID>\d+)\s+type:\s+(?<Type>\w+)\s+\w+:\s+(?<Path>.*)"
# (?m) for multiline matching.
# It must be . (not \.) for user group.
[regex]$matchPattern = "(?m)^(?<Name>\w+\.\w+)\s+pid:\s+(?<PID>\d+)\s+type:\s+(?<Type>\w+)\s+(?<User>.+)\s+\w+:\s+(?<Path>.*)$"
# skip processing banner
$data = &$handle -u $path -nobanner
# join output for multi-line matching
$data = $data -join "`n"
$MyMatches = $matchPattern.Matches( $data )
# //if ($MyMatches.value) {
if ($MyMatches.count) {
$MyMatches | foreach {
[pscustomobject]#{
FullName = $_.groups["Name"].value
Name = $_.groups["Name"].value.split(".")[0]
ID = $_.groups["PID"].value
Type = $_.groups["Type"].value
User = $_.groups["User"].value.trim()
Path = $_.groups["Path"].value
toString = "pid: $($_.groups["PID"].value), user: $($_.groups["User"].value), image: $($_.groups["Name"].value)"
} #hashtable
} #foreach
} #if data
else {
Write-Warning "No matching handles found"
}
} #end function
Example:
PS C:\tmp> . .\Get-LockingProcess.ps1
PS C:\tmp> Get-LockingProcess C:\tmp\foo.txt
Name Value
---- -----
ID 2140
FullName WINWORD.EXE
toString pid: 2140, user: J17\Administrator, image: WINWORD.EXE
Path C:\tmp\foo.txt
Type File
User J17\Administrator
Name WINWORD
PS C:\tmp>
I was looking for a solution to this as well and hit some hiccups.
Didn't want to use an external app
Open Files requires the local ON attribute which meant systems had to be configured to use it before execution.
After extensive searching I found.
https://github.com/pldmgg/misc-powershell/blob/master/MyFunctions/PowerShellCore_Compatible/Get-FileLockProcess.ps1
Thanks to Paul DiMaggio
This seems to be pure powershell and .net / C#
You can find for your path on handle.exe.
I've used PowerShell but you can do with another command line tool.
With administrative privileges:
handle.exe -a | Select-String "<INSERT_PATH_PART>" -context 0,100
Down the lines and search for "Thread: ...", you should see there the name of the process using your path.
Posted a PowerShell module in PsGallery to discover & kill processes that have open handles to a file or folder.
It exposes functions to: 1) find the locking process, and 2) kill the locking process.
The module automatically downloads handle.exe on first usage.
Find-LockingProcess()
Retrieves process information that has a file handle open to the specified path.
Example: Find-LockingProcess -Path $Env:LOCALAPPDATA
Example: Find-LockingProcess -Path $Env:LOCALAPPDATA | Get-Process
Stop-LockingProcess()
Kills all processes that have a file handle open to the specified path.
Example: Stop-LockingProcess -Path $Home\Documents
PsGallery Link: https://www.powershellgallery.com/packages/LockingProcessKiller
To install run:
Install-Module -Name LockingProcessKiller
I like what the command prompt (CMD) has, and it can be used in PowerShell as well:
tasklist /m <dllName>
Just note that you can't enter the full path of the DLL file. Just the name is good enough.
I've seen a nice solution at Locked file detection that uses only PowerShell and .NET framework classes:
function TestFileLock {
## Attempts to open a file and trap the resulting error if the file is already open/locked
param ([string]$filePath )
$filelocked = $false
$fileInfo = New-Object System.IO.FileInfo $filePath
trap {
Set-Variable -name filelocked -value $true -scope 1
continue
}
$fileStream = $fileInfo.Open( [System.IO.FileMode]::OpenOrCreate,[System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None )
if ($fileStream) {
$fileStream.Close()
}
$obj = New-Object Object
$obj | Add-Member Noteproperty FilePath -value $filePath
$obj | Add-Member Noteproperty IsLocked -value $filelocked
$obj
}
If you modify the above function slightly like below it will return True or False
(you will need to execute with full admin rights)
e.g. Usage:
PS> TestFileLock "c:\pagefile.sys"
function TestFileLock {
## Attempts to open a file and trap the resulting error if the file is already open/locked
param ([string]$filePath )
$filelocked = $false
$fileInfo = New-Object System.IO.FileInfo $filePath
trap {
Set-Variable -name Filelocked -value $true -scope 1
continue
}
$fileStream = $fileInfo.Open( [System.IO.FileMode]::OpenOrCreate, [System.IO.FileAccess]::ReadWrite, [System.IO.FileShare]::None )
if ($fileStream) {
$fileStream.Close()
}
$filelocked
}