ruby exec powershell windows - ruby

When I run the following in ruby:
`powershell.exe -executionpolicy unrestricted -command get-module -listavailable`
...the result I get is different from if I just run cmd and execute:
powershell.exe -executionpolicy unrestricted -command get-module -listavailable
How can I fix this, so I can yield the same result?

Yes. The fix apparently is the sysnative alias. Use:
C:/windows/sysnative/windowspowshell/v1.0/powershell.exe
Instead of syswow64 or system32 or none.
For more info see: http://msdn.microsoft.com/en-us/library/windows/desktop/aa384187(v=vs.85).aspx

Related

Running SendKeys commands from a .lnk (shortcut) with powershell doesn't work

I'm playing around with SendKeys and powershell. I tried to close the active window with SendKeys (ALT + F4) after running a shortcut. I got this working with adding the following command to the Target field of a Windows shortcut(.lnk):
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -File "C:\Users\user\Documents\TEST\test.ps1"
Code in test.ps1:
(New-Object -ComObject Wscript.Shell).SendKeys("%{F4}")
When I run the shortcut the active windows closes. Now I wanted to make this work without .ps1 script. I tried to run the powershell command from the Target field of the shortcut and that didn't work.
The commands I added to the shortcut Target field that didn't work:
$ C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe $wshell = New-Object -ComObject wscript.shell; $wshell.SendKeys("%{F4}")
$ C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe "$wshell = New-Object -ComObject wscript.shell; $wshell.SendKeys("%{F4}")"
$ C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe (New-Object -ComObject Wscript.Shell).SendKeys("%{F4}")
$ C:\Windows\System32\cmd.exe /c powershell.exe -noprofile -executionpolicy bypass $wshell = New-Object -ComObject wscript.shell; $wshell.SendKeys("%{F4}")
$ C:\Windows\System32\cmd.exe /c powershell.exe -noprofile -executionpolicy bypass "$wshell = New-Object -ComObject wscript.shell; $wshell.SendKeys("%{F4}")"
$ C:\Windows\System32\cmd.exe /c powershell.exe -noprofile -executionpolicy bypass (New-Object -ComObject Wscript.Shell).SendKeys("%{F4}")
What I'm doing wrong in the commands above? I need to use a different syntax when I run powershell commands from Shortcuts?
What I'm doing wrong in the commands above?
You're calling powershell.exe, the Windows PowerShell CLI, from outside PowerShell, such as in the no-shell context in which shortcut-file command lines are executed.
For troubleshooting such command lines, use -noexit as the first powershell.exe parameter in order to keep the resulting PowerShell session open, which allows you to see any error message.
The implied CLI parameter of powershell.exe is -Command (-c), which treats all subsequent arguments as tokens of a piece of PowerShell code to execute.
However, any unquoted " characters are stripped beforehand, during PowerShell's command-line processing.
In order to pass " characters through as part of a PowerShell command being passed to the PowerShell CLI via (possibly implied) -Command (-c), you need to escape them as \" (sic)
Additionally, for full robustness, it is best to pass the entire PowerShell command inside a single (unescaped) "..." string.
Therefore:
powershell.exe -noprofile -executionpolicy bypass "(New-Object -ComObject Wscript.Shell).SendKeys(\"%{F4}\")"
However, given that, in the context of your PowerShell command, a single-quoted string ('...') to represent the key combination %{F4} argument will do (and is arguably preferable, given that you only need "..." quoting in PowerShell for string interpolation), you can simplify to:
powershell.exe -noprofile -executionpolicy bypass "(New-Object -ComObject Wscript.Shell).SendKeys('%{F4}')"
The issue here is that the commands you are attempting to execute aren't being passed to the powershell exe correctly.
The below works for me in the terminal and also in the shortcut field:
powershell.exe -command "$wshell = New-Object -ComObject wscript.shell; $wshell.SendKeys('%{F4}')"
If the command you are attempting to execute does not need to interpolate any variables in its strings etc. (yours does not) then you can test your statements by executing them in a powershell session (Note that i have switched to single quotes ' for $wshell.SendKeys('%{F4}')"). Your examples would yield some errors and so you know it wont work in the shortcut.
and to give an example for the rest of your attempts (full path removed for brevity)
powershell.exe -command "(New-Object -ComObject Wscript.Shell).SendKeys('%{F4}')"
powershell.exe -noprofile -executionpolicy bypass -command "$wshell = New-Object -ComObject wscript.shell; $wshell.SendKeys('%{F4}')"

How can I change directory directly from the windows run prompt?

How can I change the current directory from the the windows run prompt when we initialize powershell as powershell. For eg: powershell --someArgs
You can use Set-Location or Cd
Powershell.exe -noexit -Command "CD 'C:\Test\'"
Powershell.exe -noexit -Command "Set-Location 'C:\Test\'"
Launch cmd.exe and use the builtin start command's /d flag to launch powershell.exe with a specific working directory:
cmd /c start /d "C:\working\directory\goes\here" powershell.exe
This will set the working directory of the powershell.exe process to C:\working\directory\goes\here, in turn causing PowerShell's $PWD to change to that directory

Batch script to run Powershell script: Flashing window

System: Windows 10
Powershell Version: 5.1
Purpose: Run a powershell script from a batch file
Parameters: Directory, Filename, Server, Username, Password all being passed in as string encompassed in "" when called from command to handle the situation when there is a space (such as the Directory which currently has a space in)
The Powershell script works perfectly, it creates the credential and starts the RDP connection without issues. When calling from a batch file however the Powershell window flashes and closes immediately. Command Prompt window is run as Administrator.
I've tried using:
- pause
- -noexit
- code from https://blog.danskingdom.com/allow-others-to-run-your-powershell-scripts-from-a-batch-file-they-will-love-you-for-it/
if ($Host.Name -eq "ConsoleHost")
{
Write-Host "Press any key to continue..."
$Host.UI.RawUI.FlushInputBuffer() # Make sure buffered input doesn't "press a key" and skip the ReadKey().
$Host.UI.RawUI.ReadKey("NoEcho,IncludeKeyUp") > $null
}
Clicking on the appearing Powershell window (To try get the select function to pause the window).
None of which have worked.
The code in question is:
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File """"%PowerShellScriptPath%"""" """"%server%"""" """"%username%"""" """"%password%""""' -Verb RunAs}";
Outside of this code no changes have been made to the system, the four speech marks were marked as required to pass through parameters and can be found under the blog post link above at the bottom just before the comments.
There is a high chance i'm using this incorrectly, I am a novice to batch and even newer to powershell. The batch scripts are being made as internal as possible, they need to be able to be used by a base install of Windows. They will eventually be migrated onto versions of Windows Server 2008 and up.
Is there anything that needs to be done with command prompt to allow it to run Powershell code?
Is the powershell code correct for the purpose i'm intending to use it for?
Is there any way, besides the ones listed, to view error, log information or pause the powershell window when run from a batch script?
Any input would be really appreciated!
Edit:
-NoExit variations:
Parent Call
PowerShell **-NoExit** -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File """"%PowerShellScriptPath%"""" """"%server%"""" """"%username%"""" """"%password%""""' -Verb RunAs}";
Nested call
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '**-NoExit** -NoProfile -ExecutionPolicy Bypass -File """"%PowerShellScriptPath%"""" """"%server%"""" """"%username%"""" """"%password%""""' -Verb RunAs}";
Parent and Nested
PowerShell **-NoExit** -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '**-NoExit** -NoProfile -ExecutionPolicy Bypass -File """"%PowerShellScriptPath%"""" """"%server%"""" """"%username%"""" """"%password%""""' -Verb RunAs}";
Variables set inside batch script as:
SET server=%~1
To remove the quotation marks I have also tried using:
SET server=%1
SET server=%server:"=%

