Powershell Reset Windows Update - powershell

I currently installed a fresh official Windows 7 Ultimate on my MacbookPro with BootCamp.
Everything is running good except Windows Update. Stuck on Searching for updates..
So I made a lot of google searches (for about 4 hours now) and I tried many things such as the FixIt tools from MS and other tricks but nothing is working.
Now i'm trying this:
http://www.sevenforums.com/performance-maintenance/372790-very-high-memory-sometimes-cpu-usage-svchost-exe-up-1-gb-post3095241.html#post3095241
I'm now at using PowerShell and entering this command line:
sc.exe sdset bits D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;AU)(A;;CCLCSWRPWPDTLOCRRC;;;PU)
I always get this error:
Missing closing ')' in expression.
At line:1 char:23
+ sc.exe sdset bits D:(A <<<< ;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRS
DRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;AU)(A;;CCLCSWRPWPDTLOCRRC;;;PU)
+ CategoryInfo : ParserError: (CloseParenToken:TokenId) [], Paren
tContainsErrorRecordException
+ FullyQualifiedErrorId : MissingEndParenthesisInExpression
enter code here
I took a look at the commande line and I dont see any missing ')', and made some other google search for this command line from other websites and always give the same error
Whats wrong..!?
Update:
I tried this without success (same error)
$str = "sc.exe sdset bits D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;AU)(A;;CCLCSWRPWPDTLOCRRC;;;PU)"
Invoke-Expression $str

SOLUTION
I found the solution and its to type the command as follow:
CMD /C "sc.exe sdset bits D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;AU)(A;;CCLCSWRPWPDTLOCRRC;;;PU)"

When I put quotes around the entire command, the dos prompt removed the quote marks, and returned the result. Putting the quotes around the long parameter list, i.e., doing this:
sc.exe sdset bits "D:(A;; [snip] ;;PU)"
resulted in the Dos Prompt executing giving the message Success.

PowerShell does not play well with DOS executable files and their arguments.
Try using:
Start-Process sc.exe -ArgumentList 'sdset bits D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;AU)(A;;CCLCSWRPWPDTLOCRRC;;;PU)'

Since this is invoking DOS use single quotes around the DOS command and add double quotes around the ACL "D:(A;;......;;PU)". It would look like this
Invoke-Expression -Command 'sc.exe sdset bits "D:(A;;CCLCSWRPWPDTLOCRRC;;;SY)(A;;CCDCLCSWRPWPDTLOCRSDRCWDWO;;;BA)(A;;CCLCSWLOCRRC;;;AU)(A;;CCLCSWRPWPDTLOCRRC;;;PU)"'

Related

Powershell, run a cmd command with latin character like ä, ö, ü

