Jump to content
david1337

Run powershell script with AutoIt

Recommended Posts

Hi guys,

I need a little help here :)

I have this simple Powershell script, that is able to set "sig.htm" as signature in OWA for the mail account specified.
First part of the script just loads the Exchange snapin, since this is needed for the Get-Mailbox command.

#Add Exchange 2010/2013 snapin if not already loaded in the PowerShell session
if (!(Get-PSSnapin | where {$_.Name -eq "Microsoft.Exchange.Management.PowerShell.E2010"}))
{
	try
	{
		Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010 -ErrorAction STOP
	}
	catch
	{
		#Snapin was not loaded
		Write-Warning $_.Exception.Message
		EXIT
	}
	. $env:ExchangeInstallPath\bin\RemoteExchange.ps1
	Connect-ExchangeServer -auto -AllowClobber
}



$mailboxes = Get-Mailbox -Identity user@domain.com
$mailboxes| foreach {$file= "sig.htm"; Set-MailboxMessageConfiguration -identity $_.alias -SignatureHtml "$(Get-Content -Path $file -ReadCount 0)"}

What I want is for AutoIt to use Powershell.exe to run the script somehow. This way I would be able to use AutoIt variables and arrays together with the PS script.

 I guess the solution would be to run Powershell.exe with command line arguments?

If that is not possible, maybe have the script stored as a "ps1" file, and interact with it that way? (not preferred)

Edited by david1337

Share this post


Link to post
Share on other sites

Try: 

or
 

Powershell.exe -File C:\my_path\run_import_script.ps1

powershell -executionpolicy bypass -File C:\my_path\run_import_script.ps1

powershell.exe -noexit "& 'C:\my_path\run_import_script.ps1'"

 

Edited by You

Share this post


Link to post
Share on other sites

Hi You,

Thank you for your answer! :)

Your suggestion is fine to just start the ps1 script from AutoIt, but I want to use it with AutoIt variables.
-> For instance: When the PS script uses "user@domain.com", it should use the $email variable from AutoIt instead.
Or run the PS script for each email address found in my Autoit Array.

 

Share this post


Link to post
Share on other sites

Try:

Global Const $iPSfile=@TempDir&"\exc.ps1"
Global Const $iHTMLfile="sig.htm"
Global Const $iDefaultEmail="user@domain.com"
Global Const $exPSscript="#Add Exchange 2010/2013 snapin if not already loaded in the PowerShell session"&@CRLF
$exPSscript&='if (!(Get-PSSnapin | where {$_.Name -eq "'&'Microsoft.Exchange.Management.PowerShell.E2010"}))'&@CRLF
$exPSscript&="{"&@CRLF
$exPSscript&="  try"&@CRLF
$exPSscript&="  {"&@CRLF
$exPSscript&="      Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010 -ErrorAction STOP"&@CRLF
$exPSscript&="  }"&@CRLF
$exPSscript&="  catch"&@CRLF
$exPSscript&="  {"&@CRLF
$exPSscript&="      #Snapin was not loaded"&@CRLF
$exPSscript&="      Write-Warning $_.Exception.Message"&@CRLF
$exPSscript&="      EXIT"&@CRLF
$exPSscript&="  }"&@CRLF
$exPSscript&="  . $env:ExchangeInstallPath\bin\RemoteExchange.ps1"&@CRLF
$exPSscript&="  Connect-ExchangeServer -auto -AllowClobber"&@CRLF
$exPSscript&="}"&@CRLF
$exPSscript&=""&@CRLF
$exPSscript&="$mailboxes = Get-Mailbox -Identity "&$iDefaultEmail&@CRLF
$exPSscript&='$mailboxes| foreach {$file= "'&$iHTMLfile&'"; Set-MailboxMessageConfiguration -identity $_.alias -SignatureHtml '&'"$(Get-Content -Path $file -ReadCount 0)'&'"}'&@CRLF

Global $PSscript, $ListEmail=StringSplit("my@gmail.com|ceo@viper.com|xxx@xxx.com","|")

For $i=1 to $ListEmail[0]-1
    $PSscript=StringReplace($exPSscript,$iDefaultEmail,$ListEmail[$i])
    _SaveExecute($PSscript)
    $PSscript=""
