See the below script that I have for renaming Movie files with .mp4 or .mkv extensions:
<# ::
@echo off
powershell -c "iex ((Get-Content -LiteralPath '%~f0') -join [Environment]::Newline); iex 'main %*'"
pause && goto :eof
#>
$path = Split-Path -Path $PSScriptRoot -Parent
echo $path
## $validExtensions = '.mkv', '.mp4'
## Get-ChildItem -LiteralPath $path -File |
## Where-Object Extension -In $validExtensions |
## Where-Object Length -GT 500mb |
## Rename-Item -NewName {
## ($_.BaseName -replace 'MkvHub.com - ' -replace '(?<=1080p|720p).+' -replace '\.', ' ').ToUpper() + $_.Extension
## }
Currently I have commented out the rest of the Powershell code for obvious reason of testing whether the code Split-Path -Path $PSScriptRoot -Parent or split-path $myInvocation.myCommand.path would give us the literal path of this same script during execution or not.
Clearly it doesn't give me the expected path, and instead throws this error:
Split-Path : Cannot bind argument to parameter 'Path' because it is an empty string.
At line:7 char:26
+ $path = Split-Path -Path $PSScriptRoot -Parent
+ ~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [Split-Path], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Microsoft.PowerShell.Commands.Spli
tPathCommand
Press any key to continue . . .
Also the similar error with split-path $myInvocation.myCommand.path too.
As aforementioned I already tried both split-path $myInvocation.myCommand.path and Split-Path -Path $PSScriptRoot -Parent, but none of them are working.
Can anyone help figuring this out ? I have to make this work in hybrid script only...
$PSScriptRootdoes not hold the value of the parent directory of the running batch file? Also, I should mention that%*could include doublequotes, which could cause you issues, as those would be nested within the-c/-commanddoublequotes.$PSScriptRootis formed when Powershell command/script is invoked, but it seems that it's losing it's value when used inside Hybrid script for sure.splitout fromGet-Location. As a somewhat related side question, what is stopping you from using%~dp0/%~p0from the batch file, and passing it as an argument, or defining it as a variable to be used as needed by PowerShell?@echo offthe command linesetlocal EnableExtensions DisableDelayedExpansionand the command lineset "ScriptPath=%~dp0". The string value of the environment variableScriptPathcan be accessed from with the PowerShell script code wherever this directory path is needed in the PowerShell script code. Please note that the directory path assigned to the environment variableScriptPathends always with a backslash.