I've a problem with latin character in powershell. I've tried to run a cmd command in a powershell script, because we work with Sumatra-PDF (printing tool).
The command looks like that:
$Befehlkpl = "W:\SumatraPDF\sumatrapdf.exe `-print-to $Drucker2 `-print`-settings `"paper=" + $Papier1 + ", " + $Farbeinstellung + ", " + $Seiteneinstellung + "`" "
$Befehlkpl | cmd -encoding 'utf8'
Now one of these variable can include a ä or ü or ö. The console-output is allright, but the respond of cmd is not working
The encoding command was in every attempt not working.
Thank you very much for every advice!
The following works for me HOWEVER as written it raises a syntax error about my use of escaped quotes, but completes the job exactly as expected
[string] $Drucker2 = "Text Only"
[string] $Option1 = "A4"
[string] $Option2 = "whatever"
[string] $Filenames = "Hello äüö World.pdf"
`"
Start-Process -FilePath "$env:comspec" -ArgumentList "/k","`"`"c:\program files\sumatrapdf\sumatrapdf.exe`"",-print-to,`"$Drucker2`",-print-settings,`"paper=$Option1","$Option2`",`"$Filenames`","`&",pause`" -Wait -WindowStyle Minimized
Note this is a conceptual answer to prove it works, you will need to change variables as required. once you prove it functions you can remove the & pause since that with /k was to debug the syntax errors, but do keep the -wait to ensure you can trap any runtime erroring.
I strongly suggest that you find a Cmd method as the contortions required getting it to work in alien PowerShell took me ages and I know that command line inside out.
DO NOT use -silent and remember PDF printing need the graphics rendering system so should not be hidden from cmd.exe which it expects to be running within as a graphics console. (e.g. do not run SumatraPDF on a headless server, without expecting problems)
By far the simplest method for drag and drop or other batch printing is to use the simplest of command lines and if you keep your printer names to the normal Latin range the only problem is long names which can be avoided by using short name equivalent thus the example above runs perfectly well using:-
set "$filename=%~s1"
"C:\Program Files\SumatraPDF\sumatrapdf.exe" -print-to "Microsoft Print to PDF" -print-settings "paper=A4,Landscape" %$filename%

PowerShell Error - Missing expression after unary operator '-'

I have two PowerShell scripts. One is for uninstalling and installing a SharePoint 2010 solution on the SharePoint server. The other calls this script with two commands, one for the uninstall and one for the install. These are not scripts I wrote, but I have inherited them.
Here is the script that calls the install / uninstall script (I've removed some parameters to simplify for troubleshooting):
& 'C:\Users\username\Documents\setup.ps1' -InstallOrUninstall '/UNINSTALL'
& 'C:\Users\username\Documents\setup.ps1' -InstallOrUninstall '/INSTALL'
Stripped down to almost nothing for the purpose of testing, here is the "setup.ps1" script:
param ($InstallOrUninstall,
$SiteURL,
$WebURL,
[switch]$ignoreFeatures,
[switch]$thisAppDomain )
if (-not $thisAppDomain)
{
Write-Host "Invoking script in a new app domain" -foregroundcolor yellow
Write-Host $MyInvocation.Line
powershell.exe -Version 2 -Command $MyInvocation.Line -thisAppDomain
return;
}
Write-Host "In Body"
Write-Host $MyInvocation.Line
Running the first script returns an error from the first command, but not from the second. The error is:
powershell.exe : - : Missing expression after unary operator '-'.
At C:\Users\username\Documents\setup.ps1:11 char:6
+ powershell.exe -Version 2 -Command $MyInvocation.Line -thisAppDo ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (- : Missing exp...y operator '-'.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
+ CategoryInfo : ParserError: (-:String) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingExpressionAfterOperator
I believe the reason the install / uninstall script is resending the command for "Version 2" is because of an issue with using PowerShell past Version 2 with SharePoint 2010 (as outlined here). However, I don't understand why only the first line fails. The second command also enters the if statement, but does not error.
If I remove the second line, and only call the setup.ps1 one time, the script that calls the install / uninstall script succeeds.
A nice little brain-teaser. Apparently, $MyInvocation.Line contains the full line, including the newline / linebreak at the end. So, -thisAppDomain is not interpreted as a parameter, but the beginning of a new expression starting with -. This is also, why it works if you remove the 2nd line, because then you do not have a line break at the end.
To reproduce this error, try:
powershell.exe -Version 2 -Command "`r`n-thisAppDomain"
Note that in newer versions the parsing algorithm was obviousy modified and the error message is different. Omit the -Version 2 switch and you likely get:
The term "-thisAppDomain" is not recognized as the name of a cmdlet, function, script file, or operable program...
One simple way to resolve this would be to .Trim() (or .TrimEnd()) the command:
powershell.exe -Version 2 -Command $MyInvocation.Line.Trim() -thisAppDomain
I need to add though, that you should reconsider what your actual problem is, and if your solution is actually the best way to solve it. Have a look at jobs for example.
As marsze said: It is not interpreted as a parameter, but the beginning of a new expression starting with -. This is also, why it works if you remove the 2nd line, because then you do not have a line break at the end.

Set window title when running "start powershell" in powershell not working?

The following command works in CMD (How to start powershell with a window title?).
start powershell -NoExit -command "$Host.UI.RawUI.WindowTitle = 'bits'"
But it doesn't work in Powershell.
PS C:\> start powershell -noexit -command "$Host.UI.RawUI.WindowTitle = 'test'; read-host"
Start-Process : A parameter cannot be found that matches parameter name 'noexit'.
At line:1 char:18
+ start powershell -noexit -command "$Host.UI.RawUI.WindowTitle = 'test ...
+ ~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [Start-Process], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.StartProcessCommand
The following command can open a new powershell window.
start powershell "$Host.UI.RawUI.WindowTitle = 'test'; read-host"
However, the new window shows the following error message and the title is not set.
System.Management.Automation.Internal.Host.InternalHost.UI.RawUI.WindowTitle : The term
'System.Management.Automation.Internal.Host.InternalHost.UI.RawUI.WindowTitle' is not recognized as the name of a
cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify
that the path is correct and try again.
At line:1 char:1
+ System.Management.Automation.Internal.Host.InternalHost.UI.RawUI.Wind ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (System.Manageme...wUI.WindowTitle:String) [], CommandNotFoundException
+ FullyQualifiedErrorId : CommandNotFoundException
Bacon Bits' helpful answer explains that start in cmd.exe means something different than in PowerShell.
Use Start-Process as follows to get the desired result; note that powershell implicitly binds to parameter -FilePath, whereas the ,-separated arguments starting with -NoExit bind implicitly to the -ArgumentList (-Args) parameter, which accepts an array of strings:
# In PowerShell, `start` is an alias for `Start-Process`
start powershell '-NoExit', '-command', "`$Host.UI.RawUI.WindowTitle = 'bits'"
In paticular, --prefixed pass-through arguments must be quoted so that they're not mistaken for Start-Process's own parameters.
Also note the ` preceding the $ in $Host, which prevents up-front interpolation of $Host by the calling PowerShell instance.
You could also use '$Host.UI.RawUI.WindowTitle = ''bits''', a single-quoted literal string with embedded single quotes escaped as ''.
Important:
While passing arguments as an array to -ArgumentList is conceptually the best approach, it is unfortunately ill-advised due to a long-standing bug in Start-Process, still present as of this writing (v7.1) - see GitHub issue #5576.
For now, using a single string comprising all arguments, enclosed in embedded "..." quoting as necessary, is the only generally robust approach. As discussed in the linked GitHub issue, an -ArgumentArray parameter that supports robust array-based argument passing may be introduced in the future.
In the case at hand this means the following, as suggested by PetSerAl in a comment on the question:
Start-Process powershell '-NoExit -command "$Host.UI.RawUI.WindowTitle = ''bits''"'
Note the single-quoting_ ('...') of the overall argument-list string, which then necessitates escaping the embedded single quotes - those that PowerShell should see as part of the command - as ''.
In Command Prompt, start is the start internal command. In Windows Powershell, start is an alias for Start-Process, which does something similar but isn't identical.
Try running this:
powershell -NoExit -command "`$Host.UI.RawUI.WindowTitle = 'bits'"
Here's another way, while avoiding the dollar sign. The double quotes have to be on the outside, so that bits stays quoted.
start powershell "-noexit (get-variable host).value.ui.rawui.windowtitle = 'bits'"
You can always avoid these quoting issues putting the command in a file.
start powershell '-noexit .\window.ps1'
start powershell with the command option for setting the window title did not work for me. Maybe because I want to open another powershell with a ps1 file. so in the other ps1 file I added the first line as below,
(Get-Host).ui.RawUI.WindowTitle='TEST TEST'
and it worked like a charm....
If you add this to your powershell profile.ps1 you can get the window title to show the current running script and if you are just opening a window with no script then 'pwsh' will be displayed.
Will be systematic with no need to add a line on top of each script. The other answers
combined with $MyInvocation.MyCommand seem to give the name of the profile.ps1 instead when running a script from the context menu.
This can also be tweaked to change the result.
[console]::title = Split-Path -Leaf ([Environment]::GetCommandLineArgs()[-1]).Replace('pwsh.dll','pwsh')
Works on both PS 5 and 7 . For ver. 5 replace pwsh.dll by powershell.exe

