So I've been trying to figure out how to get a BAT file to identify the directory it's in and assign that to a variable. I've been able to get it to work as a PS1, but a PS1 requires an extra click (right-click -> "Run in Powershell"), where a BAT you can just double-click on and have it run.
This is what my BAT file looks like now (yes, I know this looks like PowerShell commands but it's contained within a BAT file):
@PowerShell.exe -ExecutionPolicy RemoteSigned -Command "Invoke-Expression -Command ((Get-Content -Path '%~f0' | Select-Object -Skip 2) -join [environment]::NewLine)"
@exit /b %Errorlevel%
Write-Host "OPERATION: Purge BMPs from Specified Folders";
$sourceDir = "U:\SOMEFOLDER\"
Get-ChildItem -Recurse -LiteralPath $sourceDir -Filter Clear_BMPs.ps1 |
ForEach-Object { & $_.FullName }
What this does is it looks through the folder that's hardcoded as $sourceDir and executes the PS1 scripts wherever it finds them. Since the dataset that this BAT file is part of travels between computers, I'd like to be able to run this without the need to hard-code the file path (in other words, instead of telling it "look in this folder," I want it to say "here's the folder where I'm sitting, I need to search through every subfolder").
Thanks to assistance from others smarter than I am, I've been able to make this work as a PS1 by putting "$PSScriptRoot" where you see "$sourceDir" now after the LiteralPath flag. I also know that %~dp0 plays a role in the solution, but I've tried it a couple of different ways and I can't make it work so I need some help.
Thanks!
CodePudding user response:
The simplest approach is to use setlocal
and pushd "%~dp0"
to first change to the batch file's own directory, so that the PowerShell code can then simply act on the current directory:
@echo off & setlocal & pushd "%~dp0" & powerShell.exe -NoProfile -ExecutionPolicy RemoteSigned -Command "Invoke-Expression ((Get-Content -LiteralPath \"%~f0\" | Select-Object -Skip 2) -join \"`n\")"
exit /b %errorlevel%
Write-Host "OPERATION: Purge BMPs from Specified Folders";
# Act on the current dir.
Get-ChildItem -Recurse -LiteralPath . -Filter Clear_BMPs.ps1 |
ForEach-Object { & $_.FullName }
CodePudding user response:
Getting the current working directory in PS Scripts.
'Hello world'
'Get current working directory'
$PSScriptRoot # # is the same as this %~dp0, and only works in a script run
($sourceDir = Get-Location).Path
($sourceDir = $PWD).Path
($sourceDir = (cmd /c echo