• Just replace....

1) %comspec% + -ArgumentList '/c + %~fnx0 % to:

Start-Process $env:windir\system32\cmd.exe -Verb RunAs -Argument $env:cmd_arg

2) Your powershell command does not require quotes, remove them

%__APPDIR__%\WindowsPowerShell\v1.0\powershell.exe -ex unrestricted -Command Start-Process $env:windir\system32\cmd.exe -Verb RunAs -Argument $env:cmd_arg

3) Remove quotes/semi-quotes from '/c %~fnx0 %*' and replace to $env:cmd_arg


4) For %%P1%%, try using:


cmd /v /c "echo !P1!"
call echo/ %P1%
echo/ %P1%
echo= %P1%
echo[ %P1%
echo( %P1%
echo. %P1%

@echo off && setlocal EnableDelayedExpansion


title <nul && Title ...\%~nx0
%__APPDIR__%mode.com con: cols=99 lines=3
for %%i in (%*)do set "_arg=!_arg! "%%~i" "

set "cmd_arg= /v /c "%~fnx0" !_arg!" && %__APPDIR__%Net.exe file 2>nul >nul && (
      goto :RunAsAdmin 
      ) || (
      color 9f & echo/ Running your PowerShel cmdlets...
      set "_ps1=%__APPDIR__%\WindowsPowerShell\v1.0\powershell.exe"
      !_ps1! -ex unrestricted -Command Start-Process $env:windir\system32\cmd.exe -Verb RunAs -Argument $env:cmd_arg
      echo/ Press any key to exit... && %__APPDIR__%timeout.exe -1 >nul & endlocal && goto :EOF
      )

echo/ If you see this, sorry it doesn't work... && goto :EOF

:RunAsAdmin
%__APPDIR__%mode.com 99,25 && color 0A

echo/If you see this one, it works sr. Admin^!!... 
title <nul && Title ...\%~nx0 

rem ::  do your admin tasks here....
echo/ Press any key to exit... && %__APPDIR__%timeout.exe -1 >nul
endlocal && goto :EOF 
Answer from Io-oI on Stack Exchange
🌐
The Lonely Administrator
jdhitsolutions.com › commandline › friday fun: expand environmental variables in powershell strings
Friday Fun: Expand Environmental Variables in PowerShell Strings • The Lonely Administrator
June 29, 2012 - This seems reasonable enough. Take a string, use a regular expression to find the environmental variable, find the variable in ENV:, do a replacement, write the revised string back to the pipeline.
Discussions

powershell - %temp% etc not working - Stack Overflow
I have the below that is used as a batch file that launches powershell (too long to go over but it is used in another script). Anyway, I noticed the %systemroot%\temp and %systemroot% does not wor... More on stackoverflow.com
🌐 stackoverflow.com
Environment Variable inside a single '
There are a lot of different ways to do this, I like PowerShell's flexibility when dealing with strings. Single quotes do indeed turn everything literal. however, single quotes are literal inside of double quotes msiexec wont care if the path is encased in single or double quotes so you could use single quotes in your string -ArgumentList "/I '$env:temp\My MSI File.msi' /qn" You could also escape the double quote with a back tick -ArgumentList "/I `"$env:temp\My MSI File.msi`" /qn" Unrelated to your post but helpful when dealing with strings. If you are trying to access a property in an object that is a string it can be formatted like this "This is the users first name $($user.firstname)" More on reddit.com
🌐 r/PowerShell
6
14
November 10, 2021
Adding non-expanded environment variable to Path, but it doesn't expand
The trouble is the .NET method SetEnvironmentVariable will automatically set the value of the underlying registry value from REG_EXPAND_SZ to just REG_SZ which breaks automatic env var expansion. There is no way around this except to avoid using this method and manipulate the raw registry yourself. The following example will get the raw unexpanded values and set it as an ExpandString. $key = Get-Item 'HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment' # Will get the non-expanded values $existingPath = $key.GetValue('PATH', '', 'DoNotExpandEnvironmentNames') $newPath = "${existingPath};%TEST_VAR%" $key.SetValue('PATH', $newPath, 'ExpandString') More on reddit.com
🌐 r/PowerShell
10
1
April 15, 2024
Set and Get windows environment variables from powershell
Summary of the new feature / enhancement I would like to add Set-WinEnvironmentVariable and Get-WinEnvironmentVariable cmdlets that work only in Windows environment so that I can manipulate environ... More on github.com
🌐 github.com
10
September 19, 2022
🌐
Microsoft
devblogs.microsoft.com › dev blogs › scripting blog [archived] › powertip: expand environmental variables with powershell
PowerTip: Expand Environmental Variables with PowerShell - Scripting Blog [archived]
August 5, 2014 - Summary: Learn to expand the value of environmental variables by using Windows PowerShell. How can I use Windows PowerShell to find the value of a common environmental variable such as %username% or %computername%? Use the ExpandEnvornmentalVariables static method from the System.Environment .NET Framework class, for example: [System.Environment]::ExpandEnvironmentVariables("%username%") [System.Environment]::ExpandEnvironmentVariables("%computername%")
🌐
Ais
ais.com › home › blog › expanding variable strings in powershell
Expanding Variable Strings in PowerShell - Applied Information Sciences
August 28, 2023 - Turns out there is a second way. The ExpandString function does exactly what we want. It’s not a cmdlet but rather part of the internal PowerShell engine. So, you can use $ExecutionContext.InvokeCommand.ExpandString("$Domain\$User") and voila!
🌐
ITPro Today
itprotoday.com › home › powershell
Variable Expansion in PowerShell
November 29, 2024 - In some circumstances, PowerShell can even automatically translate the variable into its actual value as part of another string. For example, I could input the following: ... So, the first important point is, double-quoted strings expand environment variables, single-quoted strings do not.
🌐
Reddit
reddit.com › r/powershell › environment variable inside a single '
r/PowerShell on Reddit: Environment Variable inside a single '
November 10, 2021 -

Hi Everyone,

I am not great with scripting, so apologies for not using the correct terminology and likely asking a very basic question. I am attempting to install an MSI package and my MSI package has a space in the name (I can't rename it, it has to be this name). I am invoking the start-process command with the below argument list.

-ArgumentList '/I "$env:temp\My MSI File.msi" /qn'

This fails and I believe it is due to the use of the single quote which I think it turning everything inside of it as a literal statement so it is not reading the environment variable etc. What do I need to do to get this to work?

Cheers!

***Edit, I figured it out. I needed to wrap what needed to be in quotes with an extra set of quotes and use quotes around the entire argument list like this:

-ArgumentList "/I ""$env:temp\My MSI File.msi"" /qn"

Find elsewhere
🌐
Microsoft
devblogs.microsoft.com › dev blogs › powershell team › variable expansion in strings and here-strings
Variable expansion in strings and here-strings - PowerShell Team
February 18, 2019 - Here-Strings can use any character you want until it sees a “@ which terminates the string. ... “Cmds” with > 800 handles are: $( $limit = 800 $procs = Get-Process |where {$_.handles -ge $limit} foreach ($p in $procs) { ... “Cmds” with > 800 handles are: CCMEXEC CSRSS IEXPLORE IEXPLORE LSASS OUTLOOK POWERSHELL PS SEARCHINDEXER SVCHOST SYSTEM WINLOGON Jeffrey likes to say,
🌐
Reddit
reddit.com › r/powershell › adding non-expanded environment variable to path, but it doesn't expand
r/PowerShell on Reddit: Adding non-expanded environment variable to Path, but it doesn't expand
April 15, 2024 -

I was trying to add a environment variable to my user's Path using PowerShell, so I searched about and ended up with a code similar to this one:

[Environment]::SetEnvironmentVariable("TEST_VAR", "test-value", "User")
$currPath = [Environment]::GetEnvironmentVariable("Path", "User")
$newPath = "$currPath;%TEST_VAR%;"
[Environment]::SetEnvironmentVariable("Path", $newPath, "User")

The idea is to change TEST_VAR value in the future and by doing so updating the Path easily.

The problem I've found is that when setting Path with a non-expanded variable (in this case, %TEST_VAR%) it won't expand automatically. So, if I open the cmd and try to echo Path, I get something like this:

C:\Progr [...] omeOherStuff;%TEST_VAR%;

When it should be returning this:

C:\Progr [...] omeOherStuff;test-value;

Some places where I searched said that the answer to this problem is messing around with reg add, but I am not sure about it and even with some testing trying to set %TEST_VAR% as REG_EXPAND_SZ didn't work for me.

That is my first post here, also sorry if my english is bad. Thanks.

🌐
powershell.one
powershell.one › wmi › root › cimv2 › stdregprov-GetExpandedStringValue
GetExpandedStringValue - powershell.one
May 20, 2020 - In other words, the environment variable %USERPROFILE% is replaced with the folder (in this case, C:\Documents and Settings\jsmith.REDMOND) that contains the user profile. The components of expanded string types that appear between percent symbols (%) correspond to environment variables and ...
🌐
Nfshost
switch.nfshost.com › 2014-12-09-strings-expansion
Powershell String Expansion | switch
December 9, 2014 - The following code will expand ... to expand a property of an object, a key of a hashtable, or an index of an array, you must enclose the variable in a subexpression ($())....
🌐
Super User
superuser.com › questions › 1351802 › how-can-i-store-a-powershell-variables-value-as-a-string-while-creating-ise-sub
How can I store a Powershell variable's value as a string while creating ISE submenus - Super User
$parentProfile = $psISE.CurrentPowerShellTab.AddOnsMenu.SubMenus.Add("Modules",$null,$null) $mymodules = Get-ChildItem $env:USERPROFILE\documents\windowspowershell\modules | Where-Object { $_.PSIsContainer } | Select-Object name -ExpandProperty name $i = 0 foreach ($folder in $mymodules) { $auxStringBlock = "Import-Module -Name $folder" ### create the script block as an expanding string. $parentProfile.SubMenus.Add( "$folder", [scriptblock]::Create( $auxStringBlock), ### use the static `Create` method from the `[scriptblock]` class $null # keyboard shortcut ) } ... Find the answer to your question by asking. Ask question ... See similar questions with these tags. ... Lights, camera, open source! 3 How to avoid word wrap in PowerShell ISE output pane
🌐
Google Groups
groups.google.com › g › microsoft.public.windows.powershell › c › zeK5NEuKEV8
Expanding string
It should support nesting by '.' as well (it's a posh module for data visualization http://www.leporelo.eu/blog.aspx?id=powershell-module-for-html-visualization ) So consider this: $x = [xml]@" <root> <a> <b> <c>42</c> </b> </a> <a> <b> <c>really?</c> </b> </a> </root> "@ $property = "root.a[0].b.c" $ExecutionContext.InvokeCommand.expandstring('$($x.'+$property +')') #returns 42
🌐
ShellGeek
shellgeek.com › home › powershell › powershell variable expansion
PowerShell Variable Expansion - ShellGeek
April 14, 2024 - Double-Quotes enable variable expansion. PowerShell Variable expansion in string enables dynamic string creation based on the variable values
🌐
Microsoft Learn
learn.microsoft.com › en-us › powershell › module › microsoft.powershell.core › about › about_environment_variables
about_Environment_Variables - PowerShell | Microsoft Learn
September 5, 2024 - At line:1 char:12 + $Env:foo | Get-Member + ~~~~~~~~~~ + CategoryInfo : CloseError: (:) [Get-Member], InvalidOperationException + FullyQualifiedErrorId : NoObjectInGetMember,Microsoft.PowerShell.Commands.GetMemberCommand · Get-Member returned an error because the environment variable was removed. You can see that it doesn't return an error when you use it on an empty string:
🌐
Computer Performance
computerperformance.co.uk › home › powershell
PowerShell Basics: $Env: - Environment Variables | Examples & Scripts
January 16, 2019 - Path is probably the most interesting ... and thus expand the path. Remember we are dealing with variables, hence $Env. ... Note 1: You really do need that $dollar sign. Plain Env:Path does not work here. ... This script will find temporary files; actually, it’s a precursor to using PowerShell to delete such temp files. # PowerShell Script to List Temp Files Get-Childitem $Env:Temp -Recurse ... Here is a basic example of taking information in an environmental variable and ...
🌐
GitHub
github.com › PowerShell › PowerShell › issues › 18126
Set and Get windows environment variables from powershell · Issue #18126 · PowerShell/PowerShell
September 19, 2022 - Summary of the new feature / enhancement I would like to add Set-WinEnvironmentVariable and Get-WinEnvironmentVariable cmdlets that work only in Windows environment so that I can manipulate environ...
Author   PowerShell
🌐
Stack Overflow
stackoverflow.com › questions › 23813478 › set-nested-expandable-environment-variable-with-powershell
windows - Set nested expandable environment variable with PowerShell - Stack Overflow
(Note that simply opening the Environment Variables dialog box from System Properties and clicking OK updates all of Explorer's environment variables from the registry values). To achieve the same effect from PowerShell — simultaneously changing the value in the registry and in Explorer's environment which is passed on to new cmd sessions — you can do this: [Environment]::SetEnvironmentVariable("Path", $envpath, 'Machine') ... because if the target is Machine, the value in the current PowerShell session is not changed. (You can use the strings 'Process' and 'Machine' instead of [EnvironmentVariableTarget]::Process and [EnvironmentVariableTarget]::Machine).