powershell cmdlet errors vary in script vs. console direst entry

Please understand this is a part of a much larger script.
It is unreasonable for me to post the entire script to this question.
I have done a bunch of test and proven the root cause is the Copy-Item command ~ behaves differently run as a script vs. manually executing the cmdlet manually typing in the PS console.
#PS 5.1.14393.206 on Windows10 properly
$SiteName = "mysite"
$AppPoolTemplate = ".NET` v4.5"
$iisAppPoolTemplate = "IIS:\AppPools\$AppPoolTemplate"
$iisAppPool = "IIS:\AppPools\$SiteName"
$iisSites = "IIS:\Sites\$SiteName"
Write-Host "AppPoolTemplate //$AppPoolTemplate//"
Write-Host "iisAppPoolTemplate //$iisAppPoolTemplate//"
Write-Host "iisAppPool //$iisAppPool//"
Write-Host "iisSites //$iisSites//"
Stop-WebAppPool -Name $AppPoolTemplate
Copy-Item $iisAppPoolTemplate $iisAppPool # fails
Copy-Item IIS:\AppPools\.NET` v4.5 IIS:\AppPools\mysite # doesn't fail, but doesn't copy either
The first Copy-Item statement
Copy-Item $iisAppPoolTemplate $iisAppPool
causes the script to fail. Removing this line proves the problem starts with this line. The actual error line reported is whichever is the last line with properly "closed string literal". Erroneously reporting the literal is not closed. This error only occurs if I run the script. If I cut-and-paste the script content into PS console ... no error.
If run the second Copy-Item statement
Copy-Item IIS:\AppPools\.NET` v4.5 IIS:\AppPools\mysite
from a script it completes without error. But doesn't do what it is supposed to do. If I cut-and-paste the above command into a PS console .. no error AND does what it is supposed to do.
Here is the actual error.
The error line #87 is the last line in the script with a string literal.
Line #67 also has a string literal. If I remove line #87 the error becomes the same only now on line #67.
The Copy-Item line sets up the problem which is only reported at the last closed string literal closest to the end of the script.
PS C:\scripts> .\_addSite.ps1
At C:\scripts\_addSite.ps1:87 char:51
+ $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")
+ ~~
The string is missing the terminator: ".
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : TerminatorExpectedAtEndOfString
After posting this question, I took the boiled down script I wrote for this question and found it wasn't creating the error. So I slowly cut-and-paste little sections from the broken script into this question's version. Then re-ran the question's script each time. And always without error.
What changed? I closed and re-opened the PS console between giving up on a broken script and starting on this question. And now neither the question's script nor the broken version have a problem.
Probable solution? There was something in the previous PS console environment that was the root cause and this was flushed out by closing the console. How lovely.
Thanks everyone for your remarks

