this code works as expected:
$var = "a123"
$script = #'
Add-Content C:\temp\test.txt -Value {{"{0} name1"}}
Add-Content C:\temp\test.txt -Value {{"{0} name2"}}
'# -f $var
$command = [scriptblock]::Create($script)
Start-Process powershell.exe -Verb RunAs -ArgumentList "-NoExit -command & {$command}" -Wait
But when I change the value of $var to "123", I get the error:
At line:1 char:49
+ & {Add-Content C:\temp\test.txt -Value {123 name1}
+ ~~~~~
Unexpected token 'name1' in expression or statement.
At line:2 char:46
+ Add-Content C:\temp\test.txt -Value {123 name2}}
+ ~~~~~
Unexpected token 'name2' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
I tried with other quotes, with casting to string but I have no solution that works. Can anyone help please?
I think I figured out, what is happening and how to work around it.
The problem is, that somehow the double quotes in your script block are lost, once the command is passed to powershell.exe and something funny happens, when the first token of your script block is not identified as a string. Compare this:
{123a name1} # Returns a script block
{123 name1} # Fails with "UnexpectedToken" exception
{$true name1} # Fails with "UnexpectedToken" exception
I have not the slightest idea, why that happens, but that is what you can do, to work around it:
$var = "123"
$script = #'
Add-Content C:\temp\test.txt -Value {{'{0} name1'}}
Add-Content C:\temp\test.txt -Value {{'{0} name2'}}
'# -f $var
The single quotes are somehow maintained when the command is passed on and the output in C:\temp\test.txt looks like this:
'123 name1'
'123 name2'
Related
Basically I have file in my Windows machine of UTF8 code. Similar to this path directory and file "G:\这是一\个令人沮". And I am trying to write EICAR string (X5O!P%#AP[4\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*) to the file using PowerShell.
For regular file path it is being done like following:
#Base64 of Eicar string
[string] $EncodedEicar = 'WDVPIVAlQEFQWzRcUFpYNTQoUF4pN0NDKTd9JEVJQ0FSLVNUQU5EQVJELUFOVElWSVJVUy1URVNULUZJTEUhJEgrSCo='
if (!(Test-Path -Path $FilePath)) {
try {
[byte[]] $EicarBytes = [System.Convert]::FromBase64String($EncodedEicar)
[string] $Eicar = [System.Text.Encoding]::UTF8.GetString($EicarBytes)
Set-Content -Value $Eicar -Encoding ascii -Path $FilePath -Force
}
Tried the following suggestions didnt help :(
Executed powershell.exe "& {Import-Module C:\PROGRA~1\WindowsPowershell\Modules\new_eicar.psm1 -Force -DisableNameChecking ;New-Eicar -Path 'N:\这是一\个令人沮' -FileName 'eicar.com'; if ($?) {exit 0} else {exit 1}}". Result: {'status': 1, 'stderr': '', 'stdout': 'New-Eicar : Cannot validate argument on parameter \'Path\'. The "Test-Path $_ \r\n-PathType \'Container\'" validation script for the argument with value \r\n"N:\\\x8a\xa8T\x91~_\x84,?\\\x84,\xa6\x84\xaf\x0f\x84\xa7\xa7\x91\xfdr" did not return a result of True. Determine why the \r\nvalidation script failed, and then try the command again.\r\nAt line:1 char:116\r\n+ ... ew-Eicar -Path \'N:\\\x8a\xa8T\x91~_\x84,?\\\x84,\xa6\x84\xaf\x0f\x84\xa7\xa7\x91\xfdr\' -FileName \'eicar.com\'; if \r\n($?) {exit ...\r\n+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~\r\n + CategoryInfo : InvalidData: (:) [New-Eicar], ParameterBindingVa \r\n lidationException\r\n + FullyQualifiedErrorId : ParameterArgumentValidationError,New-Eicar\r\n \r\n'}
2017-08-30 23:31:12 DEBUG ssh.py:228 (TB) 10.5.22.4>> 'powershell.exe "& {Import-Module C:\PROGRA~1\WindowsPowershell\Modules\new_eicar.psm1 -Force -DisableNameChecking ;New-Eicar -Path 'N:\这是一\个令人沮' -FileName 'eicar.com'; if ($?) {exit 0} else {exit 1}}"', timeout: 300
2017-08-30 23:31:13 DEBUG ssh.py:306 (TB) 10.5.22.4<< '{
status: 1,
stderr: ,
stdout: New-Eicar : Cannot validate argument on parameter 'Path'. The "Test-Path $_
-PathType 'Container'" validation script for the argument with value
"N:\T~_,?\,r" did not return a result of True. Determine why the
validation script failed, and then try the command again.
At line:1 char:116
+ ... ew-Eicar -Path 'N:\T~_,?\,r' -FileName 'eicar.com'; if
($?) {exit ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidData: (:) [New-Eicar], ParameterBindingVa
lidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationError,New-Eicar
}'
this is probably an easy answer for you experts but not sure the best command to use. I want to execute the following command from within powershell :
stccmd -rh sldcege-mie003 -rs nsccahs_dev -un Administrator -up STC -cb nsccahs_dev_cb -cmd "status bobRRC_ADT_OUT_FMT"
and return the result.
The code i have so far is :
$sCmd = #'
"stccmd -rh sldcege-mie003 -rs nsccahs_dev -un Administrator -up STC -cb
nsccahs_dev_cb -cmd '\"status bobRRC_ADT_OUT_FMT\"'"
'#
$Result = Invoke-Command $sCmd | Out-String
The error i am getting is :
Invoke-Command : Parameter set cannot be resolved using the specified named par
ameters.
At E:\Andrew\MonitoreGate.ps1:20 char:25
+ $Result = Invoke-Command <<<< $sCmd | Out-String
+ CategoryInfo : InvalidArgument: (:) [Invoke-Command], Parameter
BindingException
+ FullyQualifiedErrorId : AmbiguousParameterSet,Microsoft.PowerShell.Comma
nds.InvokeCommandCommand
If i use Invoke-Expression, instead i get the following :
Invoke-Expression : Unexpected token 'status' in expression or statement.
At E:\Andrew\MonitoreGate.ps1:20 char:28
+ $Result = Invoke-Expression <<<< $sCmd | Out-String
+ CategoryInfo : ParserError: (status:String) [Invoke-Expression]
, ParseException
+ FullyQualifiedErrorId : UnexpectedToken,Microsoft.PowerShell.Commands.In
vokeExpressionCommand
Should i be using Invoke-Command or Invoke-Expression or some other way? Is the $sCmd structure correct in regards to quotes?
The program is to run on same machine (not remotely).
Any help greatly appreciated,
Andrew
neither, instead use:
Start-Process -FilePath 'path_to_stccmd.exe' -ArgumentList "-rh sldcege-mie003 -rs nsccahs_dev -un Administrator -up STC -cb nsccahs_dev_cb -cmd 'status bobRRC_ADT_OUT_FMT'" -nonewwindow
if you dont see the output using the above...try this:
$exepath = 'path_to_stccmd.exe'
&$exepath arguments
I'm trying to execute the following two lines of code in PowerShell v2.0 as a job, and am having trouble. I think I have the syntax right, but I can't get it to do what I think it should do, so I clearly am doing something wrong...
$report = <command line thing>
invoke-expression $report
These two lines work in PowerShell. But when I try to put it into a start-job command:
start-job -scriptblock {invoke-expression $report} -argumentlist $report | wait-job | receive-job
I get the following error:
Cannot bind argument to parameter 'Command' because it is null.
+ CategoryInfo : InvalidData: (:) [Invoke-Expression], ParameterBindingValidationException
+ FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.InvokeExpre
ssionCommand
+ PSComputerName : localhost
I understand that error as saying that the argument I'm passing the invoke-expression is null, but, I'd thought that by passing $report in the -argumentlist param, it'd get through?
You cannot access $report directly unless you do:
-scriptblock {param($report) invoke-expression $report}
The param($report) part captures the $report variable passed in via -ArgumentList and makes it available for use inside the scriptblock.
I am trying to add an open varible to this command so when the data pulls from line 24 it adds it to the variable and makes it executable.
$data = Get-Content "C:\Users\bgriffiths\Documents\test.dat"
$data[24]
I have tried adding different formats to do this and nothing seems to work.
one command i tried was
invoke-command sql -query = $data
I get an error telling me
Invoke-Command : A parameter cannot be found that matches parameter name 'query'.
At line:4 char:26
+ invoke-command sql -query <<<< = $data
+ CategoryInfo : InvalidArgument: (:) [Invoke-Command], ParameterBindingException
+ FullyQualifiedErrorId : NamedParameterNotFound,Microsoft.PowerShell.Commands.InvokeCommandCommand
another command I have been trying to run is
$Command.CommandType.text = $data
the only error I get from this is
Property 'text' cannot be found on this object; make sure it exists and is settable.
At line:10 char:30
+ $Command.CommandType. <<<< text = $data
+ CategoryInfo : InvalidOperation: (text:String) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
I am at a lost on how to import file data into the script and have it run it.
I figured out how to run commands for sql through my powershell I had to actaully import the assembly list for the sql ps and then I was able to run the Invoke-SqlCmd
the script to add the information for sqlps to your windows ps is -
$ErrorActionPreference = "Stop"
$sqlpsreg="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps"
if (Get-ChildItem $sqlpsreg -ErrorAction "SilentlyContinue")
{
throw "SQL Server Powershell is not installed."
}
else
{
$item = Get-ItemProperty $sqlpsreg
$sqlpsPath = [System.IO.Path]::GetDirectoryName($item.Path)
}
#
# Preload the assemblies. Note that most assemblies will be loaded when the provider
# is used. if you work only within the provider this may not be needed. It will reduce
# the shell's footprint if you leave these out.
#
$assemblylist =
"Microsoft.SqlServer.Smo",
"Microsoft.SqlServer.Dmf ",
"Microsoft.SqlServer.SqlWmiManagement ",
"Microsoft.SqlServer.ConnectionInfo ",
"Microsoft.SqlServer.SmoExtended ",
"Microsoft.SqlServer.Management.RegisteredServers ",
"Microsoft.SqlServer.Management.Sdk.Sfc ",
"Microsoft.SqlServer.SqlEnum ",
"Microsoft.SqlServer.RegSvrEnum ",
"Microsoft.SqlServer.WmiEnum ",
"Microsoft.SqlServer.ServiceBrokerEnum ",
"Microsoft.SqlServer.ConnectionInfoExtended ",
"Microsoft.SqlServer.Management.Collector ",
"Microsoft.SqlServer.Management.CollectorEnum"
foreach ($asm in $assemblylist)
{
$asm = [Reflection.Assembly]::LoadWithPartialName($asm)
}
#
# Set variables that the provider expects (mandatory for the SQL provider)
#
Set-Variable -scope Global -name SqlServerMaximumChildItems -Value 0
Set-Variable -scope Global -name SqlServerConnectionTimeout -Value 30
Set-Variable -scope Global -name SqlServerIncludeSystemObjects -Value $false
Set-Variable -scope Global -name SqlServerMaximumTabCompletion -Value 1000
#
# Load the snapins, type data, format data
#
Push-Location
cd $sqlpsPath
Add-PSSnapin SqlServerCmdletSnapin100
Add-PSSnapin SqlServerProviderSnapin100
Update-TypeData -PrependPath SQLProvider.Types.ps1xml
update-FormatData -prependpath SQLProvider.Format.ps1xml
Pop-Location
Write-Host -ForegroundColor Yellow 'SQL Server Powershell extensions are loaded.'
Write-Host
Write-Host -ForegroundColor Yellow 'Type "cd SQLSERVER:\" to step into the provider.'
Write-Host
Write-Host -ForegroundColor Yellow 'For more information, type "help SQLServer".'
the link where I found this is http://blogs.msdn.com/b/mwories/archive/2008/06/14/sql2008_5f00_powershell.aspx
I want to create a script to remove a bunch of apps. I want to do this without user interaction once I've started the script.
This is the script I have so far; it doesn't work but hopefully you can see what I'm trying to do:
$App = Get-Content "C:\ListOFApps.txt" #get a list of apps
$args= '/quiet /norestart' # stores arguments for start-process
#gwmi gets the list of applications
# where selects just the apps im interested in removing
# start-process removes each app using msiexec with quiet and norestart options
gwmi win32_product | where { $App -contains $_.Name } | foreach {Start-Process 'msicexec /uninstall ' $_.IdentifyingNumber -ArgumentList $args -wait}'
This is the error that occurred:
ForEach-Object : Cannot process command because of one or more missing mandatory parameters: Process.
At C:\Users\username\AppData\Local\Temp\406f96a1-19b4-4e0d-af1b-b1ac2e32a6ba.ps1:3 char:62
+ gwmi win32_product| where { $App -contains $_.Name }| foreach <<<<
+ CategoryInfo : InvalidArgument: (:) [ForEach-Object], ParameterBindingException
+ FullyQualifiedErrorId : MissingMandatoryParameter,Microsoft.PowerShell.Commands.ForEachObjectCommand
$_.IdentifyingNumber
Start-Process 'msicexec /uninstall $_.IdentifyingNumber' -ArgumentList $args -wait
You have an unbalanced single quote on the end of the line with the "foreach." I suspect fixing that is only the start of your problems. Good luck.
Also you have the Process misspelled. Should be "msiexec" not "msicexec"