PowerShell variables not being expanded in string? - powershell

I have written some PowerShell
param (
[Parameter(Mandatory=$true)][string]$company,
[Parameter(Mandatory=$true)][string]$output
)
...
$objRecordset.Open("Select Col1, Col2, Col3 From $company_Table1.DBF", $objConnection,$adOpenStatic,$adLockOptimistic)
I am running it using
.\Test.ps1 -company A -output C:\test.txt
but for some reason the $company variable isn't being expanded even though it's in "quotes"?
Exception calling "Open" with "4" argument(s): "File '.dbf' does not exist."
At line:17 char:1
+ $objRecordset.Open("Select Col1, Col2, Col3 From $company_Table1. ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ComMethodTargetInvocation
When I hardcode it as A_Table1.dbf it works fine ...

The error message it telling you that PowerShell is parsing $company_Table1 as the name of the variable; _ is not acting as a delimiter.
You need to tell PowerShell where the variable name being and ends using curl braces {}
${company}_Table1.DBF

.DBF stands for database file.
You are trying to do a select on the database and not on a table in that database.
So it makes sense this isn't working.
it should be Select * from TBL_Whatever LIMIT 0,1 ....
So you first need to open a connection to the DB file itself and then do your select against a TABLE in that DB.

Related

Add xml object to xml file in PowerShell

I am trying to create an RDCMan file (.rdg xml file) using PowerShell. I have started by defining this template
$newFileTemplate = '<?xml version="1.0" encoding="utf-8"?>
<RDCMan programVersion="2.7" schemaVersion="3">
<file>
<properties>
<expanded>False</expanded>
<name>Office Servers</name>
</properties>
<displaySettings inherit="None">
<liveThumbnailUpdates>True</liveThumbnailUpdates>
<allowThumbnailSessionInteraction>False</allowThumbnailSessionInteraction>
<showDisconnectedThumbnails>True</showDisconnectedThumbnails>
<thumbnailScale>1</thumbnailScale>
<smartSizeDockedWindows>True</smartSizeDockedWindows>
<smartSizeUndockedWindows>False</smartSizeUndockedWindows>
</displaySettings>
</file>
</RDCMan>
'
before creating an xml object like so
$File = 'D:\Test.rdg'
Set-Content $File $newFileTemplate
[XML]$XMLFile = [XML](Get-Content $File)
I would then like to define a function for adding a group of servers
# This function adds a new group element
Function Add-NewGroup($GroupName,$RDCManFile) {
[xml]$GroupXML = #"
<group>
<properties>
<expanded>False</expanded>
<name>$GroupName</name>
</properties>
</group>
"#
$Child = $RDCManFile.ImportNode($GroupXML.group, $true)
$RDCManFile.Configuration.AppendChild($Child)
}
And call it by running
Add-NewGroup('DCs',$XMLFile)
This would allow me to populate the xml file with all of the OUs in AD.
Is anyone able to tell me where I am going wrong?
Thanks
Update: The error I am getting is
You cannot call a method on a null-valued expression.
At D:\Users\user\Desktop\Projects\RDCMan\Create-RDG.ps1:179 char:5
+ $Child = $RDCManFile.ImportNode($GroupXML.group, $true)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At D:\Users\user\Desktop\Projects\RDCMan\Create-RDG.ps1:180 char:5
+ $RDCManFile.Configuration.AppendChild($Child)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
And I am trying to do what was suggested here https://stackoverflow.com/a/29693625/2165019
The property 'Configuration' cannot be found on this object. Verify that the property exists. error at $RDCManFile.Configuration.AppendChild($Child).
If I can accept a .rdg file format and structure as defined in the Script to create a Remote Desktop Connection Manager group from Active Directory Technet article then I'd use
$RDCManFile.RDCMan.file.AppendChild($Child)
Follow the Theo's answer about calling a function.
Pass parameters as positional
Add-NewGroup 'DCs' $XMLFile
or as named
Add-NewGroup -GroupName 'DCs' -RDCManFile $XMLFile
This error (and second) most likely means that $RDCManFile is null.
You cannot call a method on a null-valued expression.
At D:\Users\user\Desktop\Projects\RDCMan\Create-RDG.ps1:179 char:5
+ $Child = $RDCManFile.ImportNode($GroupXML.group, $true)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Try adding $RDCManFile | Out-Host at the top of the Add-NewGroup function to check what's contained in that variable.
You need to change the way you are calling the function.
Because of the comma in between the parameters, PowerShell sees this as one array value, so only parameter $GroupName will receive something.
Furthermore, you should not use brackets around the params, call the function like this:
Add-NewGroup 'DCs' $XMLFile
or send the parameters using their names:
Add-NewGroup -GroupName 'DCs' -RDCManFile $XMLFile

how to execute an exe with variable value for path and arguments

I'm trying to execute in my powershell script the command below :
D:\Apps\Documentum\product\7.3\bin\idql.exe -udmadmin -pPassword dctm04 -RC:\temp\documentum\session_list.txt -w20 > C:\temp\documentum\session_logstash.txt
In my powershell script I do that:
$DOCBASE="dctm04"
$USER_DOCBASE="dmadmin"
$USER_PWD="Password01"
$IDQL_PATH="D:\Apps\Documentum\product\7.3\bin"
$QRY_SESSIONS="C:\temp\documentum\session_list.txt"
$QRY_LOG_SESSIONS="C:\temp\documentum\session_logstash.txt"
$IDQL_PATH\idql.exe -u$USER_DOCBASE -p$USER_PWD $DOCBASE -R$QRY_SESSIONS -w20 > $QRY_LOG_SESSIONS
But it doesn't work properly, I receive the error below :
At C:\temp\documentum\Generate.ps1:49 char:13
+ $IDQL_PATH\idql.exe -u$USER_DOCBASE -p$USER_PWD $DOCBASE -R$QRY_SESSIONS -w20 ...
+ ~~~~~~~~~
Unexpected token '\idql.exe' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParseException
+ FullyQualifiedErrorId : UnexpectedToken
I think, i don't use variable properly on my command.
Please note my powershell version is :
PS C:\temp\documentum> $PSVersionTable.PSVersion
Major Minor Build Revision
----- ----- ----- --------
4 0 -1 -1
could you give me the solution in order to solve my problem
The reason is that combining a string to executable name makes no sense to Powershell's parsing rules. Use the call operator & or Invoke-Item. Like so,
$ssms="C:\Program Files (x86)\Microsoft SQL Server\140\Tools\Binn\ManagementStudio"
PS C:\> $ssms\ssms.exe
At line:1 char:6
+ $ssms\ssms.exe
+ ~~~~~~~~~
Unexpected token '\ssms.exe' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : UnexpectedToken
C:\>& $ssms\ssms.exe
# Launches SSMS succesfully
C:\>Invoke-Item $ssms\ssms.exe
# Launches SSMS succesfully
There's nice a document about running executables.

How to execute PowerShell Net MessageBox in cmd/batch

I have a batch file with lot of stuff. I there is one Alert Window with info for user.
On Windows Pro I'm using Msg command for it and it works fine.
On Windows Home there is no Msg, so I got the idea to use PowerShell instead:
[System.Windows.Forms.MessageBox]::Show("my text")
which works fine in PowerShell.
-However, when I try to use it in batch or execute it directly in Cmd, I only get the text:
C:\Windows\System32>powershell {[System.Windows.Forms.MessageBox]::Show("\""my text"\"")}
[System.Windows.Forms.MessageBox]::Show("my text")
Or I get errors:
C:\Windows\System32>powershell -command [System.Windows.Forms.MessageBox]::Show("my text")
At line:1 char:41
+ [System.Windows.Forms.MessageBox]::Show(my text)
+ ~
Missing ')' in method call.
At line:1 char:41
+ [System.Windows.Forms.MessageBox]::Show(my text)
+ ~~
Unexpected token 'my' in expression or statement.
At line:1 char:48
+ [System.Windows.Forms.MessageBox]::Show(my text)
+ ~
Unexpected token ')' in expression or statement.
+ CategoryInfo : ParserError: (:) [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : MissingEndParenthesisInMethodCall
or
C:\Windows\System32>powershell -command "& {[System.Windows.Forms.MessageBox]::Show('my text')}"
Unable to find type [System.Windows.Forms.MessageBox].
At line:1 char:4
+ & {[System.Windows.Forms.MessageBox]::Show('my text')}
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Windows.Forms.MessageBox:TypeName) [],
RuntimeException
+ FullyQualifiedErrorId : TypeNotFound
What should I do to get it to work?
(without rewriting the whole script to PowerShell, that is)
As TheMadTechnician stated, you may need to load it first.
This is effectively the same answer as theirs just over a couple of lines:
#Echo Off
PowerShell -Command^
"[Reflection.Assembly]::LoadWithPartialName('System.Windows.Forms')|Out-Null;"^
"[System.Windows.Forms.MessageBox]::Show(\"my text\")"
Pause
…and whilst double quotes around my text is not necessary, I've used them to show you the escapes.
You need to load the type before you can invoke it. You can do this:
powershell -command "[reflection.assembly]::LoadWithPartialName('System.Windows.Forms')|out-null;[windows.forms.messagebox]::Show('my message')"

Powershell: Adding element to hashtable failed

PS C:\Users\Hind> $b=#{}
PS C:\Users\Hind> $b+={k="a";v="b"}
A hash table can only be added to another hash table.
At line:1 char:1
+ $b+={k="a";v="b"}
+ ~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : AddHashTableToNonHashTable
Why did it fail? How can I add one element to a hashtable successfully?
Correction, this fails because you are missing the # character in front of #{k="a";b="b"}
PS C:\Users\Hind> $b=#{}
PS C:\Users\Hind> $b+=#{k="a";v="b"}
#{} is declaring a new hash table. {} is a script block. They are not the same.
Initialising the hashtable should be with round bracket instead of curly brackets
$b=#()
$b+=#{k="a";v="b"}

PowerShell error 'can't call null-value expresssion' [duplicate]

I am simply trying to create a powershell script which calculates the md5 sum of an executable (a file).
My .ps1 script:
$answer = Read-Host "File name and extension (ie; file.exe)"
$someFilePath = "C:\Users\xxx\Downloads\$answer"
If (Test-Path $someFilePath){
$stream = [System.IO.File]::Open("$someFilePath",[System.IO.Filemode]::Open, [System.IO.FileAccess]::Read)
$hash = [System.BitConverter]::ToString($md5.ComputeHash($stream))
$hash
$stream.Close()
}
Else{
Write-Host "Sorry, file $answer doesn't seem to exist."
}
Upon running my script I receive the following error:
You cannot call a method on a null-valued expression.
At C:\Users\xxx\Downloads\md5sum.ps1:6 char:29
+ $hash = [System.BitConverter]::ToString($md5.Compute ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
To my understanding, this error means the script is attempting to do something, but another part of the script does not have any information to permit the first part of the script to work properly. In this case, $hash.
Get-ExecutionPolicy outputs Unrestricted.
What is causing this error?
What exactly is my null valued expression?
Any help is appreciated. I apologize if this is trivial and will continue my research.
References:
http://blogs.technet.com/b/heyscriptingguy/archive/2013/03/27/troubleshoot-the-invokemethodonnull-error-with-powershell.aspx
How to get an MD5 checksum in PowerShell
The simple answer for this one is that you have an undeclared (null) variable. In this case it is $md5. From the comment you put this needed to be declared elsewhere in your code
$md5 = new-object -TypeName System.Security.Cryptography.MD5CryptoServiceProvider
The error was because you are trying to execute a method that does not exist.
PS C:\Users\Matt> $md5 | gm
TypeName: System.Security.Cryptography.MD5CryptoServiceProvider
Name MemberType Definition
---- ---------- ----------
Clear Method void Clear()
ComputeHash Method byte[] ComputeHash(System.IO.Stream inputStream), byte[] ComputeHash(byte[] buffer), byte[] ComputeHash(byte[] buffer, int offset, ...
The .ComputeHash() of $md5.ComputeHash() was the null valued expression. Typing in gibberish would create the same effect.
PS C:\Users\Matt> $bagel.MakeMeABagel()
You cannot call a method on a null-valued expression.
At line:1 char:1
+ $bagel.MakeMeABagel()
+ ~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
PowerShell by default allows this to happen as defined its StrictMode
When Set-StrictMode is off, uninitialized variables (Version 1) are assumed to have a value of 0 (zero) or $Null, depending on type. References to non-existent properties return $Null, and the results of function syntax that is not valid vary with the error. Unnamed variables are not permitted.