Execute a PowerShell script from a Windows command prompt - powershell

I have the current version of 64 bit Windows 10 installed.
I can open a Windows PowerShell window and enter the following command to execute my PowerShell script. The script execute without error.
PS C:\Users\david\Desktop\test> ./messagebox.ps1
I want to execute the same script from a Windows Command Prompt window. When I enter the follow command, I get the displayed error messages.
C:\Users\david\Desktop\test>powershell -ExecutionPolicy Bypass -file messagebox.ps1
At C:\Users\david\Desktop\test\messagebox.ps1:81 char:14
+ Class Form : System.Windows.Forms.Form
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
Unable to find type [System.Windows.Forms.Form].
At C:\Users\david\Desktop\test\messagebox.ps1:102 char:21
+ return [System.Windows.Forms.MessageBox]::Show($messsage, ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unable to find type [System.Windows.Forms.MessageBox].
At C:\Users\david\Desktop\test\messagebox.ps1:108 char:21
+ return [System.Windows.Forms.MessageBox]::Show($messsage, ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Unable to find type [System.Windows.Forms.MessageBox].
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : TypeNotFound
The script includes the following lines which I thought would include the correct assembly.
$n = new-object System.Reflection.AssemblyName("System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")
[System.AppDomain]::CurrentDomain.Load($n) | Out-Null

You did not post enough code to actually reproduce the issue, but this works for me:
Add-Type -AssemblyName System.Windows.Forms | Out-Null
[System.Windows.Forms.MessageBox]::Show("Hello World")
I assume you can extend this to whatever version of Show() you need.
See also PowerShell Magazine

Related

Powershell not always running ScriptsToProcess on import

After using Install-Module to install powershell-yaml I had about a week of use before I came in one morning to it not loading YamlDotNet properly.
Now if I try to use ConvertFrom-Yaml before manually running Import-Module powershell-yaml I get the the following error:
PS C:\Users\user> "---" | ConvertFrom-Yaml
New-Object : Cannot find type [YamlDotNet.RepresentationModel.YamlStream]: verify that the assembly containing this type is loaded.
At C:\Program Files\WindowsPowerShell\Modules\powershell-yaml\0.3.1\powershell-yaml.psm1:24 char:23
+ ... $yamlStream = New-Object "YamlDotNet.RepresentationModel.YamlStream"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidType: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : TypeNotFound,Microsoft.PowerShell.Commands.NewObjectCommand
You cannot call a method on a null-valued expression.
At C:\Program Files\WindowsPowerShell\Modules\powershell-yaml\0.3.1\powershell-yaml.psm1:25 char:9
+ $yamlStream.Load([System.IO.TextReader] $stringReader)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Previously (and on most systems) this worked fine. If I run a manual Import-Module before calling the function it works fine:
PS C:\Users\user> Import-Module powershell-yaml
PS C:\Users\user> "---" | ConvertFrom-Yaml
PS C:\Users\user>
Both my and a coworker's machines started this behavior at about the same time. This morning my system started working properly again, but his is still exhibiting the behavior. We haven't been able to duplicate it on other machines.
I've narrowed it down to a script referenced in Powershell-Yaml manifest's ScriptsToProcess not being called during autoload, but runs fine during a manual Import-Module. On working machines the script in ScriptsToProcess is run in both cases. As a workaround we can force a module load by putting an Import-Module in our profile, ideally we'd like to find a root cause.
Import-Module -Verbose doesn't help, because calling Import-Module first always works.

Set the font type and size using the command prompt (or batch file)

I tried the solution given from: Specify the size of command prompt when executing a batch file
I ran:
powershell -command "&{set-executionpolicy remotesigned; Import-Module SetConsoleFont; Get-ConsoleFontInfo | Format-Table -AutoSize}"
But I get these errors, any ideas?
Set-ExecutionPolicy : Access to the registry key 'HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.PowerShell' is denied. At line:1 char:22 + &{set-executionpolicy <<<< remotesigned; Import-Module SetConsoleFont; Get-ConsoleFontInfo | Format-Table -AutoSize} + CategoryInfo : NotSpecified: (:) [Set-ExecutionPolicy], UnauthorizedAccessException + FullyQualifiedErrorId : System.UnauthorizedAccessException,Microsoft.PowerShell.Commands.SetExecutionPolicyCommand
Import-Module : The specified module 'SetConsoleFont' was not loaded because no valid module file was found in any module directory . At line:1 char:50 + &{set-executionpolicy remotesigned; Import-Module <<<< SetConsoleFont; Get-ConsoleFontInfo | Format-Table -AutoSize} + CategoryInfo : ResourceUnavailable: (SetConsoleFont:String) [Import-Module], FileNotFoundException + FullyQualifiedErrorId : Modules_ModuleNotFound,Microsoft.PowerShell.Commands.ImportModuleCommand
The term 'Get-ConsoleFontInfo' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spe lling of the name, or if a path was included, verify that the path is correct and try again. At line:1 char:86 + &{set-executionpolicy remotesigned; Import-Module SetConsoleFont; Get-ConsoleFontInfo <<<< | Format-Table -AutoSize} + CategoryInfo : ObjectNotFound: (Get-ConsoleFontInfo:String) [], CommandNotFoundException + FullyQualifiedErrorId : CommandNotFoundException
I have put the file SetConsoleFont.psm1 in
C:\Users\Adrian\Documents\WindowsPowerShell\Modules\SetConsoleFont
You say "You're not allowed to set the execution policy" well maybe I'm not, but it's my machine so why shouldn't I? I don't want to execute these commands as Administrator, just as a user, me (Adrian)
Another comment was to try set-executionpolicy bypass process
so I tried:
powershell -command "&{set-executionpolicy bypass process; set-executionpolicy remotesigned; Import-Module SetConsoleFont; Get-ConsoleFontInfo | Format-Table -AutoSize}"
But got even more red errors.
I have no idea what powershell is or how to use it, I just want to change the font from a batch file without hassle!
Try set-executionpolicy bypass process instead.
Also make sure you have put the module in a module path folder such as:
[yourprofile]\Documents\WindowsPowershell\Modules
I managed to get it working but only in a PowerShell console, and I had to run it as Administrator. However this is not practical for me for the following reasons:
I wish to change the font of new window seamlessly from a batch file, which will be run by users of the software. They may not have Administrator access and so cannot execute "set-executionpolicy remotesigned" which I needed to do to get it working.
Also this has to be done in a DOS batch file, so opening up a powershell window is not an option. It only works in a PowerShell window and not with the DOS "powershell -command" option.
So a partial answer.
If you want to change Execution Policy, it should be done in an elevated prompt.
And loading the module can be done by giving absolute path. Example is below.
Import-Module c:\users\testuser\desktop\SetConsoleFont.psm1 -Verbose
and we can bypass execution policy like below.
powershell.exe -executionpolicy bypass -command "${<your code>}"
Edit: The imported module will be available only in the scope of the script block.
here it is with in {}. So whatever cmdlets and functions in side the module should be executed in sided the scriptblock.
Regards,
Kvprasoon

Powershell scripts will not work with Jenkins plugin on Windows

I'm writing some pretty simple scripts in Powershell 32-bit and they are working fine.
For instance, I want to open internet explorer to a webpage and start typing in keys. The following code works fine when I run it in powershell ISE.
Add-Type –AssemblyName System.Windows.Forms
$url = "http://WebAddress"
$ie = New-Object -com "InternetExplorer.Application"
$ie.Navigate($url)
sleep 30
[System.Windows.Forms.SendKeys]::SendWait("{2}{tab}{H}{E}{L}{L}{O}")
I have downloaded a Windows PowerShell plugin and have executed the same code through it and received the following errors:
Building on master in workspace C:\Program Files\Jenkins\workspace\Jenkins Test
[Jenkins Test] $ powershell.exe -NonInteractive -ExecutionPolicy ByPass "& 'C:\WINDOWS\TEMP\hudson257018662776252417.ps1'"
New-Object : Creating an instance of the COM component with CLSID {0002DF01-000
0-0000-C000-000000000046} from the IClassFactory failed due to the following er
ror: 80004005.
At C:\WINDOWS\TEMP\hudson257018662776252417.ps1:4 char:17
+ $ie = New-Object <<<< -com "InternetExplorer.Application"
+ CategoryInfo : ResourceUnavailable: (:) [New-Object], COMExcept
ion
+ FullyQualifiedErrorId : NoCOMClassIdentified,Microsoft.PowerShell.Comman
ds.NewObjectCommand
You cannot call a method on a null-valued expression.
At C:\WINDOWS\TEMP\hudson257018662776252417.ps1:5 char:13
+ $ie.Navigate <<<< ($url)
+ CategoryInfo : InvalidOperation: (Navigate:String) [], RuntimeE
xception
+ FullyQualifiedErrorId : InvokeMethodOnNull
Exception calling "SendWait" with "1" argument(s): "Access is denied"
At C:\WINDOWS\TEMP\hudson257018662776252417.ps1:9 char:42
+ [System.Windows.Forms.SendKeys]::SendWait <<<< ("{2}{tab}{H}{E}{L}{L}{O}")
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : DotNetMethodException
Is there a reason why my code will not work through Jenkins like it does in Powershell? I tried some simple echo scripts which worked fine, but any more complex and it throws an error.
You may need to set execution policy once: https://technet.microsoft.com/library/hh849812.aspx
Set-ExecutionPolicy Unrestricted
Run PowerShell as admin and run that command. There may be security concerns using Unrestricted. But if it works, read the link above and find the policy that works best in your context. Options are (copy/pasted from the link):
Restricted. Does not load configuration files or run scripts. Restricted is the default execution policy.
AllSigned. Requires that all scripts and configuration files be signed by a trusted publisher, including scripts that you write on
the local computer.
RemoteSigned. Requires that all scripts and configuration files downloaded from the Internet be signed by a trusted publisher.
Unrestricted. Loads all configuration files and runs all scripts. If you run an unsigned script that was downloaded from the Internet,
you are prompted for permission before it runs.
Bypass. Nothing is blocked and there are no warnings or prompts.
Undefined. Removes the currently assigned execution policy from the current scope. This parameter will not remove an execution policy
that is set in a Group Policy scope.

Compress folder using Powershell from SQLSERVER runtime

I need to zip a folder using powershell from within SQLPS runtime. I tried the following from PS SQLSERVER:\> prompt:
$dest = "C:\SomePath\FolderToBeZipped"
$zipfile = $dest + ".zip"
Add-Type -assembly "system.io.compression.filesystem"
[io.compression.zipfile]::CreateFromDirectory($dest,$zipfile)
When run, I get the below error :
Add-Type : Cannot add type. The assembly 'system.io.compression.filesystem' could not be found.
At C:\SomePath\Compress.ps1:10 char:9
+ Add-Type <<<< -assembly "system.io.compression.filesystem"
+ CategoryInfo : ObjectNotFound: (system.io.compression.filesystem:String) [Add-Type], Exception
+ FullyQualifiedErrorId : ASSEMBLY_NOT_FOUND,Microsoft.PowerShell.Commands.AddTypeComm
and
Add-Type : Cannot add type. One or more required assemblies are missing.
At C:\SomePath\Compress.ps1:10 char:9
+ Add-Type <<<< -assembly "system.io.compression.filesystem"
+ CategoryInfo : InvalidData: (:) [Add-Type], InvalidOperationException
+ FullyQualifiedErrorId : ASSEMBLY_LOAD_ERRORS,Microsoft.PowerShell.Commands.AddTypeCommand
But if I exit out of PS SQLSERVER:\> runtime and execute from normal PS command prompt it is able to compress successfully. Please help how to compress from SQLSERVER powershell runtime. I even tried to invoke a separate .ps1 script (for compressing) using Invoke-Expression from within PS SQLSERVER:\> runtime, but failed. Please help

Script Only Runns Sucessfully 50-60% of the time

I'm sending a zip and the powershell script to computers in our organisation through our management software and then executing the powershell script through command prompt. The script unzips the folder, installs a program and adds some registry keys to the registry.
If the machine doesnt say that a policy is preventing execution of the script, it runs as expected, the program is installed and the registry keys are imported. But if it does give the warning and I set the policy to unrestricted I get the below error error. I am on Windows 8.1 and using Powershell 4.0
Id not be found.
At C:\Temp\tps1.ps1:5 char:9
+ Add-Type <<<< -assembly "system.io.compression.filesystem"
+ CategoryInfo : ObjectNotFound: (system.io.compression.filesyste
m:String) [Add-Type], Exception
+ FullyQualifiedErrorId : ASSEMBLY_NOT_FOUND,Microsoft.PowerShell.Commands
.AddTypeCommand
Add-Type : Cannot add type. One or more required assemblies are missing.
At C:\Temp\tps1.ps1:5 char:9
+ Add-Type <<<< -assembly "system.io.compression.filesystem"
+ CategoryInfo : InvalidData: (:) [Add-Type], InvalidOperationExc
eption
+ FullyQualifiedErrorId : ASSEMBLY_LOAD_ERRORS,Microsoft.PowerShell.Comman
ds.AddTypeCommand
Unable to find type [io.compression.zipfile]: make sure that the assembly conta ining this type is loaded.
At C:\Temp\tps1.ps1:7 char:25
+ [io.compression.zipfile] <<<< ::ExtractToDirectory($BackUpPath, $destination) + CategoryInfo : InvalidOperation: (io.compression.zipfile:String
) [], RuntimeException
+ FullyQualifiedErrorId : TypeNotFound
anyone have any ideas?
on systems where .NET 4.5 is not installed, use:
$BackUpPath = "C:\Temp\Install.zip"
$Destination = "C:\Temp"
$shell_app=new-object -com shell.application
$zip_file = $shell_app.namespace($BackUpPath )
$destination = $shell_app.namespace($Destination )
$destination.Copyhere($zip_file.items(),0x4)
on systems with.NET 4.5 use:
Add-Type -assembly "system.io.compression.filesystem"
[io.compression.zipfile]::ExtractToDirectory($BackUpPath, $destination)
A script on technet combines the above 2 methods.
On PowerShell V5 , this is much simplified:
Expand-Archive $BackUpPath -destination $Destination
there are other ways to unzip files using 3rd party libraries such as 7-zip, etc but that creates a dependency.
Note: Powershell execution policies can be set using group policy. see link here