PowerShell App-V 5.0 SP3 server install

I'm trying to make this script work which automates App-V 5.0 installation using PowerShell. I'm installing it on Windows Server 2012 R2 With SQL 2012. Whenever it reaches Invoke-Expression $installappv, nothing happens. I can see the setup file start for a few seconds in task manager, but nothing gets installed. Please help.
.\AppVInstall\AppVServer\appv_server_setup.exe /layout
$appvconf = Get-Content .\AppVInstall\AppVServer\AppV_Conf.ini
$appvparameters = $appvconf -join " "
$installappv = ".\AppVInstall\AppVServer\appv_server_setup.exe" + " " + $appvparameters
Invoke-Expression $installappv
This is the contents of the file ".\AppVInstall\AppVServer\AppV_Conf.ini"
/QUIET
/ACCEPTEULA
/MANAGEMENT_SERVER
/MANAGEMENT_ADMINACCOUNT="XXXX.local\XXXXX"
/MANAGEMENT_WEBSITE_NAME="Microsoft App-V Management Service"
/MANAGEMENT_WEBSITE_PORT="80"
/DB_PREDEPLOY_MANAGEMENT
/MANAGEMENT_DB_SQLINSTANCE_USE_DEFAULT
/MANAGEMENT_DB_NAME="AppVManagement"
/PUBLISHING_SERVER /PUBLISHING_MGT_SERVER="testappvsvr.XXXX.local:80";
/PUBLISHING_WEBSITE_NAME="Microsoft AppV Publishing Service"
/PUBLISHING_WEBSITE_PORT="81"
Invoke-Expression is treating your string like 2 commands because of the semi-colon.
Consider the following statements.
Example 1
PS C:\temp> Invoke-Expression "echo test;stuff test"
test
stuff : The term 'stuff' is not recognized as the name of a cmdlet, function, ....output truncated...
Example 2
PS C:\temp> Invoke-Expression "echo 'test;stuff test'"
test;stuff test
In the first example the semicolon is not escaped or encased in quotes. It is a line terminator in PowerShell so it is treating 'stuff test' as its own command stuff with test as an argument. I don't have a cmdlet or exe called stuff so I get an error. I think that's what happening to you. A chunk of your parameters are not being sent to appv_server_setup.exe .
In the second example the semicolon is in single quote so the entire string is output on one line.
I don't know if it needs to be there but that semicolon has to be addressed somehow so that Invoke-Expression does not see it all by its lonesome.
Perhaps you can wrap all the arguments in one set of quotes.
$appvparameters = "'$($appvconf -join "' '")'"
#Matt I figured out the problem. The setup doesn't except changes to the default port numbers from the INI. Those parameters must be changed after the install. Thanks for your help Matt.