-2

Set-Variable -Force does not work. I want to assign the value of it. I don't care if you think that's incorrect or something.

I tried it and it didnt work.

2
  • Take it easy partner :-) See stackoverflow.com/questions/3494115/… Commented Oct 7, 2023 at 16:44
  • 1
    Basically, you can, but not in a persistent way, and it’s not generally a good idea - the value is automatically assigned by Powershell in a variety of contexts so any changes you make get destroyed when the context goes out of scope - for example at the end of each foreach-object iteration (see @mklement0’s answer below). However, if you show some example code where you feel the need to assign a value to $_ it might help explain the reason for your question, and might help you find an alternate approach… Commented Oct 9, 2023 at 7:00

1 Answer 1

3

$_ (aka $PSItem) is an automatic variable, i.e. one controlled by PowerShell itself, and therefore shouldn't be assigned to.

However, you can get PowerShell to set it for you, via an auxiliary ForEach-Object call:

ForEach-Object -InputObject 'custom value for $_' {

  # Inside this block, $_ is now set to whatever you passed to -InputObject

  "`$_ is now: $_"  # -> '$_ is now: custom value for $_'

}

For more information about $_ and the contexts in which it is meaningfully defined by PowerShell, see this answer.

Sign up to request clarification or add additional context in comments.

2 Comments

Interestingly, it seems you can directly assign values to $_ (inside a foreach-object at least - I haven’t tried other contexts) - for example @( "aaa", "bbb" ) | foreach-object { write-host $_; $_ = "xxx"; write-host $_ } outputs xxx from the second write-host call, but the changes are “lost”(by design) when the current context ends (e.g. at the end of every foreach-object iteration). I’d still say it’s not a good idea to do though, even if it works (to a limited extent) :-).
Indeed, @mclayton, you technically can, and that's why I said you shouldn't (which you agree with), instead of you cannot. For a (lengthy) discussion from 6 years ago, see GitHub issue #3695. Perhaps also of interest: the feature request in GitHub issue #3830, which was declined.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.