Run process using CMD command fails if the argument is not hardcoded - powershell

I want to run cmd command and run process:
This function works fins:
function RunProcess($processPath)
{
&$processPath "my argument"
}
Usage:
RunProcess "myExe.exe"
Now if I want to make it more generic and send also the argument:
function RunProcess($processPath, $ar)
{
&$processPath $ar
}
Usage:
RunProcess "myExe.exe" "my argument"
This failed and I don't know why.

Your code is working for me, you could try this as well:
function RunProcess($processPath, $ar)
{
Start-Process $processPath -ArgumentList $ar
}

Related

AutomationFocusChangedEventHandler: event dose not triggerd in powershell

I'm traying to detect focus change using a powershell script, hier is my code
start calc
Write-Host "Loading MS UIA assemblies"
[void][System.Reflection.Assembly]::LoadWithPartialName("UIAutomationClient")
[void][System.Reflection.Assembly]::LoadWithPartialName("UIAutomationTypes")
[void][System.Reflection.Assembly]::LoadWithPartialName("UIAutomationProvider")
[void][System.Reflection.Assembly]::LoadWithPartialName("UIAutomationClientsideProviders")
try
{
# WORKAROUND: There is a weird bug: first call fails ...
[Windows.Automation.ClientSettings]::RegisterClientSideProviderAssembly([UIAutomationClientsideProviders.UIAutomationClientSideProviders].Assembly.GetName())
}
catch {}
# ... second call succeeds:
[Windows.Automation.ClientSettings]::RegisterClientSideProviderAssembly([UIAutomationClientsideProviders.UIAutomationClientSideProviders].Assembly.GetName())
$focusedElem = [Windows.Automation.AutomationElement]::FocusedElement #this one work fine
Write-Host "name: " $focusedElem.Current.Name
Write-Host "ControlType: " $focusedElem.Current.ControlType
Write-Host "ProcessId: " $focusedElem.Current.ProcessId
$onFocusChange = { # this dose not fired !!!!
param([Sytem.Object]$src, [Windows.Automation.AutomationFocusChangedEventArgs]$e)
start notepad
}
$focusChangeHandler = [Windows.Automation.AutomationFocusChangedEventHandler]($onFocusChange)
[Windows.Automation.Automation]::AddAutomationFocusChangedEventHandler($focusChangeHandler)
Start-Sleep -Seconds 5 #durring this sleep i change the focused window, but nothing happen :(
[Windows.Automation.Automation]:: RemoveAutomationFocusChangedEventHandler($focusChangeHandler)
any idea why this script not working, or any idea how to monitoring focus change in powershell without external tools ?

Powershell remote : function with nested function

I'm new in Powershell and I have a question about remote.
I have a script.ps1
My script can be illustrated like this :
function Begin{
#Step 1 :
StartTodoSometing
#Step2 :
KeepDooingSomething
}
function StartTodoSometing{}
function KeepDoingSomething{}
This script have can be run on a local server or multiple remote server.
The nested function StartTodoSometing and KeepDoingSomething are public so I can't put it in the "Begin" function.
My question is, how can I run the "Begin" function on a remote computer ???
Thanks for your help !!! :)
I don't know what you mean with public, but if it's a fileshare or anything you should be able to use the following:
function Begin{
. .\POWERSHELLSCRIPT\LOCATION\StartTodoSometing.ps1
. .\POWERSHELLSCRIPT\LOCATION\KeepDoingSomething.ps1
#Step 1 :
StartTodoSometing
#Step2 :
KeepDooingSomething
}

Timeout an MS Access ComObject from powershell

I have a powershell script that creates an MS Access ComObject and uses it to run a macro in an MS Access database as shown below:
$AccessDb= New-Object -ComObject Access.Application
try{
foreach($file in $Files)
{
...
$AccessDb.DoCmd.RunMacro('mcrScr')
...
}
}
catch { ... }
The issue is when there are runtime errors, MS Access throws the errors in an interactive window or dialog box and this causes the powershell to hang; just waiting for the window to close and thus macros for other .mdb files do not get to run.
I have been trying out options from online articles to timeout this piece of my code $AccessDb.DoCmd.RunMacro('mcrScr'), if it runs more than x number of seconds. I used jobs, runspace and [system.diagnostics.stopwatch] but have not been successful.
Is there any better approach to do this. I am kind of running out of options.
Edit:
#Paul, in response to your comment I am adding how i am using runspace to address the problem.
function Script-Timeout {
param([scriptblock]$Command,[int]$Timeout)
$Runspace = [runspacefactory]::CreateRunspace()
$Runspace.Open()
$PS = [powershell]::Create().AddScript($Command)
$PS.Runspace = $Runspace
$chk = $PS.BeginInvoke()
if($chk.AsyncWaitHandle.WaitOne($Timeout))
{
$PS.EndInvoke($chk)
}
else
{
throw "Command taking too long to run. Timeout exceeded."
$PS.EndInvoke($chk)
}
}
The Script-Timeout function is then used in the portion of my script that runs the MS Acess macro as shown below:
Try{
forEach($mdbfile in Files)
{
...
Script-Timeout -Command {
$AccessDb= New-Object -ComObject Access.Application
$AccessDb.OpenCurrentDatabase($mdbfile)
$AccessDb.DoCmd.RunMacro('mcrUpdate')
$AccessDb.CloseCurrentDatabase()
} -Timeout 20
...
}
}
catch
{
#catch exception
}
I have artificially created a runtime error in the VBA which throws an error dialog box. This way the RunMacro portion of the script, if it gets run, will hung the powershell. This is where i expect the runspace to timeout the macro run from powershell after x seconds.
The problem with runspace is that the MS Access Macro does not get run at all. In powershell debug mode, i see the if-block of the script-timeout function always execute successfully with or without the artificial runtime error

