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.
$_ (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.
$_ (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) :-).
foreach-objectiteration (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…