Next

Func _SaveExecute($PSscript)
    Local $hFile=FileOpen($iPSfile,2+8)
    FileWrite($hFile,$PSscript)
    FileClose($hFile)
;~  _ExecutePSfile($iPSfile)
;~ Do more somethink
EndFunc

 

Share this post


Link to post
Share on other sites

You should be able to add the following to your PowerShell Script to accept parameters:

Example: PScript.ps1 -Email mail@gmail.com, -File @ScriptDir\Sig.htm

param (
    [Parameter(Mandatory=$true)][string]$Email,
    [string]$File)
 )

 

Share this post


Link to post
Share on other sites

Hi Subz,

Thanks for your answer!

Okay so I add this to my ps1 file:

param (
    [Parameter(Mandatory=$true)][string]$Email,
    [string]$File)
 )

 

and how would I call the file correctly from AutoIt?

Share this post


Link to post
Share on other sites
5 hours ago, You said:

Try: 

or
 

Powershell.exe -File C:\my_path\run_import_script.ps1

powershell -executionpolicy bypass -File C:\my_path\run_import_script.ps1

powershell.exe -noexit "& 'C:\my_path\run_import_script.ps1'"

 

FYI, You, I have actually looked into the first suggestion you made concerning the Powershell Com object, but if you dig into the issue a little more, you will find that that method is only useful up to powershell version 3.  If you have any version greater than that, it is useless.

Share this post


Link to post
Share on other sites

Here is a really basic example:

Example.ps1

param (
    [Parameter(Mandatory=$true)][string]$Email,
    [string]$File)

write-output $Email
write-output $File

Example.au3

Global $aUserInfo[2][2]
    $aUserInfo[0][0] = 'First.User@google.com'
    $aUserInfo[0][1] = @TempDir & '\First.User-Sig'
    $aUserInfo[1][0] = 'Second.User@google.com'
    $aUserInfo[1][1] = @TempDir & '\Second.User-Sig.htm'

For $i = 0 To UBound($aUserInfo) - 1
    RunWait(@ComSpec & ' /k PowerShell.exe -ExecutionPolicy Bypass -File "' & @ScriptDir & '\Example.ps1" -Email ' & $aUserInfo[$i][0] & '-File "' & $aUserInfo[$i][1] & '"')
Next

 

Share this post


Link to post
Share on other sites

Here is another options similar to @You suggestion although haven't tested this, you will need to uncomment the RunWait to test.

Global $sPSScript = @TempDir & "\PSScript.ps1"
Global $aUserInfo[2][2]
    $aUserInfo[0][0] = 'First.User@google.com'
    $aUserInfo[0][1] = @TempDir & '\First.User-Sig'
    $aUserInfo[1][0] = 'Second.User@google.com'
    $aUserInfo[1][1] = @TempDir & '\Second.User-Sig.htm'

    For $i = 0 To UBound($aUserInfo) - 1
        _PSScript($aUserInfo[$i][0], $aUserInfo[$i][1])
    Next

Func _PSscript($sEmail, $sFile)
    Local $hPSScript, $sPSWrite = ""
        $sPSWrite &= "#Add Exchange 2010/2013 snapin if not already loaded in the PowerShell session" & @CRLF
        $sPSWrite &= 'if (!(Get-PSSnapin | where {$_.Name -eq "'&'Microsoft.Exchange.Management.PowerShell.E2010"}))' & @CRLF
        $sPSWrite &= "{" & @CRLF
        $sPSWrite &= "  try" & @CRLF
        $sPSWrite &= "  {" & @CRLF
        $sPSWrite &= "      Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010 -ErrorAction STOP" & @CRLF
        $sPSWrite &= "  }" & @CRLF
        $sPSWrite &= "  catch" & @CRLF
        $sPSWrite &= "  {" & @CRLF
        $sPSWrite &= "      #Snapin was not loaded" & @CRLF
        $sPSWrite &= "      Write-Warning $_.Exception.Message" & @CRLF
        $sPSWrite &= "      EXIT" & @CRLF
        $sPSWrite &= "  }" & @CRLF
        $sPSWrite &= "  . $env:ExchangeInstallPath\bin\RemoteExchange.ps1" & @CRLF
        $sPSWrite &= "  Connect-ExchangeServer -auto -AllowClobber" & @CRLF
        $sPSWrite &= "}" & @CRLF
        $sPSWrite &= "" & @CRLF
        $sPSWrite &= "$mailboxes = Get-Mailbox -Identity " & $sEmail & @CRLF
        $sPSWrite &= '$mailboxes| foreach {$file= "' & $sFile & '"; Set-MailboxMessageConfiguration -identity $_.alias -SignatureHtml ' & '"$(Get-Content -Path $file -ReadCount 0)' & '"}' & @CRLF
        $hPSScript = FileOpen($sPSScript, 10)
            If @error Then Return
        FileWrite($sPSScript, $sPSWrite)
        FileClose($hPSScript)
