Sweet T
Sweet T

Reputation: 5

Run PowerShell script in folder that it lives in

I have a question that I think will be relatively simple to answer. I have a script that will change blank file extensions to be PDFs. Here it is:

$directory = 'C:\Test\Files'

Get-ChildItem -File $directory | Where-Object { -Not $_.Extension } | Foreach-Object {
  $_ | Rename-Item -NewName "$($_.Name).pdf"
}

It works just fine, but I need it to only run in the directory/folder it lives in. For example, if I have it in my documents folder, it would only run in my documents folder and not make any changes to any other folders, including subfolders in the documents folder. Is this possible, and what would it look like? Thanks!

Upvotes: 0

Views: 166

Answers (2)

Ansgar Wiechers
Ansgar Wiechers

Reputation: 200323

On PowerShell v3 or newer use

$directory = $PSScriptRoot

On older versions use

$directory = Split-Path -Parent $MyInvocation.MyCommand.Path

Upvotes: 1

GNUzilla
GNUzilla

Reputation: 116

Use the $myinvocation automatic variable

$invoke = $myinvocation.mycommand.path
$directory = Split-Path $invoke
Get-ChildItem -File $directory | Where-Object { -Not $_.Extension } | Foreach-Object {$_ | Rename-Item -NewName "$($_.Name).pdf"
}

Upvotes: 0

Related Questions