Powershell - changing value of returned SQL data variable fails - powershell

In Powershell, I am doing a SQL query for a single row of data. Lets say $data for example.
The response from the query a System.Data.DataSet type. Within it, there is a tables property that has the data I need.
$data.Tables
ServerName : Server15
SamAccount : Admin-Server15
LastPWDReset : 1/15/2019 12:00:00 AM
LastPWDResetAttempt :
I don't intend to write this data back out of anything. Instead, I want to display it, and convert the empty "LastPWDResetAttemp" to "NONE" where it is blank.
I thought it would be done like this:
$data.Tables.lastPWDResetAttempt = "None"
but that gives me an error The property 'lastPWDResetAttempt' cannot be found on this object. Verify that the property exists and can be set.
I can't help but think I am missing some conversion from "Dataset" to "String".
I've tried to-string but in doing so, I ended up with just a string of data and not the headings. Nothing I could update, or easily use to build my eventual table.
My work around:
$webdata = "" | select ServerName,SamAccount,LastPWDReset,LastPWDResetAttempt
$webdata.ServerName = $data.tables.servername
$webdata.SamAccount = $data.tables.samaccount
$webdata.LastPWDReset = $data.tables.LastPWDReset
$webdata.LastPWDResetAttempt = $data.tables.LastPWDResetAttempt
$webdata.LastPWDResetAttempt = "Never"
works. I just can't believe there isn't an easier way, nor do I understand why I can view a list of the data, just to not then be able to set it.

I think it is because Tables is an array and does not have the property LastPWDResetAttempt.
You can try the following instead:
$data.Tables[0].Rows[0].LastPWDResetAttempt = "None"
Also I think your workaround, though it may contain more lines of code, is actually a better solution though.

Related

Powershell - Hashtable in Foreach statement

I'm looking to get an idea of how to go about this.
In a for each loop. Do you need to define the variables before using them in a hash table for TITLE,DEPARTMENT,MANANGER,OFFICE
Currently, this does not set anything for the users in the foreach statement.
Foreach ($userdata in $datafile) {
$SetADUserdetails = #{
Identity=$userdata.Adusername
Title = $userdata.title
Office=$userdata.office
Department=$userdata.department
Manager=$userdata.manager
}
Set-ADUser #SetADUserdetails # Need to add Domain Controller Parameter
}
This is how the datafile looks like.
GivenName,Surname,Office,Title,Path,Manager,Department,Adusername
I'm sure if I set the variable first and then match the variable to hash table keys, it going to work.
Please let me know your thought. I'm fair new to PowerShell. I tried searching the internet for the correct method. No luck. just want to double-check before I define variables.
Yes, variables are rendered at runtime. When you define the hashtable the key will have the variable assigned at the time the hashtable was defined, or the last value that was set for that key with =.
In your code example, the keys of $SetADUserdetails have no value because the $userdata Properties have no value. Make sure that $datafile has the correct entries you are expecting and confirm each iteration of $userdata has some value. Either $datafile is incorrect or you are referencing each column by the wrong column name.

Import-Excel only data without header in string - PowerShell

I have installed Import-Excel Module for PowerShell by dfinke which has a great functionality but I'm facing some troubles with the headers.
I would like to insert only the text into a string array, but instead, it comes with the header even when -NoHeader is declared. According to the documentation it's not its function not insert the header in the variable but I'm looking for a way to do it. So far I came with a newbie solution of $xlsxArray | Format-Table -HideHeaders | Out-File C:\temp\info.txt and then remove the spaces with .Trim() so the file doesn't get written #{P1=ContentofTheCell}.
Is there a better way to accomplish it?
Thank you so far.
You didn't give enough detail about the desired output, but I'll try to give guidance.
Import-Excel will return objects. Normally the column headers become the property names on the objects. When you use -NoHeader, the property names are simply named P1, P2 etc... An object's properties must have names. If you want the data from those properties you may have to process differently. You can access the properties like any other object collection:
$ExcelData = Import-Excel "C:\Temp\Some.xlsx"
$ExcelData.PropertyName
The PropertyName would be the column header from the file. So let's say I had a colum named Balance in that file, then the example would something like:
$ExcelData = Import-Excel "C:\Temp\Some.xlsx"
$ExcelData.balance
Output:
7254.74
4268.16
3051.32
64.77
323.22
146.62
14798.83
Note: these are pretty simple examples. Obviously things can get more complex.

How do I create and array with two heads and LOTS of members

Preface: Please tell me a better way of doing this if you know of any! Even if it changes everything.
I have a powershell script that works with Net-SNMP to store the current value of an OID, change it and then check and store the values. Right now the previous and new values are stored in their own variable. There are about 160 OIDs that I need to change on >1000 nodes in my environment.
For Example for Previous and New values:
$P_vpwrSystemTempCompensation_0 = & '.\SnmpGet.exe' -q -r:"$ip" -v:2c -c:public -o:.1.3.6.1.4.1.13858.2.2.1.0
$N_vpwrSystemTempCompensation_0 = & '.\SnmpGet.exe' -q -r:"$ip" -v:2c -c:public -o:.1.3.6.1.4.1.13858.2.2.1.0
I'm try to figure the best way to store these and output into an CSV. I would like it to be formatted liked this:
Each CSV will be saved with the name and IP of the node I'm hitting.
You can make an object like this in a loop, and that could be exported to csv:
$oid = 'vpwrSystemTempCompensation.0'
$prev = 2
$new = 4647
[pscustomobject]#{OID=$oid; Previous=$prev; New=$new}
OID Previous New
--- -------- ---
vpwrSystemTempCompensation.0 2 5647
By the way, you don't need the call operator to run smnpget, if you don't put it in quotes:
.\SnmpGet.exe -q -r:$ip -v:2c -c:public -o:.1.3.6.1.4.1.13858.2.2.1.0

