How to change powershell "pwsh" to STA ApartmentState - powershell

I'm trying to port some scripts from poweshell 5.0 to the new pwsh powershell 6 and i've noticed that there is no -sta parameter anymore. How can I set the ApartmentState of pwsh? I can;t find anything about it and it looks like it's defined in compile time to be either mta or sta depending on the target plattform. Am i right?
C:\WINDOWS\system32>pwsh -sta
The argument '-sta' is not recognized as the name of a script file. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
C:\WINDOWS\system32>powershell -sta
Windows PowerShell
Copyright (C) Microsoft Corporation. All rights reserved.

Since the ...core components are designed to work across multiple platforms I think you are going to find windows-specific concepts are not included. If you need cross-platform compatibility you will need to find another way. If you don't use powershell and realize that it is going to slowly fall behind in available features as pwsh move ahead.

Related

Suppress "Try the new cross-platform PowerShell https://aka.ms/pscore6"

I don't mind a bit of Microsoft marketing, but this is annoying when I just want a clean PowerShell prompt. Has anyone found a way of suppressing just the Try the new cross-platform PowerShell https://aka.ms/pscore6 on opening PowerShell, without removing the basic copyright message Windows PowerShell, Copyright (C) Microsoft Corporation. All rights reserved.? I've googled around a lot but found no answer (I know there is a way to suppress everything, but I just want rid of that pscore6 advert only).
Since Windows Terminal 1.0 is released, you can use it instead.
In settings add a flag -NoLogo as shown below:
"list": [
{
// Make changes here to the powershell.exe profile.
"guid": "{61c54bd-c2c6-5271-96e7-009a87ff44bf}",
"name": "Windows PowerShell",
"commandline": "powershell.exe -NoLogo",
"hidden": false
},
You can get rid of the copyright banner by starting powershell from running this in cmd:
Powershell.exe -NoLogo -NoExit
-NoExit is not necessary as #Albin said, and you could create a desktop shortcut/batch file from it.
This message is part of the resource string embedded in Microsoft.PowerShell.ConsoleHost in the ManagedEntranceStrings.resources resource. The full message is
Copyright (C) Microsoft Corporation. All rights reserved.
Try the new cross-platform PowerShell https://aka.ms/pscore6
This is one string, not two, and there is no logic for picking a different banner.
Because the string is read as a resource, in theory you could create a new resource assembly and put it in C:\Windows\System32\WindowsPowerShell\v1.0\en-US. In practice you can't (even if you'd be willing to put new files in a system directory), because the main assembly is strong-named and installed in the GAC, which means you can't produce a satellite assembly that will load since you don't have the private key required for signing. It does, however, work -- I verified this by building such an assembly with delayed signing, but obviously that's not really a workable idea on a production system.
Replace command line argument in settings.json with this:
"commandline": "powershell.exe -NoLogo -NoExit -Command Write-Host Windows PowerShell`nCopyright `(C`) Microsoft Corporation. All rights reserved.`n",
It disables original text, and writes what we need instead.
If you want to write something else, use `n for new lines, and don't forget to add ` for escaping reserved symbols, like parentheses.
Different language example:
"commandline": "powershell.exe -NoLogo -NoExit -Command Write-Host Windows PowerShell`n`(C`) Корпорация Майкрософт `(Microsoft Corporation`). Все права защищены.`n",
Suppressing messages in IntelliJ IDEA (i.e. WebStorm).
Had the same messages in the terminal windows of my WebStorm.
You can suppress these messages by adding the -NoLogo flag to the Shell Path for the Terminal Emulator.
Go to the settings for configuring the Terminal Emulator by clicking:
File menu -> Settings -> Tools -> Terminal.
Click to confirm editing these settings if needed and then change the Shell path accordingly to:
powershell.exe -NoLogo
When you next time start your IntelliJ IDEA the terminal windows will be clean.
This message means "you are using the old version of powershell". You must update it with commands and software.
When I updated powershell, this message never came again.

