How to avoid preceeding space when expanding Powershell variable

493 views Asked by At

Basically I am trying to put together an IE11 uninstall script. I have found this guide from Microsoft: IE11 Uninstall guide But I want to do it with Powershell and DISM instead, since pkgmgr is depricated.

I have put together the below script:

# Get list of IE11 related components to remove
$filenames = Get-ChildItem -Path $env:windir\servicing\Packages | Where-Object { $_.Name -clike "Microsoft-Windows-InternetExplorer-*11.*.mum" }


# Use DISM to remove all the components found above
foreach ($filename in $filenames)
{
    Dism.exe /Online /Remove-Package /Packagepath:($filename.FullName) /quiet /norestart
}

My problem is that the DISM command will fail because the /Packagepath: parameter fails to read the path. The above code will resolve the path to: ..../Packagepath: C:\Windows.... giving me a space between the ":" and the path.

Is there any way I can avoid that space, or alternatively remove that space?

Thanks.

2

There are 2 answers

0
Duncan On

Your problem here is that Powershell interprets /Packagepath:($filename.FullName) as two separate arguments, the first one is the fixed string /Packagepath:, and the second one is a pipeline that evaluates $filename.FullName. The space is inserted to separate the arguments.

The solution is to tell Powershell that you have a single string expression by enclosing it in quotes and using $(...) to evaluate the sub-expression.

PS C:\> $a = 'x'
PS C:\> cmd /c echo /abc:$a
/abc:x
PS C:\> cmd /c echo /abc:($a)
/abc: x
PS C:\> cmd /c echo "/abc:$($a)"

The first echo is similar to the solution you found that works: you have a single argument and Powershell interprets it as one string. The second illustrates your problem with a string /abc: followed by an expression. The last one has a single string made explicit with the quotes and the $(...) may contain any expresion.

0
Jesper On

So this is the script that removed the leading space. Now I just need to get DISM to play nicely:

# Get list of IE11 related components to remove
$filenames = Get-ChildItem -Path $env:windir\servicing\Packages | Where-Object { $_.Name -clike "Microsoft-Windows-InternetExplorer-*11.*" }

# Use DISM to remove all the components found above
foreach ($filename in $filenames)
{

$FullFilePath=$filename.Fullname

Dism.exe "/Online /Remove-Package /Packagename:$FullFilePath /quiet /norestart"