MaineMan
MaineMan

Reputation: 51

Set a location to a Variable in PowerShell

I'm very new to PowerShell, and I'm sure this is a simple question but I'm a little stumped. I'm trying to open a Folder, sort by LastWriteTime, and open the Folder at the top of the list. I want to store that in a variable so when I call the variable I can set my location to that variable. The problem I'm having is that when I call my variable, nothing happens:

$latest = Get-Childitem C:\Main | Sort LastWriteTime -Descending | Select -First 1 | Invoke-Item

How come I get an error when I try to 'Set-Location $latest'?

Upvotes: 5

Views: 13032

Answers (5)

rovinos
rovinos

Reputation: 222

If you want to use a variable as the value for Set-Location then you should use it like this:

$variableName = whatever
Set-Location (Split-Path variableName)

Notice that I'm not using the $ sign.

Upvotes: 2

Petro Franko
Petro Franko

Reputation: 6786

This worked for me:

$last = gci ./ | sort LastWriteTime | select -last 1
Set-Location ($last.FullName)

Upvotes: 3

Shay Levy
Shay Levy

Reputation: 126722

Give this a try:

$first = Get-Childitem C:\Main | Sort-Object LastWriteTime -Descending | Select-Object -First 1
Set-Location (Split-Path $first.FullName)

Upvotes: 1

Aaron Jensen
Aaron Jensen

Reputation: 26729

I would use Tee-Object to set the variable $latest to the directory and also continue sending the directory object down the pipeline.

Get-Childitem C:\Main | 
    Sort LastWriteTime -Descending | 
    Select-Object -First 1 | 
    Tee-Object -Variable latest |
    Invoke-Item

Upvotes: 2

johnshen64
johnshen64

Reputation: 3884

You already invoke-item on what you got, and the default action was performed. the variable will just return the status of that action, not the item returned. If you remove the last pipe invoke-item, you may get what you want.

set-location needs a string, and powershell returns an object. so something like this may be what you want.

set-location "c:\Main\" + $lastest.name

Upvotes: 0

Related Questions