;~  RunWait(@ComSpec & ' /k PowerShell.exe -ExecutionPolicy Bypass -File "' & $sPSScript & '"')
EndFunc

 

Share this post


Link to post
Share on other sites
53 minutes ago, Subz said:

Here is another options similar to @You suggestion although haven't tested this, you will need to uncomment the RunWait to test.

Global $sPSScript = @TempDir & "\PSScript.ps1"
Global $aUserInfo[2][2]
    $aUserInfo[0][0] = 'First.User@google.com'
    $aUserInfo[0][1] = @TempDir & '\First.User-Sig'
    $aUserInfo[1][0] = 'Second.User@google.com'
    $aUserInfo[1][1] = @TempDir & '\Second.User-Sig.htm'

    For $i = 0 To UBound($aUserInfo) - 1
        _PSScript($aUserInfo[$i][0], $aUserInfo[$i][1])
    Next

Func _PSscript($sEmail, $sFile)
    Local $hPSScript, $sPSWrite = ""
        $sPSWrite &= "#Add Exchange 2010/2013 snapin if not already loaded in the PowerShell session" & @CRLF
        $sPSWrite &= 'if (!(Get-PSSnapin | where {$_.Name -eq "'&'Microsoft.Exchange.Management.PowerShell.E2010"}))' & @CRLF
        $sPSWrite &= "{" & @CRLF
        $sPSWrite &= "  try" & @CRLF
        $sPSWrite &= "  {" & @CRLF
        $sPSWrite &= "      Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010 -ErrorAction STOP" & @CRLF
        $sPSWrite &= "  }" & @CRLF
        $sPSWrite &= "  catch" & @CRLF
        $sPSWrite &= "  {" & @CRLF
        $sPSWrite &= "      #Snapin was not loaded" & @CRLF
        $sPSWrite &= "      Write-Warning $_.Exception.Message" & @CRLF
        $sPSWrite &= "      EXIT" & @CRLF
        $sPSWrite &= "  }" & @CRLF
        $sPSWrite &= "  . $env:ExchangeInstallPath\bin\RemoteExchange.ps1" & @CRLF
        $sPSWrite &= "  Connect-ExchangeServer -auto -AllowClobber" & @CRLF
        $sPSWrite &= "}" & @CRLF
        $sPSWrite &= "" & @CRLF
        $sPSWrite &= "$mailboxes = Get-Mailbox -Identity " & $sEmail & @CRLF
        $sPSWrite &= '$mailboxes| foreach {$file= "' & $sFile & '"; Set-MailboxMessageConfiguration -identity $_.alias -SignatureHtml ' & '"$(Get-Content -Path $file -ReadCount 0)' & '"}' & @CRLF
        $hPSScript = FileOpen($sPSScript, 10)
            If @error Then Return
        FileWrite($sPSScript, $sPSWrite)
        FileClose($hPSScript)
;~  RunWait(@ComSpec & ' /k PowerShell.exe -ExecutionPolicy Bypass -File "' & $sPSScript & '"')
EndFunc

 

 

Wow, I think that we are very close now.
But there seems to be a problem with running a ps1 script that includes the Exchange snapin.
I get the below error in the cmd window:

WARNING: The Windows PowerShell snap-in
'Microsoft.Exchange.Management.PowerShell.E2010' is not installed on this
machine.

 

I tried to run another ps1 script that didn't contain the exchange snapin, and that worked fine using the Run command from AutoIt.

What could be the problem?

Share this post


Link to post
Share on other sites

