Running a Powershell script from cmd - powershell

I'm trying to use a simple Port-Scanner as a PowerShell one-liner that looks like this:
1..1024 | % {echo ((new-object Net.Sockets.TcpClient).Connect("192.168.171.1",$_)) "Port $_ is open!"} 2>$null
It works perfectly in a PowerShell Window. But, if I try to start it from a Windows Command Window (CMD), I get the following error message:

Your quotes are conflicting. Try using:
powershell '1..1024 | % {echo ((new-object Net.Sockets.TcpClient).Connect("192.168.171.1",$_)) "Port $_ is open!"} 2>$null'

Unless you on PowerShellv2, why not simplify this. Use the built-in cmdlets.
powershell -Command "1..1024 | ForEach {Test-NetConnection 192.168.171.1 -Port $PSitem}"
Absolutely, PowerShell is cleaner, the present/future, and where you want to be, but you could do this VBScript as well.
VBS Script to Check Port Availability in Windows

Related

Is it possible to use PowerShell to automate interactions with installed programs in windows 10?

Is it possible, from a PowerShell script, to for example automate text box population, automate striking of the enter key inside of an installed program in Windows 10? Could anyone point me in the direction of relevant documentation?
Would a different alternative to PowerShell be more appropriate?
Thanks!
I know how to execute the program from PowerShell (PS C:> 'filepath\program.exe'). I also know how to kill the program from PowerShell (PS C:> stop-process -Name "program_name").
In trying to figure out how events are identified, I tried:
PS C:> $Events = Get-Event
PS C:> $Events[0] | Format-List -Property *
But it returns an error message: "Cannot index into a null array"

Redirect the output of a PowerShell script to a file using command prompt

How to redirect the output of a PowerShell 5.0 script to a file using cmd in Windows 10? I tried the following:
powershell ".\myscript.ps1 | Out-File outfile.txt"
and:
powershell .\myscript.ps1 > outfile.txt
to no avail. The outfile.txt is created but remains empty. The command prompt window is run with Administrator privileges.
In a script I use:
Write-Host $MyVar
Write-Host $SomeOtherVar
to output the values to a screen.
Use the specific PowerShell redirection operators:
(they appear to work at the (cmd) command prompt as wel)
Redirect the success stream (1>):
powershell .\myscript.ps1 1> outfile.txt
Redirect all streams (*>):
powershell .\myscript.ps1 *> outfile.txt
In a script I use:
Write-Host $MyVar
Write-Host $SomeOtherVar
to output the values to a screen.
Yeah, that's your problem right there! Write-Host writes the information straight to the screen buffer of the host application, so the standard output stream will never actually see anything.
Change your Write-Host statements to Write-Output (or just remove them):
Write-Output $MyVar
Write-Output $SomeOtherVar
# or simply
$MyVar
$SomeOtherVar

how do I make it easy for my parents to run this Powershell command?

