如果您只需要主要和次要数字,通过powershell,那么只返回那些似乎更明智,而不是事后解析结果:
For /F %%G In ('^""%__AppDir__%WindowsPowerShell\v1.0\powershell.exe" ^
-NoProfile -NoLogo -Command "[System.Environment]::OSVersion.Version | " ^
"ForEach-Object { '{0}.{1}' -F $_.Major,$_.Minor }"^"') Do Set "OSVar=%%G"
作为单行者:
For /F %%G In ('%__AppDir__%WindowsPowerShell\v1.0\powershell.exe -NoP "[System.Environment]::OSVersion.Version|%%{'{0}.{1}' -F $_.Major,$_.Minor}"')Do Set "OSVar=%%G"
如果你真的想坚持使用powershell 和Get-CimInstance:
For /F %%G In ('^""%__AppDir__%WindowsPowerShell\v1.0\powershell.exe" -NoP ^
"(Get-CimInstance Win32_OperatingSystem).Version.Split('.')[0,1] -Join '.'"^"'
) Do Set "OSVar=%%G"
作为单行者:
For /F %%G In ('%__AppDir__%WindowsPowerShell\v1.0\powershell.exe -NoP "(GCim Win32_OperatingSystem).Version.Split('.')[0,1] -Join '.'"')Do Set "OSVar=%%G"
但是,如果您希望在检索到 do 部分后对其进行解析,那么我建议使用比使用标记和分隔符更简单的方法:
For /F %%G In ('^""%__AppDir__%WindowsPowerShell\v1.0\powershell.exe" ^
-NoProfile -NoLogo "(Get-CimInstance Win32_OperatingSystem).Version"^"'
) Do Set "OSVar=%%~nG"
作为单行者:
For /F %%G In ('%__AppDir__%WindowsPowerShell\v1.0\powershell.exe -NoP "(GCim Win32_OperatingSystem).Version"')Do Set "OSVar=%%~nG"
在前面的两个示例中,.BuildNumber 被视为扩展名,因此使用元变量扩展我们可以返回不带扩展名的名称。
但是,您不需要powershell 来获取 WMI 信息,您可以改用wmic:
For /F %%G In ('"%__AppDir__%wbem\WMIC.exe" OS Get Version'
) Do If "%%~xG" NEq "" Set "OSVar=%%~nG"
再次作为单行者:
For /F %%G In ('%__AppDir__%wbem\WMIC.exe OS Get Version')Do If "%%~xG" NEq "" Set "OSVar=%%~nG"