The creation of the ps1 scripts works perfectly though.

I tried (Run with Powershell) on the ps1 script that was created in the temp folder by AutoIt, and it worked just as expected!

So the only problem is to execute the ps1 script directly from AutoSig :)

Share this post


Link to post
Share on other sites

You could try adding #RequireAdmin to the top of you Au3 Script if that doesn't work you can try using the line below which will Start PowerShell in Admin mode

RunWait(@ComSpec & ' /k PowerShell.exe -Command "& {Start-Process PowerShell.exe -ArgumentList ' & "'-ExecutionPolicy Bypass -File " & '""' & $sPSScript & '"' & "' -Verb RunAs}")

 

Share this post


Link to post
Share on other sites

Its 4am in the morning here and got work in 4 hours so going to go now to get some zzz, I'm fairly sure that the issue is running PowerShell in Admin mode so hopefully either of the commands above will work for you.

Share this post


Link to post
Share on other sites

Wow okay you must be pretty tired atm then. have a good nights sleep!

I tried both RequireAdmin and starting PS in Admin mode, but both gave the result to just leave an empty cmd window open, and no signature was set. (No errors this time though)

You got me very close to the finish line, and I will just have to figure out why the script won't run from AutoIT!

Thank you very much for the help!

 

Share this post


Link to post
Share on other sites

ShellExecute will open the file with Windows' default behavior. In this case it will just open the ps1 file in edit mode.

 

But I found out that if I start the script with a batch file like this, it works:
 

Powershell.exe -executionpolicy Bypass -File  "TempFolder...\PSScript.ps1"

So I'm sure that I can get it to work from AutoIt somehow also! :)

Share this post


Link to post
Share on other sites