PowerShell - InvalidCastException when returning Boolean to explicitly declared variable [duplicate]

This question already has answers here:
Function return value in PowerShell
(10 answers)
Closed 5 years ago.
I've written a PowerShell script to perform some pre-installation setup for a series of patches I'm deploying to client computers across our estate and I'm hitting a bit of an odd issue that I can't wrap my head around.
The setup patch checks the 'C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe.config' file due to a "feature" of PowerShell 2.0 whereby the application uses .NET Framework 2.0.0 by default instead of 4.5.2, preventing certain functions from being executed. If the file doesn't exist or the evaluated values don't match a specification, I add the XML file and provide the necessary values.
The command I run is as follows:
$psConfigDir = "C:\Windows\System32\WindowsPowerShell\v1.0"
$psConfigFileName = "powershell.exe.config"
[boolean]$psExeXml = Set-PSRuntimeConfigs -FilePath ( [String]::Format("{0}\{1}", $psConfigDir, $psConfigFileName) ) -CLRVersions #("v4.0.30319", "v2.0.50727")
...and the Set-PSRuntimeConfigs method is found in a PowerShell Module I created with the code below:
Function Set-PSRuntimeConfigs {
[CmdletBinding()]
Param(
[String]$FilePath,
[System.Collections.ArrayList]$CLRVersions
)
Try {
$xmlWriter = New-Object System.Xml.XmlTextWriter($FilePath, $null)
$xmlWriter.Formatting = "Indented"
$xmlWriter.Indentation = 4
$xmlWriter.WriteStartDocument()
$xmlWriter.WriteStartElement("configuration")
$xmlWriter.WriteStartElement("startup")
$xmlWriter.WriteAttributeString("useLegacyV2RuntimeActivationPolicy", $true)
$CLRVersions | ForEach-Object {
$xmlWriter.WriteStartElement("supportedRuntime")
$xmlWriter.WriteAttributeString("version", $_)
$xmlWriter.WriteEndElement()
}
$xmlWriter.WriteEndElement()
$xmlWriter.WriteEndElement()
$xmlWriter.WriteEndDocument()
$xmlWriter.Close()
$xmlWriter.Dispose()
return $true
} Catch {
echo "ERROR: Exception occurred during XML write process!"
echo "ERROR: Exception message: $($_.Exception.Message)"
return $false
}
}
However, the function is returning an InvalidCastException when trying to assign the result of the function to the $psExeXml variable. Oddly, PowerShell returns with an error stating that [System.Object()] cannot be converted to type [Boolean] despite the fact that only $true or $false is returned from the function.
My first thought is that an exception was being thrown by the function due to a code issue but the function is written to report the error in the prompt and just return $false in that case... Regardless, I'm stuck and can't figure out where to proceed with this...
If the function produces any output then the result will be an array containing the strings that were output and then the final element will be your boolean.
So for this code:
echo "ERROR: Exception occurred during XML write process!"
echo "ERROR: Exception message: $($_.Exception.Message)"
return $false
the function returns an array of two strings and a boolean.

PowerShell webdeploy

I'm trying to use PowerShell with web deployment based on this
article
This is how my script looks like
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.Web.Deployment")
function Sync-Provider($provider, $sourceLocation, $destLocation)
{
$destBaseOptions = new-object Microsoft.Web.Deployment.DeploymentBaseOptions
$syncOptions = new-object Microsoft.Web.Deployment.DeploymentSyncOptions
Try
{
$deploymentObject = [Microsoft.Web.Deployment.DeploymentManager]::CreateObject($provider, $sourceLocation)
$deploymentObject.SyncTo($provider,$destLocation,$destBaseOptions,$syncOptions)
}
Catch
{
echo "EXCEPTION THROWN::[ $_ ] "
#throw $_
}
}
Sync-Provider ("apphostConfig","D:\NerdDinner_2.0\NerdDinner","c:\inetpub\wwwroot")
Running this gives the following exception
EXCEPTION THROWN::[ Cannot convert argument "0", with value: "System.Object[]",
for "CreateObject" to type "Microsoft.Web.Deployment.DeploymentWellKnownProvid
er": "Cannot convert value "apphostConfig,D:\NerdDinner_2.0\Ne
rdDinner,c:\inetpub\wwwroot" to type "Microsoft.Web.Deployment.DeploymentWellKn
ownProvider" due to invalid enumeration values. Specify one of the following en
umeration values and try again. The possible enumeration values are "Unknown, A
ppHostConfig, AppHostSchema, AppPoolConfig, ArchiveDir, Auto, Cert, ComObject32
, ComObject64, ContentPath, CreateApp, DirPath, DBFullSql, DBMySql, FilePath, G
acAssembly, IisApp, MachineConfig32, MachineConfig64, Manifest, MetaKey, Packag
e, RecycleApp, RegKey, RegValue, RootWebConfig32, RootWebConfig64, RunCommand,
SetAcl, WebServer, WebServer60"." ]
Could you give me some hints on this, please?
Try to enclose the first parameter [Microsoft.Web.Deployment]::DeploymentWellKnownProvider.AppHostConfig with a pair of extra parenthesis: ([Microsoft.Web.Deployment]::DeploymentWellKnownProvider.AppHostConfig).
In my case I had the same problem, just opened the powershell console as Administrator and it worked.