Shell – What’s the powershell equivalent to “%~dpn0” in batch

batchhard drivepowershell

I'm new to powershell and I asked myself how could I put the following variables in a powershell script? I know how to set a variable in powershell, but I don't know how to get "%~dpn0".

set pgm=%~n0
set log=%~dpn0.log
set csv=%~dpn0.csv
set dir=%~dp0users
set txt=%~n0.txt
set fix=%~dpn0.fix

Best Answer

In batch, %~dpn0 returns the Drive, Path and Name of the currently executing script.

To do the same in a PowerShell script you can use $MyInvocation.MyCommand.Definition.

eg:

$scriptPathAndName = $MyInvocation.MyCommand.Definition
write-host $scriptPathAndName

To get just the path to the script you could use:

$scriptPath = split-path -parent $MyInvocation.MyCommand.Definition
write-host $scriptPath

(Note: in Powershell v3+ you can get the script's path (without the name) by referencing the predefined variable $PSScriptRoot)

To get just the name of the script:

$scriptName = split-path -leaf $MyInvocation.MyCommand.Definition
write-host $scriptName

More info on Split-Path's options: https://technet.microsoft.com/en-us/library/hh849809.aspx

Related Question