Do you run CMD in Administrative mode?  When running PowerShell?  Can you manually try using the same command line and see what the result is?

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • By Exit
      For my next project I would like to send files with "alternate data streams" by email in ZIP format.
      I can not use any external program like 7-Zip or WinRAR. (They would fit😥)
      Who knows how to create a ZIP file with "alternate data streams" included with the Powershell command "Compress-Archive"? 
      Here a test script:  (save as "ADSTester.cmd")
      @rem Try to create a zip file with alternate data streams (ADS) included @rem Housekeeping @cls @del ADSTester.zip >nul: @RD /S /Q Extracted >nul: @del ADSTester.txt >nul: @rem End of Housekeeping echo This is the ADSTester.txt file >ADSTester.txt echo This is the ADSTester.txt:Part1 file >ADSTester.txt:Part1 echo This is the ADSTester.txt:Part2 file >ADSTester.txt:Part2 dir /r ADSTester.txt @rem See the 3 files @rem **************************************************************** @rem **************************************************************** @rem Please alter the next lines to include the alternate data streams. powershell Compress-Archive -Path .\ADSTester.txt -Update -DestinationPath ADSTester.zip powershell Expand-Archive -Path ADSTester.zip -DestinationPath .\Extracted\ dir /r Extracted\ADSTester.txt @rem Only one file left :-( pause  
    • By ur
      Which Powershell command in the PowerCLI module for VMware ESX used to interact with UI apps?
       
      When I launch any exe/any exeutable using powercli on guest VM using powercli command.
      Invoke-VMScript, I am able to run them in the background but not in the foreground.
       
      i.e., UI apps are not launching but showing the background as running in the task manager.
       
      We need our UI Automation scripts to execute in the VM, but it is not working.
       
      We are able to do in virtualbox and hyper-v but not in vmware esx using powercli.
       
      Please suggest.
    • By ambad4u
      Hello and Good Day to All!
      I am trying to install .NET 3.5 on Windows 10 x64bit via autoit (via ShellExecuteWait + PowerShell).
      If I run this line, it will runs without issues:
      ShellExecuteWait('PowerShell.exe', '-executionpolicy Bypass -File "' & @ScriptDir & '\OJP83BU523.ps1' & '"') "OJP83BU523.ps1" contains: DISM /Online /Enable-Feature /FeatureName:NetFX3 /All /Source:D:\Sources\sxs /LimitAccess
      However, since I won't know in advance the drive letter of the "sources" folder, I created a script to generate a PowerShell Script to give a correct path for it.
      With the modified script below, PowerShell only blinks and nothing happens
      ShellExecuteWait('PowerShell.exe', '-executionpolicy Bypass -File "' & @ScriptDir & '\' & $filename & '"') or
      ShellExecuteWait('PowerShell.exe', '-executionpolicy Bypass -File "' & $filename & '"')  
      I wish I know the difference with "$filename" and "\OJP83BU523.ps1" usage, as for me, it should be the same.
      Attached is my entire autoit script.
      any help is appreciated!, many thanks in advance!
      test.au3
    • By JLogan3o13
      There are a number of posts on the forum regarding use of Selenium in AutoIt. I recently had a go at using the PowerShell Selenium module, and was amazed at how easy it is. Thought I would post an example here; if anyone is interested this could probably be incorporated into AutoIt code pretty easily. 
      Pre-Req - The true star of this script is the ChroPath extension, available for Edge, Chrome and FireFox. With it installed, you just click on the element, select Inspect, and then ChroPath generates the XPath to the element for you. Here is an example based on a simple form I created on one of my sites.
      $myForm = Start-SeChrome -StartURL "http://logancomputerser.com/Appointment.html" -Maximized $firstName = Find-SeElement -Driver $myForm -Timeout 30 -XPath "//input[@id='formElement_First']" $lastName = Find-SeElement -Driver $myForm -Timeout 30 -XPath "//input[@id='formElement_Last']" $address = Find-SeElement -Driver $myForm -Timeout 30 -XPath "//input[@id='formElement_Street1']" $city = Find-SeElement -Driver $myForm -Timeout 30 -XPath "//input[@id='formElement_City']" $zip = Find-SeElement -Driver $myForm -Timeout 30 -XPath "//input[@id='formElement_Zip']" $state = Find-SeElement -Driver $myForm -Timeout 30 -XPath "//select[@id='formElement_State']" $phoneDay = Find-SeElement -Driver $myForm -Timeout 30 -XPath "//input[@id='formElement_DaytimePhone']" $phoneNight = Find-SeElement -Driver $myForm -Timeout 30 -XPath "//input[@id='formElement_EveningPhone']" $email = Find-SeElement -Driver $myForm -Timeout 30 -XPath "//input[@id='formElement_liamE']" $user = Find-SeElement -Driver $myForm -Timeout 30 -XPath "//input[@id='formElement_48564']" $pw = Find-SeElement -Driver $myForm -Timeout 30 -XPath "//input[@id='formElement_f403c']" $submit = Find-SeElement -Driver $myForm -Timeout 30 -XPath "//input[@id='wstForm_Contact_Submit']" $reset = Find-SeElement -Driver $myForm -Timeout 30 -XPath "//input[@id='wstForm_Contact_Reset']" Send-SeKeys -Element $firstName -Keys "Joe" Send-SeKeys -Element $lastName -Keys "Blow" Send-SeKeys -Element $address -Keys "111 S. Main St." Send-SeKeys -Element $city -Keys "AnyCity" Send-SeKeys -Element $zip -Keys "90210" Send-SeKeys -Element $state -Keys "CA" Send-SeKeys -Element $phoneDay -Keys "555.867.5309" Send-SeKeys -Element $phoneNight -Keys "555.888.1212" Send-SeKeys -Element $email -Keys "1Adam12@gmail.com" Send-SeKeys -Element $user -Keys "JBlow" Send-SeKeys -Element $pw -Keys "MyPassword" Start-Sleep 1 Invoke-SeClick -Element $submit Stop-SeDriver -Driver $myForm  
      As mentioned, this is just another way to skin the cat, but I found it a pretty fast way to initiate some easy testing in Selenium, and have used it a couple of times in projects now, both straight through PowerShell and wrapped in AutoIt.
    • By antonioj84
      I need some help with the powershell code below
      #include <AutoItConstants.au3> #include <Array.au3> #RequireAdmin $PS='Get-NetConnectionProfile | Where-Object { $_.NetworkCategory -match "$Public" } | Set-NetConnectionProfile -NetworkCategory Private' $sCommands = "powershell -Command " & $PS &"" $iPID = Run(@ComSpec & " /k " & $sCommands, "", @SW_SHOW , $stdout_child)  
×
×
  • Create New...