Home > Software design >  Powershell script, how to open folder just created by script?
Powershell script, how to open folder just created by script?

Time:03-05

So I'm trying to create a script for the first time in PowerShell, and I was wondering how I could cd into the folder the script just created?

Set-Location -Path G:\Backup
$folderName = (Get-Date).tostring("dd-MM-yyyy-hh-mm-ss")            
New-Item -itemType Directory -Name $FolderName

This script will be used to do a fast backup of personal files. So i want the script to create this folder, cd into it and then i'll script it to copy the most important stuff

CodePudding user response:

Pass the New-Item command's output to Set-Location:

Set-Location -LiteralPath (New-Item -ItemType Directory -Name $FolderName)

Note: The simpler and arguably more PowerShell-idiomatic formulation would be:

New-Item -itemType Directory -Name $FolderName | Set-Location

However, up to at least PowerShell 7.1.2 this has an unexpected side effect: the file-system provider prefix - Microsoft.PowerShell.Core\FileSystem:: - is then reflected in $PWD / Get-Location and therefore also in the interactive prompt string.

This problem is the subject of GitHub issue #10522

  • Related