There is no Get-GacAssembly cmdlet

Windows 8.1, PowerShell 4. I'm wanting to use PS to manage the GAC. I find lots of references to Get-GacAssembly for reading a list, getting detailed info, etc.
But running PS as administrator, and PS ISE, I get an error:
>
The term 'Get-GacAssembly' is not recognized as the name of a cmdlet
Do I need to CD to somewhere? How would I discover where to go to find the cmdlets?
The general answer to your question is that you must first install the module (by adding relevant files to Documents\Powershell\Modules or Windows\System32\WindowsPowershell\v1.0\Modules. Then, you should use Import-Module to load the cmdlets. Cmdlets in Windows\System32\WindowsPowershell\v1.0\Modules should be loaded by default. Script modules (e.g., modules that export functions) require at least RemoteSigned execution settings to run.

How can I include KB2670838 in an installer with InstallShield 2013?

I'm using InstallShield 2013 to make a Basic MSI installer for an application that requires Windows Platform Update KB2670838.
For .NET frameworks and other requirements, I select them in InstallShield in the Redistributables section. KB2670838 is not available.
If I download KB2670838 from Microsoft I get a .msu file. Can that be included in the installer somehow so that it automatically installs if needed? If not, is there a way to stop the install and tell the user that "KB2670838 is required but not installed. Get it here..."?
In InstallShield, you should typically deliver this sort of update as a prerequisite (Tools > Prerequisite Editor), or as a package included in a Suite (reference [SystemFolder]wusa.exe to install an .msu file). In both cases this keeps the redistributable installation logically separate from your package's installation, while providing your users a single installer experience.
Glytzhkof mentions several really good points about how to determine whether the update has been installed. You will want to incorporate these into your conditions (on the prerequisite or suite package), and also into detecting the update or lack thereof in your .msi package so it can abort if the required update has not been installed by the time the .msi is launched.
The Add/Remove programs list in the registry could help you get a rough idea of what's installed:
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
It seems this doesn't provide a full list of what is installed though: http://social.technet.microsoft.com/Forums/windows/en-US/d913471a-d7fb-448d-869b-da9025dcc943/where-does-addremove-programs-get-its-information-from-in-the-registry?forum=w7itprogeneral
Another way may be to use the file information from the knowledge base article:
http://support.microsoft.com/kb/2670838/en (For More Information : File Information) and use WIX / MSI's AppSearch / LaunchCondition feature. That should do the trick, though I find the syntax a bit counterintuitive.
Another approach is to write a custom action and combine these two sources (add /remove entry and file info). Such a custom action will make no changes to the system, and is hence less problematic than other custom actions that cause rollback-problems. I find it easier to test and maintain a custom action in case there are further prerequisites that are needed at some point. This is a matter of taste though. I just find it easier to run a prerequisite script against a selection of files to test that it identifies them correctly and run through as expected than to keep running the MSI file for every test.
Here is a similar question with some pointers from superuser.com:
https://superuser.com/questions/521175/determine-if-windows-hotfix-has-been-applied
And another link to serverfault.com (system administration site). Nice approach using PowerShell which can certainly be migrated to a custom action:
https://serverfault.com/questions/312778/determine-if-user-has-hotfix-981889-installed
Even more serverfault.com stuff involving update.exe, WMI and a Powershell script to view all installed hotfixes:
https://serverfault.com/questions/263847/how-can-i-query-my-system-via-command-line-to-see-if-a-kb-patch-is-installed . Recommended read. Microsoft: http://technet.microsoft.com/en-us/library/hh849836.aspx
PSInfo appears to be able to show installed hotfixes: http://technet.microsoft.com/en-us/sysinternals/bb897550
#Glytzhkof Good point. So how do I get InstallShield to abort and give the user a nice message so they know what to do? – shoelzer 1 hour ago
I will just add a new answer then - too long to write in a comment.
Locate the file details you need to scan for under "For More
Information : File Information" in this kdb article:
http://support.microsoft.com/kb/2670838/en
Select a few files to scan for and add as file searches in Installshield (see below screenshot). You specify a property for each file (FILE1FOUND, FILE2FOUND, FILE3FOUND, etc...), and if the search matches the file details (version, size, date, etc...) the property is set to the full path of the file. Otherwise the property is undefined or set to a default value (screenshot shows predefined search, and not file search, but you get the idea).
Finally you add LaunchCondition entries for each file to ensure that all files you have selected to check are the correct version or higher. I guess this is in Prerequisites or similar - I can't recall. Open the compiled MSI and check that it looks like the LaunchConditon table.
For the record: (not part of above suggestion)
Personally I am in favor of coding a single script for complex logic like this to ensure the logic can be inspected as a whole and crucially tested as a whole outside the MSI file. It is also good to add comments to such code to explain what the script is checking, and why (helps corporate deployment). A script can be run through dozens of tests against the machine directly without recompiling the MSI. This can save a lot of time if the logic is complex. If you write a compiled dll you can show a message box and attach the visual studio debugger to the msiexec.exe process (client or server depending on what context your custom action is running in) and step-through the code whilst embedded in the MSI, but this seems out of scope for your scenario. Just want to mention it for other people who might read this. Also check Stefan Kruger's installsite.com for more information on complex setup debugging like this.
It is important to note that scripting is never generally recommended for scenarios where the script makes changes to the system - if there is a built-in MSI way to achieve the same result. The reason for this is that a script that makes changes to a machine will need a separate rollback-operation to be specified for it for the MSI to follow best practice. This can be a spectacular amount of work and complexity to get right. The above script would only check system conditions, so there is no need for rollback support.
Let me try and add a reference style answer since my other answer is a bit organic to say the least at this point - I will leave it in since it contains an MSI discussion. See MSI recommendation in the middle section below:
WMI:
wmic qfe where "HotfixID = 'KB973687'"
PowerShell: (just get-hotfix for full list)
get-hotfix | findstr "981889"
SystemInfo (remove arguments for list format):
systeminfo /fo csv
PSInfo (seems to not list everything on all machines, and may not run silently properly):
PSinfo -h
Registry (apparently not complete list of hotfixes):
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
For MSI custom action use, I would actually use a custom action that inspects file versions as explained in my other answer. Very reliable, and takes into account that the hotfix may be deprecated whilst the files are still up to date.
References:
Recommended: https://serverfault.com/questions/263847/how-can-i-query-my-system-via-command-line-to-see-if-a-kb-patch-is-installed
How do I get a list of installed updates and hotfixes?
SystemInfo: https://serverfault.com/questions/334552/how-to-check-that-a-known-windows-vulnerability-has-been-patched
http://windowsitpro.com/scripting/get-hotfix-information-quickly-wmic
https://serverfault.com/questions/69467/list-all-hotfixes-applied-to-windows-server
wmic in general: http://technet.microsoft.com/en-us/library/bb742610.aspx
Recommended: http://www.dedoimedo.com/computers/windows-wmic.html
http://www.techsupportalert.com/content/quick-and-easy-way-list-all-windows-updates-installed-your-system.htm
http://pario.no/2011/06/19/list-installed-windows-updates-using-wmic/
Had the same issue and solved it by adding a prerequisite of a PowerShell script and a batch file to execute it.
The pre.ps1 file looks something like this:
function TestConnection
{
Test-Connection -ComputerName "8.8.8.8" -Quiet
}
get-hotfix -id KB2670838
if(!$?){
#SourceURI = "https://download.microsoft.com/download/1/4/9/14936FE9-4D16-4019-A093-5E00182609EB/Windows6.1-KB2670838-x64.msu";
#$FileName = $SourceURI .Split('/')[-1]
#$BinPath = Join-Path $DownloadPath -ChildPath $FileName
Invoke-Webrequest -Uri $SourceURI -OutFile $BinPath
#Start-Process -FilePath $BinPath -ArgumentList "/q /norestart" -Wait -NoNewWindow
}
the pre.cmd file looks something like this:
#echo off
::set PS_FILE=%~dp0Prerequisite.ps1
set PS_FILE=%~dpn0.ps1
set PS_EXEC_PATH=%SystemRoot%\sysnative\WindowsPowerShell\v1.0\
set PS_EXEC_PATH=%SystemRoot%\System32\WindowsPowerShell\v1.0\
::set PS_EXEC_PATH=%SystemRoot%\SysWOW64\WindowsPowerShell\v1.0\
set PS_EXEC_PATH=
set PS_EXEC=%PS_EXEC_PATH%powershell.exe
echo %PS_EXEC%
echo %PS_FILE%
::%PS_EXEC% -file %PS_FILE% set-executionpolicy remotesigned
::%PS_EXEC% -NoProfile -ExecutionPolicy Bypass -Command "& '%PS_FILE%'"
::This is with admin rights
%PS_EXEC% -NoProfile -Command "& {Start-Process PowerShell.exe -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%PS_FILE%""' -Verb RunAs}"
::pause

Powershell: Add Snap-in (install util managementCmdlets.dll)

Howsit!
I'm in need of a solution, I need to add a snap-in - and can't.
I'm attempting to run processes on my company's share-point site
Thus the real error: Get-SPSite: 'Get SPSite' is not recognized as the name of a cmdlet, function, script file,..
Need to Add a snap-in to solve this (working systematically from example 3: from the site http://technet.microsoft.com/en-us/library/hh849705(v=wps.620).aspx
I am stuck on fourth command (not sure which installutil to select or download?):
It does not exist/ cannot find the installutil: ManagementCmdlets.dll
- does anyone know where to download this?
I tried a file called Microsoft.PowerShell.Commands.Management.dll however
the installation failed, and the rollback has been performed
Powershell code is below (if this may help):
PS C:\Users\Gisintern1.PPF> get-pssnapin -registered
PS C:\Users\Gisintern1.PPF> set-alias installutil $env:windir\Microsoft.NET\Framework\v2.0.50727\installutil.exe
PS C:\Users\Gisintern1.PPF> installutil C:\Dev\Management\ManagementCmdlets.dll
**Microsoft (R) .NET Framework Installation utility Version 2.0.50727.5420
Copyright (c) Microsoft Corporation. All rights reserved.
Exception occurred while initializing the installation:
System.IO.FileNotFoundException: Could not load file or assembly 'file:///C:\Dev\Management\ManagementCmdlets.dll' or one of its dependencies.
The system cannot find the file specified..
Per that site, it appears that the ManagementCmdlets.dll is a fictitious snap-in, only used by the example to show how the process works.
I haven't tried managing SharePoint via PowerShell myself, but I did a little digging. From the looks of it, the Get-SPSite snap-in is installed along with SharePoint 2010, and I would assume some other versions of it as well. On the same server that SharePoint is installed on I would try to run:
Add-PsSnapin Microsoft.SharePoint.PowerShell
Get-SPSite
Alternatively (and per https://blogs.technet.com/b/heyscriptingguy/archive/2010/09/20/get-started-managing-sharepoint-2010-with-powershell-cmdlets.aspx) there may be a "SharePoint Management Shell" that can be started which would seem to load the proper snap-in(s) automatically into an otherwise normal PowerShell environment.
Hopefully one of these two ideas helps you out.

Why is my locally-created script not allowed to run under the RemoteSigned execution policy?

Since this question continues to attract responses that are either
refuted by the question body or don't address the actual problem,
please read this simple summary of what you need to know:
This is not a "Why won't my default installation of PowerShell run scripts?" question.
This is not a "Why won't my installation of PowerShell run scripts downloaded from the internet?" question.
The question is why the RemoteSigned execution policy is preventing script execution when it shouldn't.
RemoteSigned is the only execution policy I want to use. I am aware that other, less-restrictive policies are available. If
those policies were acceptable substitutes I would have just used them
instead and this question wouldn't exist.
The execution policy is already set to RemoteSigned. Changing it from RemoteSigned to RemoteSigned is not a solution.
The script file is created and stored locally.
The script file is not blocked. The script file was never blocked (see previous point).
The script file cannot be unblocked because there is nothing to unblock (see previous point).
The script file is (attempted to be) executed by an administrator.
Windows PowerShell is the only application involved. Not Windows PowerShell ISE nor Command Prompt nor any other tools or
editors are relevant.
The cause of the problem has already been identified (see accepted answer). After nearly 8 years, I think all other obvious
explanations, whether applicable or not, have been posted, too. If
you think otherwise then please read the question and existing
answers in their entirety before adding yours.
I am using Windows PowerShell 2.0 on 64-bit Windows 7 Professional. I have a script on my Desktop that causes the following error when I try to run it:
File C:\Users\UserName\Desktop\Script.ps1 cannot be loaded. The file C:\Users\UserName\Desktop\Script.ps1 is not digitally signed. The script will not execute on the system. Please see "get-help about_signing" for more details..
At line:1 char:54
+ C:\Users\UserName\Desktop\TestGetWindowsUpdateLog.ps1 <<<<
+ CategoryInfo : NotSpecified: (:) [], PSSecurityException
+ FullyQualifiedErrorId : RuntimeException
I am both a domain administrator and a local administrator, and if I run Get-ExecutionPolicy -List, I can see that the Group Policy Object I created to configure PowerShell is correctly applying the RemoteSigned execution policy at the machine level:
Scope ExecutionPolicy
----- ---------------
MachinePolicy RemoteSigned
UserPolicy Undefined
Process Undefined
CurrentUser Undefined
LocalMachine Undefined
I created the script myself in Notepad, and used the Sysinternals' streams utility and the file Properties dialog to confirm that the script is not being treated as having come from the internet. If I copy the script to a network share on a domain server, then it's allowed to execute. If I run Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope LocalMachine then the local script is still not allowed to execute, which makes sense since the execution policy at the MachinePolicy scope will take precedence.
As documented by about_Execution_Policies(current; at time of question), the RemoteSigned policy means:
Scripts can run.
Requires a digital signature from a trusted publisher on scripts and configuration files that are downloaded from the Internet
(including e-mail and instant messaging programs).
Does not require digital signatures on scripts that you have run and that you have written on the local computer (not downloaded from
the Internet).
Risks running unsigned scripts from sources other than the Internet and signed, but malicious, scripts.
My script is not signed, but since it is both created and executed locally, it should satisfy the third bullet point above. Therefore...
Why is my script not being allowed to run?
Why does PowerShell complain that my script "is not digitally signed" when that requirement should only apply to files from the Internet?
Why does PowerShell no longer care about the script not being signed when it's run from a network share?
Some things to check:
Can you change to unrestricted?
Set-ExecutionPolicy Unrestricted
Is the group policy set?
Computer Configuration\Administrative Templates\Windows Components\Windows PowerShell
User Configuration\Administrative Templates\Windows Components\Windows PowerShell
Also, how are you calling Script.ps1?
Does this allow it to run?
powershell.exe -executionpolicy bypass -file .\Script.ps1
Is the file being blocked? I had the same issue and was able to resolve it by right clicking the .PS1 file, Properties and choosing Unblock.
When you run a .ps1 PowerShell script you might get the message saying “.ps1 is not digitally signed. The script will not execute on the system.”
To fix it you have to run the command below to run Set-ExecutionPolicy and change the Execution Policy setting.
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass
I have found out when running a PS1 file for a Mapped drive to Dropbox that I'm always getting this error. When opening up properties for the PS1 there is no "Unblock".
The only thing that work for me is
powershell.exe -executionpolicy bypass -file .\Script.ps1
I finally tracked this down to .NET Code Access Security. I have some internally-developed binary modules that are stored on and executed from a network share. To get .NET 2.0/PowerShell 2.0 to load them, I had added a URL rule to the Intranet code group to trust that directory:
PS> & "$Env:SystemRoot\Microsoft.NET\Framework64\v2.0.50727\caspol.exe" -machine -listgroups
Microsoft (R) .NET Framework CasPol 2.0.50727.5420
Copyright (c) Microsoft Corporation. All rights reserved.
Security is ON
Execution checking is ON
Policy change prompt is ON
Level = Machine
Code Groups:
1. All code: Nothing
1.1. Zone - MyComputer: FullTrust
1.1.1. StrongName - ...: FullTrust
1.1.2. StrongName - ...: FullTrust
1.2. Zone - Intranet: LocalIntranet
1.2.1. All code: Same site Web
1.2.2. All code: Same directory FileIO - 'Read, PathDiscovery'
1.2.3. Url - file://Server/Share/Directory/WindowsPowerShell/Modules/*: FullTrust
1.3. Zone - Internet: Internet
1.3.1. All code: Same site Web
1.4. Zone - Untrusted: Nothing
1.5. Zone - Trusted: Internet
1.5.1. All code: Same site Web
Note that, depending on which versions of .NET are installed and whether it's 32- or 64-bit Windows, caspol.exe can exist in the following locations, each with their own security configuration (security.config):
$Env:SystemRoot\Microsoft.NET\Framework\v2.0.50727\
$Env:SystemRoot\Microsoft.NET\Framework64\v2.0.50727\
$Env:SystemRoot\Microsoft.NET\Framework\v4.0.30319\
$Env:SystemRoot\Microsoft.NET\Framework64\v4.0.30319\
After deleting group 1.2.3....
PS> & "$Env:SystemRoot\Microsoft.NET\Framework64\v2.0.50727\caspol.exe" -machine -remgroup 1.2.3.
Microsoft (R) .NET Framework CasPol 2.0.50727.9136
Copyright (c) Microsoft Corporation. All rights reserved.
The operation you are performing will alter security policy.
Are you sure you want to perform this operation? (yes/no)
yes
Removed code group from the Machine level.
Success
...I am left with the default CAS configuration and local scripts now work again. It's been a while since I've tinkered with CAS, and I'm not sure why my rule would seem to interfere with those granting FullTrust to MyComputer, but since CAS is deprecated as of .NET 4.0 (on which PowerShell 3.0 is based), I guess it's a moot point now.
If the file is copied from a network location, that is, another computer, Windows might have blocked that file. Right click on the file and click on the unblock button and see if it works.
What works for me was right-click on the .ps1 file and then properties. Click the "UNBLOCK" button. Works great fir me after spending hours trying to change the policies.
Select your terminal Command prompt instead of Power shell. That should work.
This is an IDE issue. Change the setting in the PowerShell GUI. Go to the Tools tab and select Options, and then Debugging options. Then check the box Turn off requirement for scripts to be signed. Done.
Please make a backup for the script.bs1 file
What works for me was deleting the script.bs1 file and running the execution command.
I was having the same issue and fixed it by changing the default program to open .ps1 files to PowerShell. It was set to Notepad.
Try running the Powershell GUI as Administrator
This occurs due to Powershell execution policy is set to restricted by default which prevents execution PowerShell scripts and protects from running malicious scripts.
You can change execution scope for specific scope by running the following command
Set-ExecutionPolicy -Scope Process
Run below 2 commands in PowerShell window
Set-ExecutionPolicy unrestricted
Unblock-File -Path D:\PowerShell\Script.ps1