2

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?

1

2 Answers 2

4

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

cd (Join-Path $env:USERPROFILE 'Desktop')
Sign up to request clarification or add additional context in comments.

3 Comments

Thank you very much. It works like charm. Best Regards
By the way, I have this line convert Image.png -resize 300x300 -density 300 -quality 100 ImageNew.png, how can I make Image.png as variable that takes its value from cell in excel .. as I will execute this from excel VBA
Sorry, im not into excel VBA. You probably have to add param($image) at the top of the script and pass the value when you invoke it (ofc, you also have to use $image instead of Image.png). You may start a new question.
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.