Comment puis-je obtenir l'emplacement du système de fichiers D'un script PowerShell?

j'ai un script PowerShell situé à D:temp .

quand j'exécute ce script, je veux que l'emplacement actuel du fichier soit indiqué. Comment dois-je faire?

par exemple, ce code l'accomplirait dans un fichier batch DOS; j'essaie de le convertir en script PowerShell...

FOR /f "usebackq tokens=*" %%a IN ('%0') DO SET this_cmds_dir=%%~dpa
CD /d "%this_cmds_dir%"
48
demandé sur Peter Mortensen 2010-09-08 15:31:26

2 réponses

PowerShell 3+

le chemin d'un script en cours d'exécution est:

$PSCommandPath

son répertoire est:

$PSScriptRoot

PowerShell 2

le chemin d'un script en cours d'exécution est:

$MyInvocation.MyCommand.Path

son répertoire est:

$PSScriptRoot = Split-Path $MyInvocation.MyCommand.Path -Parent
104
répondu Roman Kuzmin 2014-04-29 18:36:21

Roman Kuzmin a répondu à la question imho. J'ajouterai simplement que si vous importez un module (via Import-Module ), vous pouvez accéder à la variable automatique $PsScriptRoot à l'intérieur du module -- qui vous indiquera où se trouve le module.

8
répondu stej 2010-09-08 12:26:11