YasserKhalil
YasserKhalil

Reputation: 9538

Make the path as variable in PowerShell

I am newbie in PowerShell and I am searching for a way to make the script more dynamic As an example in the script file I have this line

cd C:\Users\Future\Desktop

How can I make the path dynamic ...? I mean to let the other people who will take this script file to run it without changing the username in this line?

Upvotes: 2

Views: 789

Answers (2)

general-gouda
general-gouda

Reputation: 318

To expand upon @Martin Brandl's answer, I would suggest going the Parameter route. You can set a default value for your own use while also allowing people to specify a different path when they run the script. As a small example:

[CmdletBinding()]
param(
    [string]$Path = "C:\Users\Future\Desktop"
)

Set-Location $Path

If you use the Mandatory parameter setting it will require someone to input a Path each time the script is run which is similar to using Read-Host

[CmdletBinding()]
param(
    [Parameter(Mandatory=$true)]
    [string]$Path
)

Set-Location $Path

There are other parameter settings you can use for validation purposes.

I would recommend looking through this page for more information on to set up functions as it describes a lot of the options you can use in parameters.

https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions?view=powershell-6

Upvotes: 1

Martin Brandl
Martin Brandl

Reputation: 58931

You can either add a parameter to the script or use the USERPROFILE variable:

cd (Join-Path $env:USERPROFILE 'Desktop')

Upvotes: 4

Related Questions