I am not a programmer and my parents' Windows 10 PC tends to loose its start menu and cortana processes, resulting in start menu not showing up at all when the start icon is clicked.
I made a quick search and found + tested this Powershell command and it worked:
Get-AppxPackage | % { Add-AppxPackage -DisableDevelopmentMode -Register "$($_.InstallLocation)\AppxManifest.xml" -verbose }
I wish to turn this command into a shortcut/batchfile that executes the command and restarts the PC whenever the desktop icon is double clicked, in order to avoid explaining to my parents what to do to fix the problem. Can any one help me out please?
Thank you in Advance.
you can encode the command and put the whole thing into a single batch file (no .ps1 necessary)
details here
https://blogs.msdn.microsoft.com/timid/2014/03/26/powershell-encodedcommand-and-round-trips/
or you can use this function
https://github.com/gangstanthony/PowerShell/blob/master/Encode-Text.ps1
first, either use Get-Content or Get-Clipboard (copy your whole script to the clipboard) to encode your desired script
PS> Encode-Text (Get-Clipboard | out-string)
RwBlAHQALQBBAHAAcAB4AFAAYQBjAGsAYQBnAGUAIAB8ACAAJQAgAHsAIABBAGQAZAAtAEEAcABwAHgAUABhAGMAawBhAGcAZQAgAC0ARABpAHMAYQBiAGwAZQBEAGUAdgBlAGwAbwBwAG0AZQBuAHQATQBvAGQAZQAgAC0AUgBlAGcAaQBzAHQAZQByACAAIgAkACgAJABfAC4ASQBuAHMAdABhAGwAbABMAG8AYwBhAHQAaQBvAG4AKQBcAEEAcABwAHgATQBhAG4AaQBmAGUAcwB0AC4AeABtAGwAIgAgAC0AdgBlAHIAYgBvAHMAZQAgAH0ADQAKAA==
then you can use that in your batch file like so
powershell -encodedcommand RwBlAHQALQBBAHAAcAB4AFAAYQBjAGsAYQBnAGUAIAB8ACAAJQAgAHsAIABBAGQAZAAtAEEAcABwAHgAUABhAGMAawBhAGcAZQAgAC0ARABpAHMAYQBiAGwAZQBEAGUAdgBlAGwAbwBwAG0AZQBuAHQATQBvAGQAZQAgAC0AUgBlAGcAaQBzAHQAZQByACAAIgAkACgAJABfAC4ASQBuAHMAdABhAGwAbABMAG8AYwBhAHQAaQBvAG4AKQBcAEEAcABwAHgATQBhAG4AaQBmAGUAcwB0AC4AeABtAGwAIgAgAC0AdgBlAHIAYgBvAHMAZQAgAH0ADQAKAA==
You could execute the PowerShell script via a batch file.
Batch file:
set powerscriptPath=C:\Example.ps1
PowerShell.exe -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File ""%powerscriptPath%""' -Verb RunAs}"
This will bypass the execution policies on the computer allowing the script to run in Administrator mode too. NOTE: You will need to edit the powerscriptPath to point to your PowerShell script location, I just used C:\Example.ps1 as an example.
You will want to add Restart-Computer -Force to the end of your PowerShell script to restart the computer
Get-AppxPackage | % { Add-AppxPackage -DisableDevelopmentMode -Register "$($_.InstallLocation)\AppxManifest.xml" -verbose }
Restart-Computer -Force
Make a bat file which executes powershell with that file. Then add a shortcut to the bat file
I am really unsure why you would run a batch file just to call a powershell script! Talk about hokey approaches to a non-problem.
To call a powershell script is really no different than calling a batch script:
It's simply path to PowerShell, and the script path as a parameter:
"%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe" "C:\users\austinfrench\desktop\example.ps1"
You can also use the exact same format as the target for a desktop shortcut.

Simple PowerShell script refuses to write file when running from command line but works fine in ISE

So I have a pretty simple PowerShell script used to update a version number during a build.
$InputFile = 'D:\BuildAgent\work\c9716e2651305a2e\web\WEB-INF\classes\version.properties'
$OutputFile = $InputFile
Write-Host $('Updating "' + $OutputFile + '" to reflect version "2.10.0.51"')
(Get-Content $InputFile) |
Foreach-Object {
$_ -replace 'version.release\s*:.*','version.release: 2.10.0.51'
} |
Out-File $OutputFile
It works completely fine from within ISE, but when I run it from the command line with
powershell.exe -Command - < powershell2447437064467034590.ps1
or
powershell.exe -NoProfile -NonInteractive -ExecutionPolicy ByPass
-Command - < powershell2447437064467034590.ps1
All this does though is blank out the file. How can this work fine from ISE but not from the command line?
"Windows Powershell does not load commands from the current location by default. If you trust this command, instead type ".\test.ps1"
-Windows Powershell
powershell.exe .\powershell2447437064467034590.ps1
I tested with Powershell command prompt and classic command prompt
For more information
Run from an elevated script or command, Powershell 3.0
Update-Help
Get-help about_Command_Precedence
I figured it out. I used tabs in the file to pretty print and format the text. Apparently that breaks it. If I copy and past it into ISE, it silently converts all the tabs into spaces which is why it worked there. Pretty surprising that the tokenizer doesn't treat all whitespace the same.

Running PowerShell from RunOnce

I am trying to run a set of powershell commands during a template customization. These commands are injected into the RunOnce in the registry.
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -command &{Add-Type -Assembly System.Web; [Web.Security.Membership]::GeneratePassword(21,7) | Select-Object #{N="Group";E={"Test Group"}}, #{N="Username";E={"TestUser"}}, #{N="Password";E={$_}} | Export-Csv -Path C:\stuff\user.csv -NoTypeInformation}
I know that these commands work, as I can run them in a powershell console. I know that "%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -command &{PSCODE}" is correct because other runonce commands will run correctly. I cannot figure out what part of my syntax is failing.
This could be a long trial and error session, to save you precious time, I suggest you use a script file instead of that long command:
%SystemRoot%\system32\WindowsPowerShell\v1.0\powershell.exe -File c:\script.ps1
Just want to add, that in order to run a sequence of commands you have to run it without quotes. At least only in this way it worked for me:
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noexit Import-Module Hyper-V; Get-VMSwitch \"*Virtual*\" | Remove-VMSwitch -Force; New-VMSwitch -NetAdapterName \"Ethernet\" -Name \"VMNet\"