SharePoint REST: Column does not exist error

I'm calling a REST API with a SharePoint Designer workflow on SharePoint online. I'm setting the column name with a variable, and when i put the variable into my URL to call it it says "Column [name] does not exist".
Annoying part is when I call just /items? I can see the column in the result, but if I try select it or filter by it I get 'does not exist'. I have alot of these columns similarly named, and I get the error for all of them.
I am using the internal name, I have tried adding "OData_" to the front. I've tried typing the url manually in the browser and entering values (incase the variable was causing issues) but I get the same error, column does not exist. but i can see it them I call all items. :(
so I have quite a few columns with naming convention "[Q#] Score [#]" eg "Q4 Score 2". The internal name that's clearly appearing in the full items results is "Q4_x0020_Score_x0020_2".
This works:
https://MYSITE.sharepoint.com/sites/portal/intranet/CorpServices/QSR/_api/web/lists/GetbyTitle('Audit')/Items?
and I get big full normal REST results that includes the line:
0
However if I try:
https://MYSITE.sharepoint.com/sites/portal/intranet/CorpServices/QSR/_api/web/lists/GetbyTitle('Audit')/Items?$Select=Q4_x0020_Score_x0020_2
Then I get:
-2146232832, Microsoft.SharePoint.SPExceptionColumn 'Q4_x0020_Score_x0020_2' does not exist. It may have been deleted by another user.
I expect to be able to select that column (and the dozens like it) but none work. I've searched all similar problems on the forum and they've usually got a spelling mistake or forgot the ODATA_ but i cant seem to get the problem. Please help.
It seemed to be working intermittently.... So it was in fact just a naming error...... Half of the columns were [Q#]_x0020_Score_x0020_[#] and half were [Q#]_x0020_score_x0020_[#]. The word "Score" was capitalized on some and not others. I Didn't realize the HTTP Calls were case sensitive. Now I have added a bunch of if statements to handle the different variations haha. Thanks for reading.
Judging by the naming convention you are on an older version of SharePoint. The x0020 is the value for a space. Ideally when you first create the column you would name it without the spacing. For example UserInformation. Then come in and edit the name after the fact and call it User Information. If you click on the title name and look at the URL, you will see what the actual name of the column is at the end of the URL. It is case sensitive because you can have a column named score and Score which is ultimately why it wasn't working.
Must load all fields like this
var lists = context.Web.Lists;
context.Load(lists);
context.ExecuteQuery();
CamlQuery query = new CamlQuery();
query.ViewXml = #"";
var list = lists.GetById("file.guid");
var listitems = list.GetItems(query);
context.Load(listitems);
context.ExecuteQuery();
var creationInformation = new ListItemCreationInformation();
var newItem=list.AddItem(creationInformation);
var fields = list.Fields;
context.Load(fields);
context.ExecuteQuery();

Add rows in smartsheets using python

How do I take a list of values, iterate through it to create the needed objects then pass that "list" of objects to the API to create multiple rows?
I have been successful in adding a new row with a value using the API example. In that example, two objects are created.
row_a = ss_client.models.Row()
row_b = ss_client.models.Row()
These two objects are passed in the add row function. (Forgive me if I use the wrong terms. Still new to this)
response = ss_client.Sheets.add_rows(
2331373580117892, # sheet_id
[row_a, row_b])
I have not been successful in passing an unknown amount of objects with something like this.
newRowsToCreate = []
for row in new_rows:
rowObject = ss.models.Row()
rowObject.cells.append({
'column_id': PM_columns['Row ID Master'],
'value': row
})
newRowsToCreate.append(rowObject)
# Add rows to sheet
response = ss.Sheets.add_rows(
OH_MkrSheetId, # sheet_id
newRowsToCreate)
This returns this error:
{"code": 1062, "errorCode": 1062, "message": "Invalid row location: You must
use at least 1 location specifier.",
Thank you for any help.
From the error message, it looks like you're missing the location specification for the new rows.
Each row object that you create needs to have a location value set. For example, if you want your new rows to be added to the bottom of your sheet, then you would add this attribute to your rowObject.
rowObject.toBottom=True
You can read about this location specific attribute and how it relates to the Python SDK here.
To be 100% precise here I had to set the attribute differently to make it work:
rowObject.to_bottom = True
I've found the name of the property below:
https://smartsheet-platform.github.io/smartsheet-python-sdk/smartsheet.models.html#module-smartsheet.models.row
To be 100% precise here I had to set the attribute differently to make it work:
Yep, the documentation isn't super clear about this other than in the examples, but the API uses camelCase in Javascript, but the same terms are always in snake_case in the Python API (which is, after all, the Pythonic way to do it!)