Executing file from Admin CMD via CLI

I am trying to execute a file via the CMD with Administrative privileges.
How can I open a cmd via command line with Administrative privileges.
I have to execute a script within a script.
powershell -ExecutionPolicy ByPass -noprofile -command "&{ start-process powershell -ArgumentList '-noprofile -File C:\scripts\install_ims.ps1' -verb RunAs}"
I have tried this in a bat file, but it doesn't work when executed within the script.
This should work fine for your purposes.
powershell -Command "Start-Process <filename> -Verb RunAs"
This is copy-pasted from some Batch files that I finally added to GitHub in the last few days if you have questions, that's probably the best place to go. https://github.com/Benny121221/Batch-BS

The syntax of the command is incorrect running .ps1 from .bat

So I am trying to run a powershell script on windows server from a .bat file and I keep getting this error.
This is the only line I have in my script:
start /d "C:\Windows\SysWOW64\WindowsPowerShell\v1.0\" Powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "& 'C:\path\to\scripts\awesomescript.ps1'"
I have successfully run that command by itself in the cmd window by copying/pasting that whole line into the cmd prompt. The script has been tested as well.
However the same command will not work in the batch file and gives me the error "The syntax of the command is incorrect".
Does anyone happen to know why?
Update:
Thank you to the poster. I merely exited my old command prompt and started a new one. That old command and the previous posters worked. I hate those little things with windows.
Powershell.exe -NoProfile -ExecutionPolicy Bypass -Command "& 'C:\path\to\script\script.ps1'"
I will be keeping the posters answer as the accepted.
Thank you!
Why are you putting path before powershell.exe? Seems to be working without this full path:
PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& 'C:\Users\SE\Desktop\ps.ps1'"
Look there.

Resources