Tuesday, March 5, 2019

How we can get the script file system location of from Power-Shell script ?


Here is the some cases we have to get power shell script system directory path .There is many way to achieve that .Power shell have some inbuilt function to get system directory and script path and root n-1 directory.
I am showing some example here. This examples may be help you to get your target Dir.




1. Best way to get Script directory path is

         $PSScriptRoot

Just save below code in .PS1 format and run it and you will get Dir path

         $ScriptName = $PSScriptRoot
         Write-host $ScriptName

Note:- For using $PSScriptRoot method your power shell version has 3.0 or above.If you have below 3.0 power shell function so please use below methods.

2. Get power shell script path

         $Script:sScriptFolder = (Get-Item $($MyInvocation.MyCommand.Path)).DirectoryName
         Write-Host $sScriptFolder

3. Get power shell script path

         $MyDir = [System.IO.Path]::GetDirectoryName($myInvocation.MyCommand.Definition)
         Write-Host $MyDir

4. Get power shell script file name.This is very good function

         $MyDir1 = $MyInvocation.MyCommand.Name
         Write-Host $MyDir1

5. Get complete power shell script path.

         $script_path = $myinvocation.mycommand.path
         Write-Host "Current ScriptPath $script_path"

6. Get the current directory of the cmdlet being executed

         (Get-Item -Path ".\").FullName

7. Get Script parent folder N-1 and N-2 folder path.This script will help you.

         $scriptPath = (Get-Item $($MyInvocation.MyCommand.Path)).DirectoryName
         $parentPath = Split-Path -parent $scriptPath
         Write-host $parentPath
         $rootPath = Split-Path -parent $parentPath
         Write-host $rootPath



Note:- Please test script in your test environment before running in production directly.


No comments:

Post a Comment