5

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
1
  • What an answerer was helpful enough to state "In batch, %~dpn0 returns the Drive, Path and Name of the currently executing script." You were not
    – barlop
    Commented Feb 18, 2018 at 22:39

2 Answers 2

7

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

0
1

I think you're looking for something like this

$ScriptPath = Split-Path $MyInvocation.MyCommand.Path

Then I think -Parent will give you the PWD, but you may not need that.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .