executing the powershell commands using python - python-3.x

import os
os.system("powershell.exe [Get-ItemProperty
HKLM:\\Software\\Wow6432Node\\Microsoft\\\Windows\\CurrentVersion\\Uninstall\\*| Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table –AutoSize > D:\\application whitelisting\\InstalledProgramsPS.txt ]")
this is my code. I want to display the list of software installed in the system.
but i am getting error like
Select-Object is not recognized as an external or internal command.
when i execute the same command using powershell, it is working fine.
can anyone please help?
thanks in advance.

The reason is that Powershell's command parameter is not properly constructed. os.system() call will star a CMD session, and Select-Object is not recognized as an external or internal command is an error message from CMD.
Let's see what CMD does. First it will run Powershell and pass some arguments. Note the triple backslash, which is an error by itself and needs to be fixed.
powershell.exe [Get-ItemProperty HKLM:\\Software\\Wow6432Node\\Microsoft\\\Windows\\CurrentVersion\\Uninstall\\*
| Select-Object DisplayName, DisplayVersion, Publisher, InstallDate
Now, the first thing is that Powershell is invoked and (wrongly) paramerized Get-ItemProperty is passed. Because the pipe char | is used in CMD as well, it is interpreted as a command for CMD. Thus CMD tries to pipe the first command's output to Select-Object, but there isn't such a command in CMD. Thus the error.
To fix the issue, use -command "<commands>" to pass commands to Powershell. The double quotes " are used to create a single string that CMD passes to Powershell as an argument.
powershell.exe -command "Get-ItemProperty HKLM:\\Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall\\*| Select-Object DisplayName, DisplayVersion, Publisher, InstallDate | Format-Table -AutoSize > D:\\application whitelisting\\InstalledProgramsPS.txt"

Related

Azure Pipeline Extract Task 7zip

Unable to extract zip to destination with default usage of Extract Task its fails with error:
##[error]Unable to locate executable file: 'C:\azagent\A5\_work\_tasks\ExtractFiles_5e1e3830-fbfb-11e5-aab1-090c92bc4988\1.200.0\7zip\7z.exe'. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.
Stating its fails to locate default 7zip path. Tried to use custom PATH setting but also fails with the same error.
UPDATE
Issue seem to be caused by permissions of agent. Still haven't been able to execute Release with Admin privileges in service mode. When run in interactive mode as Admin the release executes successfully.
Task fails whenever admin permission is required.
From the error message, 7zip seems not installed on your self-hosted agent. Try to install the 7zip before you use the Extract Task.
Take Bash Task as an example:
brew install p7zip
For Windows, use the below PowerShell script to install:
$dlurl = 'https://7-zip.org/' + (Invoke-WebRequest -UseBasicParsing -Uri 'https://7-zip.org/' | Select-Object -ExpandProperty Links | Where-Object {($_.outerHTML -match 'Download')-and ($_.href -like "a/*") -and ($_.href -like "*-x64.exe")} | Select-Object -First 1 | Select-Object -ExpandProperty href)
# modified to work without IE
# above code from: https://perplexity.nl/windows-powershell/installing-or-updating-7-zip-using-powershell/
$installerPath = Join-Path $env:TEMP (Split-Path $dlurl -Leaf)
Invoke-WebRequest $dlurl -OutFile $installerPath
Start-Process -FilePath $installerPath -Args "/S" -Verb RunAs -Wait
Remove-Item $installerPath

Disable/enable completely input devices (mouse+keyboard+touchpad) in Windows10

I'm trying to disable/enable input devices in my laptop (win10), automatically (.reg file, python code etc)
I tried to use DevCon but after a lot of attempts it didn't work out for my touchpad and keyboard (I tried to disable, remove).
I searched the web and the solutions don't completely disable the devices (for example: Ctrl+Alt+Delete is not blocked).
I work on a windows 10 Laptop, You can assume that you have admin Privileges.
Have to check for Keyboard but for Mouse and Touchpad, you can use some Powershell commands to check and find out the actual device Classes and InstanceIDs and then turn off with an Admin elevated Powershell prompt.
The InstanceIDs of Mouse and Touchpad is different on different brands and types of Laptops, but first you can identify those with their Classes such as HIDClass. To get that fire up Powershell prompt(you've already tried REG and Python, so assuming you'll be okay with Powershell too (.ps1)) and run this command:
Get-PnpDevice | Where-Object {$_.Class -eq 'HIDClass'}
This may show 2 or 3 entries of which 1 belongs to Mouse and other to Touchpad, this would be a bit of trial and error, you have to pick any InstanceID to make filter more target specific and fire-up admin-elevated Powershell (search Powershell and click on "Run As Administrator") and run Disable-PnpDevice method like below(if InstanceId contains "ACPI"):
Get-PnpDevice | Where-Object {$_.Class -eq 'HIDClass' -and $_.InstanceId -like 'ACPI*'} | Disable-PnpDevice -Confirm:$false
This will disable Touchpad(in mine(Lenovo) it did disabled it) and then you can try out another InstanceID and disable the Mouse too in the same way. Voila !! both are turned off now.
If you prefer this in .ps1 script format then you need a self-elevating script which can enable/disable the devices without any halts, save this code in .ps1 file and then right-click > Run with PowerShell:
$Loc = Get-Location
"Security.Principal.Windows" | % { IEX "( [ $_`Principal ] [$_`Identity ]::GetCurrent() ).IsInRole( 'Administrator' )" } | ? {
$True | % { $Arguments = #('-NoProfile','-ExecutionPolicy Bypass','-NoExit','-File',"`"$($MyInvocation.MyCommand.Path)`"","\`"$Loc\`"");
Start-Process -FilePath PowerShell.exe -Verb RunAs -ArgumentList $Arguments; } }
Get-PnpDevice | Where-Object {$_.Class -eq 'HIDClass' -and $_.InstanceId -like 'ACPI*'} | Disable-PnpDevice -Confirm:$false
Read-Host
Note: If you in case disable the wrong or undesired device than for enabling it, in the same admin-elevated Powershell window run the same filter command (the Get-PnpDevice with filters) and replace Disable-PnpDevice with Enable-PnpDevice.
Let me know in comments if you still face issue with above commands.
Untested, but calling BlockInput() should do what you want. It blocks both keyboad and mouse input. It is however defined in user32.dll so you will need to use ctypes to access it:
import ctypes
ctypes.windll.user32.BlockInput(True)

How to hide console output from Select-AzureRmSubscription

Does anyone know how to hide output from command Select-AzureRmSubscription inside azure workbook which runs as powershell workflow
Thanks
You can use Out-Null. Works for any PowerShell cmdlet.
Select-AzureRmSubscription | Out-null
The Out-Null cmdlet sends its output to NULL, in effect, removing it
from the pipeline and preventing the output to be displayed at the
screen.
https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.core/out-null
Select-AzSubscription -SubscriptionId $s.Id | Out-Null + ~~~~~~~~ Cannot call the 'Out-Null' command. Other commands from this module have been packaged as workflow activities, but this command was specifically excluded. This is likely because the command requires an interactive Windows PowerShell session, or has behavior not suited for workflows. To run this command anyway, place it within an inline-script (InlineScript { Out-Null }) where it will be invoked in isolation

visual studio 2012 multiple -commands in command line arguments

In visual studio 2012 it is possible on the debug-> start options to specify command line arguments. I am working on a powershell cmdlet so I'd like to be able to parse multiple commands into powershell. My arguments looks like this
-noexit -command add-pssnapin Registerv2.0 -command New-Token -command www.google.com
the problem is it is treating -command as 1 long string i.e -command "add-pssnapin Registerv2.0 -command New-Token -command www.google.com" rather then 3 seperae commands. Does anyone know how to change this:
edit
the results I am looking for is when I run the project
power shell opens
my snapin is registered
Call the cmdlet new-token
enter in the cmdlet parameters
If you first want add-pssnapin Registerv2.0 and then New-Token to be called, you should chain them in one command, like so:
-command "add-pssnapin Registerv2.0; New-Token"
If New-Token expects a parameter, you should pass it on the command line directly, instead of trying to simulate user input.
For example, New-Item would expect a list of paths and a type as input, both can also be supplied on the command line as parameters. Like so:
New-Item foo -type directory
So, how you would pass the value www.google.com to New-Token depends on the name of the parameter. But could look like:
-command "add-pssnapin Registerv2.0; New-Token -tokenName www.google.com"

How do you call msdeploy from powershell when the parameters have spaces?

I'm running into a problem with spaces in my parameters that I try to send into msdeploy from a powershell script.
There are a number of other related articles but none of them solve the problem.
Problems Using Power Shell And MSDeploy.
Similar SO issue that doesn't work: How to run exe in powershell with parameters with spaces and quotes
PowerShell BUG: Executing commands which require quotes and variables is practically impossible
Another SO issue that doesn't work:Passing parameters in PowerShell 2.0
The simplest example that succeeds and then fails when I make it more complicated is just dumping the default web site.
$msdeploy = "C:\Program Files\IIS\Microsoft Web Deploy\msdeploy.exe"
&$msdeploy -verb:dump -source:appHostConfig=`'default web site`' -verbose
==SUCCESS
This one?
$sitename="default web site"
&$msdeploy -verb:dump -source:appHostConfig=$sitename -verbose
==FAIL with the following error
msdeploy.exe : Error: Unrecognized argument '"-source:"appHostConfig=default'. All arguments must begin with "-".
At C:\xxx\test.ps1:122 char:6
+ &
+ CategoryInfo : NotSpecified: (Error: Unrecogn...begin with "-".:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
Error count: 1.
The following variations have also failed
#FAIL
$sitename=`'default web site`'
$sitename=`'"default web site"`'
$sitename="`'default web site`'"
$sitename="default web site"
$sitename="'default web site'"
&$msdeploy -verb:dump "-source:appHostConfig=$sitename" -verbose
&$msdeploy -verb:dump -source:appHostConfig="$sitename" -verbose
&$msdeploy -verb:dump -source:appHostConfig='$sitename' -verbose
&$msdeploy -verb:dump -source:appHostConfig=`'$sitename`' -verbose
&$msdeploy -verb:dump -source:appHostConfig=`"$sitename`" -verbose
I'm at a loss. Everyone I work with is at a loss. Seriously this sucks. I loved Powershell. I loved msdeploy. I can't say that I love putting them together. It looks like it may have been easier to focus on the API instead of the cli.
EDIT:
The parameters in the string array suggested by Emperor XLII works well. An alternative solution is presented in the following article: The trials and tribulations of using MSDeploy with PowerShell
function PushToTarget([string]$server, [string]$remotePath, [string]$localPath) {
cmd.exe /C $("msdeploy.exe -verb:sync -source:contentPath=`"{0}`" -dest:computerName=`"{1}`",contentPath=`"{2}`" -whatif" -f $localPath, $server, $remotePath )
}
Using the technique from Keith's answer to How to run exe in powershell with parameters with spaces and quotes question you linked to, running echoargs -verb:dump -source:appHostConfig=$sitename -verbose gave me this output:
Arg 0 is <-verb:dump>
Arg 1 is <-source:appHostConfig=default>
Arg 2 is <web>
Arg 3 is <site>
Arg 4 is <-verbose>
This would explain the invalid argument of appHostConfig=default that msdeploy was seeing.
Running echoargs -verb:dump "-source:appHostConfig=$sitename" -verbose, with $sitename = "default web site", appears to result in the desired arguments:
Arg 0 is <-verb:dump>
Arg 1 is <-source:appHostConfig=default web site>
Arg 2 is <-verbose>
Though from your list, it appears that this did not work for you.
Another method you might try is building up the list of arguments in an array, which powershell can automatically escape. For example, this gives the same output as above:
[string[]]$msdeployArgs = #(
"-verb:dump",
"-source:appHostConfig=$sitename",
"-verbose"
)
echoargs $msdeployArgs
Just adding another way in case it is helpful to anyone:
Invoke-Expression "& '[path to msdeploy]\msdeploy.exe' --% -verb:sync -source:contentPath=`'$source`' -dest:contentPath=`'$dest`'"
"--%" is new to powershell 3. From here: "You simply add a the --% sequence (two dashes and a percent sign) anywhere in the command line and PowerShell will not try to parse the remainder of that line."
Found a working solution and easy fix.
Reference: http://answered.site/all-arguments-must-begin-with--at-cwindowsdtldownloadswebserviceswebservicesidservicepublishedwebsitesidservicedeploymentidservicewsdeployps123/4231580/
$msdeploy = "C:\Program Files\IIS\Microsoft Web Deploy V3\msdeploy.exe"
$msdeployArgs = #(
"-verb:sync",
"-source:iisApp='Default Web Site/HelloWorld'",
"-verbose",
"-dest:archiveDir='c:\temp1'"
)
Start-Process $msdeploy -NoNewWindow -ArgumentList $msdeployArgs
We had faced the similar kind of issue. Our fix was like below,
$path = "C:\Program Files\IIS\Microsoft Web Deploy V3\msdeploy.exe";
$verb = "-verb:sync";
$src = "-source:contentPath=[ESC][ESC][ESC]"c:\aa aa[ESC][ESC][ESC]";
$dest = "-dest:contentPath=[ESC][ESC][ESC]"c:\aa[ESC][ESC][ESC]";
Invoke-Expression "&'$path' $verb $src $dest";
where, ESC - is escape sequence/character
I tried every technique under the sun, and this is the only one that worked for me (using PowerShell 2).
cmd.exe /C $("msdeploy.exe -verb:sync -source:package=`"{0}`" -dest:auto,IncludeAcls=`"False`" -disableLink:AppPoolExtension -disableLink:ContentExtension -disableLink:CertificateExtension -setParamFile:`"{1}`"" -f $mypackagepath, $myparamfilepath )
Here is another approach derived from the input below.
$msdeploy = "C:\Program Files\IIS\Microsoft Web Deploy V3\msdeploy.exe";
$command = "-verb:sync";
$sourcePath = "C:\aa aa\";
$source = $("-source:contentPath=`"{0}`"" -f $sourcePath);
$destPath = "C:\aa"
$destination = $("-dest:contentPath=`"{0}`" -f $destPath);
$msdeploycommand = $("`"{0}`" {1} {2} {3} -verbose" -f $msdeploy, $command, $source, $destination);
cmd.exe /C "`"$msdeploycommand`"";
This caters for the MSDeploy.exe being in its default installation folder which contains spaces. Hence the wrapping with the escape character (`).
I've used some ideas from answers above and came up with the following simpler function to do the thing.
Note that it is important to give the full path to MSDeploy as when running under the build agent it sometimes doesnt recognise the PATH to msdeploy.
function Deploy([string]$server, [string]$remotePath, [string]$localPath) {
$msdeploy = "C:\Program Files\IIS\Microsoft Web Deploy V3\msdeploy.exe";
cmd.exe /C $("`"{3}`" -verb:sync -source:contentPath=`"{0}`" -dest:computerName=`"{1}`",contentPath=`"{2}`" " -f $localPath, $server, $remotePath , $msdeploy )
}
Usage
Deploy $hostName $remotePath $source
All of the above did not work for me, this is the solution that worked:
# get msdeploy exe
$MSDeploy = ${env:ProgramFiles}, ${env:ProgramFiles(x86)} |
ForEach-Object {Get-ChildItem -Path $_ -Filter 'MSDeploy.exe' -Recurse} |
Sort-Object -Property #{Expression={[version]$_.VersionInfo.FileVersion}} -Descending |
Select-Object -First 1 -ExpandProperty FullName
#build deploy command
$deplyCmd = """""$MSDeploy"" -verb:sync -dest:iisApp=""Default Web Site"" -enableRule:DoNotDeleteRule -source:iisApp=""$ExtraWebFilesFolder"""
#execute
&cmd /c $deplyCmd
This problem has certainly been around for a long time and I spent some time battling it recently. The result has been successful for me so I'll post it here in hopes that it can help others who find this question in the future.
The first problem to resolve is getting rid of the spaces in the msdeploy path. There are two approaches here. One is persistent and requires you to have server access, the other is temporary in the context of your PowerShell script. Either will work but I'd prefer the first if it's an option for you.
For the first approach, create a junction point. Example script:
new-item -Path "c:\MS-WebDeploy" -ItemType Junction -Value "c:/Program Files (x86)/iis/microsoft web deploy v3"
For the second approach, create a PSDrive (w in this example)
New-PSDrive -Name "w" -PSProvider FileSystem -Root "C:/Program Files (x86)/iis/microsoft web deploy v3"
I'm using three PowerShell variables below. For example purposes, pretend that all three have spaces.
$ParamFilePath = "c:\deployment files\parameters.xml"
$PackageName = "c:\deployment files\My Website.zip"
$WebAppPath = "Default Web Site"
First, create an array and build up your arguments as needed.
#nothing needs to be done with these arguments so we'll start with them
[string[]]$arguments = #("-verb:sync", "-dest:auto", "-disableLink:AppPoolExtension", "-disableLink:ContentExtension", "-disableLink:CertificateExtension", "-allowUntrusted")
#double up on the quotes for these paths after the colon
$arguments += "-setParamFile:""$ParamFilePath"""
$arguments += "-source:package=""$PackageName"""
#must not have spaces with the commma, use single quotes on the name and value here
$arguments += "-setParam:name='IIS Web Application Name',value='$WebAppPath'"
#add your own logic for optional arguments
$arguments += "-EnableRule:EncryptWebConfig"
Now build the msdeploy command and put the PowerShell escape sequence to prevent PowerShell from "helping" later. Use the path you created with the junction or the PSDrive
$command = "w:\msdeploy.exe" + " --% " + $arguments -join " "
Finally, execute that command as a script block.
$sb = $ExecutionContext.InvokeCommand.NewScriptBlock($command)
& $sb
I've wrapped this and a bit more code into a script which is called like this.
.\Run-WebDeploy -WebAppPath "Default Web Site" -PackageName "c:\deployment files\My Website.zip" -ParamFilePath "c:\deployment files\parameters.xml" -EncryptWebConfig
In general, you can help yourself a lot by getting rid of the spaces in your paths/names. Sometimes, that can't be done and this should get you through.

Resources