Can I pass a string parameter to MongoDB.Driver.QueryDocument?
For the same scripts following, 1) returns document and 2) returns null.
1)
$query = new-object MongoDB.Driver.QueryDocument("item", "car")
$found = $mongoCollection.FindOne($query)
2)
$comp = "car"
function Get-Document($comp){
$query = new-object MongoDB.Driver.QueryDocument("item", $comp)
$found = $mongoCollection.FindOne($query)
return $found
}
$result = Get-Document $comp
Write-host $result
I don't have experience with MongoDB, but I don't see why the second code snippet shouldn't work if the first one does. I think the problem is that your function doesn't actually return anything.
PowerShell functions return all non-captured output to the caller, so you need to remove the assignment $found = ... to make the function return the result (and of course you need to call it, too):
$comp = "car"
function Get-Document($item){
$query = new-object MongoDB.Driver.QueryDocument("item", $item)
$mongoCollection.FindOne($query)
}
$found = Get-Document $comp
Related
I wish to go through a sharepoint list and if a property (a choice field named Status) is a certain value then change the author of that item.
Add-PSSnapin Microsoft.SharePoint.Powershell
$web = Get-SPWeb "http://site"
$library = $web.Lists["UserInfo"]
$newUser = $web.EnsureUser("user1")
$oldUser = $web.EnsureUser("user2")
foreach ($item in $library.Items)
{
#$userfield = New-Object Microsoft.SharePoint.SPFieldUserValue($web,$item["DocumentAuthorColumnInternalName"].ToString())
$userfield = New-Object Microsoft.SharePoint.SPFieldUserValue($web,$item["Author"].ToString())
$userfield = New-Object Microsoft.SharePoint.SPFieldUserValue($web,$item["Author"].ToString())
$login = $userfield.User.LoginName
#if ($login -eq $oldUser.LoginName)
if ($login -eq $oldUser.LoginName)
{
#if($item["Status"] eq 'Fully Implemented')
#{
$item["Author"] = $newUser
#if you are using default "Author" column, you need to set the following as well:
$item.Properties["vti_author"] = $newUser.LoginName
$item.UpdateOverwriteVersion() #this saves changes without incrementing the version
#}
}
$login = $null
}
$web.Dispose();
I can get it working but when I reach the line
if($item["Status"] eq 'Fully Implemented')
It causes an error
unexpected token 'eq'
Have you just missed the hyphen in eq? So it should be:
if($item["Status"] -eq 'Fully Implemented')
{
}
I have function with a foreach inside a foreach. My hashtable set inside the foreach is not accessible outside and I don't understand why.
The scope of sampletab is in "Script"
function Generate(){
$script:sampletab=#{}
$y=0
$samples = Invoke-Sqlcmd -Query "SELECT * FROM ..."
foreach ($row in $samples)
{
$paramID = $row["xxx"]
$query = "SELECT * FROM ... ${paramID};"
$parameters = Invoke-Sqlcmd -Query $query
foreach ($row in $parameters)
{
$name = "coucou"
$name = $row["name"]
$sampletab[$y] = #{
$name = $row["value"]
}
}
$y++
break
}
}
Generate
echo $sampletab[0].Keys # gives me only 1 key, should be 20 keys
Okay I found it. It's missing the "+="
$name = $row["name"]
$sampletab[$y] += #{
$name = $row["value"]
}
thank you !
I have found a great answer on Stack Overflow that explains how to have a powershell function that runs some SQL to return a single value.
What I'm not understanding is how to call the function and place the result into a variable that I can use later? Any help would be appreciated
https://stackoverflow.com/a/22715645/2461666
[string] $Server= "10.0.100.1",
[string] $Database = "Database123",
[string] $SQLQuery= $("SELECT [FeedID] FROM [dbo].[FeedList] WHERE [FeedFileName] = 'filename.txt'")
function GenericSqlQuery ($Server, $Database, $SQLQuery) {
$Connection = New-Object System.Data.SQLClient.SQLConnection
$Connection.ConnectionString = "server='$Server';database='$Database';trusted_connection=true;"
$Connection.Open()
$Command = New-Object System.Data.SQLClient.SQLCommand
$Command.Connection = $Connection
$Command.CommandText = $SQLQuery
$Reader = $Command.ExecuteReader()
while ($Reader.Read()) {
$Reader.GetValue($1)
}
$Connection.Close()
}
This is what I am currently trying but it doesn't seem to be working at all...
$myvariable = GenericSqlQuery
Awesome to see you searched stack overflow for an answer first Tommy!
Think I found another one to help you!
I have found something that may help:
powershell function output to variable
Below is from the above link
function getip {
$strComputer = "computername"
$colItems = GWMI -cl "Win32_NetworkAdapterConfiguration" -name "root\CimV2" -comp $strComputer -filter "IpEnabled = TRUE"
ForEach ($objItem in $colItems) {
$objItem.IpAddress
}
}
$ipaddress = getip
Okay, the way I have got it to work for me in this situation is to pass the value to a variable within my function and then within my function return the variable like this....
while ($Reader.Read()) {
$SQLResult = $Reader.GetValue($1)
return $SQLResult
}
I would like to find all cells in a range based on a property value using EPPlus. Let's say I need to find all cells with bold text in an existing spreadsheet. I need to create a function that will accept a configurable properties parameter but I'm having trouble using a property stored in a variable:
$cellobject = $ws.cells[1,1,10,10]
$properties = 'Style.Font.Bold'
$cellobject.$properties
$cellobject.{$properties}
$cellobject.($properties)
$cellobject."$properties"
None of these work and cause a call depth overflow.
If this way wont work, is there something in the library I can use?
Edited: To show the final solution I updated the function with concepts provided by HanShotFirst...
function Get-CellObject($ExcelSheet,[string]$PropertyString,[regex]$Value){
#First you have to get the last row with text,
#solution for that is not provided here...
$Row = Get-LastUsedRow -ExcelSheet $ExcelSheet -Dimension $true
while($Row -gt 0){
$range = $ExcelSheet.Cells[$Row, 1, $Row, $ExcelSheet.Dimension.End.Column]
foreach($cellObject in $range){
if($PropertyString -like '*.*'){
$PropertyArr = $PropertyString.Split('.')
$thisObject = $cellObject
foreach($Property in $PropertyArr){
$thisObject = $thisObject.$Property
if($thisObject -match $Value){
$cellObject
}
}
}
else{
if($cellObject.$PropertyString -match $Value){
$cellObject
}
}
}
$Row--
}
}
#The ExcelSheet parameter takes a worksheet object
Get-CellObject -ExcelSheet $ws -Property 'Style.Font.Bold' -Value 'True'
Dot walking into properties does not really work with a string. You need to separate the layers of properties. Here is an example for an object with three layers of properties.
# create object
$props = #{
first = #{
second = #{
third = 'test'
}
}
}
$obj = New-Object -TypeName psobject -Property $props
# outputs "test"
$obj.first.second.third
# does not work
$obj.'first.second.third'
# outputs "test"
$a = 'first'
$b = 'second'
$c = 'third'
$obj.$a.$b.$c
In your example this would be something like this:
$cellobject = $ws.cells[1,1,10,10]
$p1 = 'Style'
$p2 = 'Font'
$p3 = 'Bold'
$cellobject.$p1.$p2.$p3
Or you can do it a bit dynamic. This should produce the same result:
$cellobject = $ws.cells[1,1,10,10]
$props = 'Style.Font.Bold'.Split('.')
$result = $cellobject
foreach ($prop in $props) {
$result = $result.$prop
}
$result
And since its Friday, here is a function for it :)
function GetValue {
param (
[psobject]$InputObject,
[string]$PropertyString
)
if ($PropertyString -like '*.*') {
$props = $PropertyString.Split('.')
$result = $InputObject
foreach ($prop in $props) {
$result = $result.$prop
}
} else {
$result = $InputObject.$PropertyString
}
$result
}
# then call the function
GetValue -InputObject $cellobject -PropertyString 'Style.Font.Bold'
I am trying to generate the next available ad account using incremental numbers. for example, my domain currently has accounts names"opr1000-opr1014", so when i run my script, i should expect opr1015, instead it gets stuck in a loop and never returns a value. I have it running a do while loop and increasing the numerical value in increments until it finds an unused value at which point the do while loop should no longer be true and the script should end. anyone have any ideas?
$Account = "opr"
$Accountnum = "1000"
$Accountname = $account + $Accountnum
$Accountint = $account + $int
$int = [System.Decimal]::Parse($Accountnum)
do{
$query = "(&(objectClass=user)(samaccountname=$Accountname))"
$result = ([adsisearcher]$query).FindOne()
If($result){$int++}
}While($accountint)
"$account$Int"
There are quite few mistakes, see this:
$Account = "opr"
$Accountnum = 1000
do
{
$Accountname = $Account + $Accountnum;
$query = "(&(objectClass=user)(samaccountname=$Accountname))"
$result = ([adsisearcher]$query).FindOne()
if($result -eq $false)
{
break
}
$Accountnum++
} while($true)
$Account = "opr"
$Accountnum = 1000
do
{
$Accountname = $Account + $Accountnum;
$query = "(&(objectClass=user)(samaccountname=$Accountname))"
$result = ([adsisearcher]$query).FindOne()
if($result)
{
$Accountnum++
}else{
break
}} while($true)
"$Account$Accountnum"