Search code examples
powershellbatch-fileone-liner

PowerShell mask Get-ItemPropertyValue one-liner in batch file


I use PowerShell one-liners in several batch scripts, but seem failing to escape the following one correctly:

if not defined LANGUAGE (
for /f "usebackq" %%v in (`PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command "(Get-ItemPropertyValue -Path 'HKCU:Control Panel\International\' -Name 'LocaleName').Split('-')[0]"`) do set LANGUAGE=%%v
)

I verified that it is this line that fails in my batch file. The idea behind the code is to read the value from the registry and assign the first part before the hyphen to an environment variable. So if the registry value is "de-DE", LANGUAGE shall have the value of "de".


Solution

  • I cannot reproduce an issue with the code you've provided.

    I would however suggest you consider other approaches - compare these examples and note which executes the fastest

    @Echo off
    
     Setlocal
    
     For /f "delims=" %%v in ('where /r "%Windir%\SysWOW64\WindowsPowerShell" powershell.exe')Do Set "powershell=%%v -nologo -noprofile"
    
     Echo(%TIME%
     For /f "usebackq" %%v in (`PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command "(Get-ItemPropertyValue -Path 'HKCU:Control Panel\International\' -Name 'LocaleName').Split('-')[0]"`) do set "LANGUAGE=%%v"
     Set LANG
     Echo(%TIME%
    
     For /f "usebackq tokens=1 Delims=-" %%G in (`
      %powershell% -c "Get-ItemPropertyValue -Path 'HKCU:Control Panel\International\' -Name 'LocaleName'"
     `)Do Set "LANGUAGE=%%G"
     Set LANG
     Echo(%TIME%
    
     For /f "Skip=1 tokens=3 Delims=- " %%G in ('reg query "HKEY_CURRENT_USER\Control Panel\International" /v localename')Do Set "LANGUAGE=%%G"
     Set LANG
     Echo(%TIME%
    
     Endlocal
    Goto:Eof