Quantcast
Channel: PowerShell.org » All Posts
Viewing all 13067 articles
Browse latest View live

Null-Valued Expression Error

$
0
0

Hello All,

I'm very new to Powershell and am trying to execute some code which will remove commas from certain fields in a CSV file, then output the result back to a file. While my script does generate the following error, it still does finish and create a new file when I run it from the Powershell ISE. However, I need to run this from a SQL job agent (i'm a data guy) and the error actually stops the job.

There error is here:

You cannot call a method on a null-valued expression.
At line:9 char:9
+ if ($i.Community_Name.split(',')[1])
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull

My code i'm running is here:

$array = Import-Csv -Path D:\DataExtracts\HolidayPricing\holiday.csv | Select UniqueID,Community_Name,Company_Number,LastUpdated,UnitType,MinStartMarketRate

$finalarray = @()

Foreach ($i in $array)
{
$newobject = New-Object System.Object
$newobject | Add-Member -Type NoteProperty -Name 'Unique ID' -Value $i.UniqueID
if ($i.Community_Name.split(',')[1])
{
$formatted = $i.Community_Name.split(',')[0] + ';' + $i.Community_Name.split(',')[1]
}
else
{
$formatted = $i.Community_Name.split(',')[0]
}
$newobject | Add-Member -Type NoteProperty -Name 'Community_Name' -Value $formatted
$newobject | Add-Member -Type NoteProperty -Name 'Company_Number' -Value $i.Company_Number
$newobject | Add-Member -Type NoteProperty -Name 'LastUpdated' -Value $i.LastUpdated
$newobject | Add-Member -Type NoteProperty -Name 'UnitType' -Value $i.UnitType
$newobject | Add-Member -Type NoteProperty -Name 'MinStartMarketRate' -Value $i.MinStartMarketRate
$finalarray += $newobject
}
$finalarray | Export-Csv -Path D:\DataExtracts\HolidayPricing\holiday_Out.csv


Reply To: Null-Valued Expression Error

$
0
0

At that point, either $i is empty of $i.Community_Name doesn't exist.

Note that there's no need to use $array…

foreach ($i in (Import-CSV …)) {}

Will save a bit of memory.

You might look into using Write-Verbose (you'll need to enable the Verbose pipeline by setting $VerbosePreference='Continue') to output the contents of $i

Write-Verbose "$i"

Before your If construct. That would let you see what $i really contains at that point. It's also possible that $i.Community_Name isn't evaluating as a String, but that'd usually be a different error. It's likely that Community_Name is coming up empty.

Reply To: Null-Valued Expression Error

$
0
0

Thanks, Don.

Community_Name is actually empty in one instance, when I run just the $array portion of the script it returns the data from the file, however the very last one is empty for all columns.

How can I handle this?

Reply To: Null-Valued Expression Error

$
0
0

Add another If construct to test the property for being equal to $null, or an empty string, before you try to do something with it.

Reply To: Null-Valued Expression Error

$
0
0

Or, fix your CSV file to not have a blank line at the end, if that's possible. Or, filter those out:

foreach ($i in (
  import-csv blah blah | where { $_.Community_Name -neq $null }
)) {}

Or something like that, logic-wise.

selecting items from an output

$
0
0

Hello

I got a weird question. Can I use powershell in a way to select "items" from an output. say get-vm or get-disk. I know PS is built around objects, so obviously it understands that each line is a separate thing and not just a stream of text.
my use case would be eg. select from the 10th to the 30th in the output and delete them. Just like in a file explorer.

Reply To: selecting items from an output

$
0
0

Hi Garegin,

It's certainly possible. Here's an idea of how that type of thing can be done, only with files as an example.. The first illustration is just to show that there are currently five files in the directory, and the second shows how we get the files, select the range of items we want, and then remove them. I've deliberately done from the second element in the array (1), to the third to show that we can also remove items in the middle of a list.

Set-Location D:\Temp\epguides
Get-ChildItem


    Directory: D:\Temp\epguides


Mode                LastWriteTime         Length Name                                                                                                                                                                                                                                                                               
----                -------------         ------ ----                                                                                                                                                                                                                                                                               
-a----        2/15/2015  10:09 PM            309 epguides.css                                                                                                                                                                                                                                                                       
-a----        2/15/2015  10:31 PM           3484 epguides.ps1                                                                                                                                                                                                                                                                       
-a----        2/15/2015  10:09 PM          72174 jquery.js                                                                                                                                                                                                                                                                          
-a----        2/15/2015  10:09 PM            429 manifest.json                                                                                                                                                                                                                                                                      
-a----        2/15/2015  10:09 PM           3048 modify.js        
PS 02/20/2015 06:53:24> Set-Location D:\Temp\epguides
$files = Get-ChildItem
$files[1..3] | Remove-Item -Force
Get-ChildItem



    Directory: D:\Temp\epguides


Mode                LastWriteTime         Length Name                                                                                                                                                                                                                                                                               
----                -------------         ------ ----                                                                                                                                                                                                                                                                               
-a----        2/15/2015  10:09 PM            309 epguides.css                                                                                                                                                                                                                                                                       
-a----        2/15/2015  10:09 PM           3048 modify.js                                     

Reply To: selecting items from an output

$
0
0
Get-VM | Out-GridView -PassThru | Remove-VM

This will give you a nice list view of all your VMs, and then if you select any of them and press OK, they will be removed.


Can't find anyone with strong PS and MS Server Suite Skills in Netherlands

$
0
0

Can anyone help me out? Finding it sooo difficult to get people with strong PowerShell and MS Server suite skills in the Netherlands, or who willing to move there permanently. 100% cloud and automation work, permanent role. Searching for over 6 months. SaaSplaza, Amstelveen, Noord Holland. plz drop me a private message if you know anyone. I'm close to despair.

And it's for my employers directly, so no agency rubbish.

Reply To: Managing .mof files. How do you avoid making multiple .mofs for the same node?

$
0
0

So is your suggestion that I would implement each "to be created VM" as a partial configuration of my localhost server?
Would this not also end up in me having to use different resource names for each partial configuration? I bet it would complain about that here as well. Would it?

Reply To: Managing .mof files. How do you avoid making multiple .mofs for the same node?

$
0
0

I'm not sure I understand the problem your running in to.

We are managing configs for close to 3000 machine with only one configuration script. There are plenty of If statements, so only sections of the config that are valid to a specific node run for that node run. The script is stored in Git so every one who needs to has access to it.

Reply To: selecting items from an output

Reply To: Restarting Script

$
0
0

So another question on this type of scenario…In the same code, I've added a ping feature to the top that will ping the machine name before proceeding. Now, I have it setup so that it pings, and if it finds the machine it will continue to the next menu option. My hiccup is trying to get it to prompt for the user to re-enter the machine name, and then re-run the whole pinging section on the new machine name. I can make it pop-up with a prompt for a new machine name, however the results are very strange.

If the re-entered machine name is valid, it doesn't ping and just continues to the next part of the script.

If it is invalid again, it acts like it is pinging again, but I get an error:

"Cannot convert value "\\PTLW95S7YY1\root\ccm:SMS_Client" to"System.Management.ManagementClass"…..

So it looks like it's proceeding with the code as normal here but it can't find the machine, so instead of pinging and re-prompting to fix it just continues.

I tried messing around with what you did with the last situation where I was trying to re-run part of the script, but I can't seem to get anything to work in full.

$caption = "Choose SCCM Schedule";
Write-Host "`nSCCM Task Scheduler" -Fore Magenta
Write-Host
$machine = Read-Host 'What is the machine name?'
Write-Host
Write-Host "Pinging Machine…" -Fore Yellow
Write-Host
[b]if [Test-Connection $machine -Quiet]{
Write-Host "Machine Found!" -Fore DarkGreen
}
else {
Write-Host "Machine Not Found – Check Name" -Fore Red
$machine = Read-Host 'What is the machine name'
}
[/b]Write-Host
$SMSCli = [wmiclass] "\\$machine\root\ccm:SMS_Client"
[int]$xMenuChoiceA = 0
while ( $xMenuChoiceA -lt 1 -or $xMenuChoiceA -gt 3 )
{
Write-host "1. Hardware Inventory" -fore Cyan
Write-host "2. Software Inventory" -fore Cyan
Write-host "3. Discovery Data" -fore Cyan
Write-Host 
[Int]$xMenuChoiceA = read-host "Select Task to Schedule"
 
Switch( $xMenuChoiceA )
{
  1{$SMSCli.TriggerSchedule("{00000000-0000-0000-0000-000000000001}"), "Scheduling Hardware Inventory"; break}
  2{$SMSCli.TriggerSchedule("{00000000-0000-0000-0000-000000000002}"), "Scheduling Software Inventory"; break}
  3{$SMSCli.TriggerSchedule("{00000000-0000-0000-0000-000000000003}"), "Scheduling Discovery Data"; break}
}
Write-Host
$message = Write-Host "Do you want to schedule another task?" -foregroundcolor Green
Write-Host
$yes = New-Object System.Management.Automation.Host.ChoiceDescription "&Yes"
$no = New-Object System.Management.Automation.Host.ChoiceDescription "&No"
$options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
$result = $host.ui.PromptForChoice($title, $message, $options, 0)
switch ($result)
{
        0 {$xMenuChoiceA = 0}
        1 {"You Chose No"}
}
 
}

Reply To: Nested Groups – User Properties

$
0
0

Hi Tim,

The code above is working well.
My poorly requested assistance meant to ask for help filtering out the resultant data set

I don't want to see users that are disabled nor do I want to see users that don't have the account expiry not set.

I'm trying to use something like Get-ADUser -filter {enabled -eq $true} -Prop Description……. with no luck.

I'm thinking it's an issue with what is returned from the function (ADNestedGroupMembers)

Thank you for your time!

Mike

Reply To: Nested Groups – User Properties

$
0
0

And while we (ok you) are at it, I'd like to know what the path to their user object is (like when you view advanced features in AD and select the user\computer 'OBJECT' tab.


Reply To: How do I list ActiveSync device users by manager

$
0
0

Ok I now have a the data I need in one csv file.

Now I have to take:

CN=Joe Bloggs,OU=Network,OU=IT,OU=Office,OU=XXXXXX,DC=xxx,DC=yyyyyyyyyyy,DC=com

and strip it down to leave Joe Bloggs

Any pointers?

Install Office Service pack 2

$
0
0

I would like to install office sp2 remotely by creating a PSSession.

I will have the kb package in a share .. This is what I have so far

$COMPAREDATE=GET-DATE 
$NumberDays=14
$Pcs = $computers  | Get-QADComputer -SizeLimit 0 -IncludedProperties LastLogonTimeStamp | where { ($CompareDate-$_.LastLogonTimeStamp).Days -lt $NumberDays } 
 
 
$s = new-PSSession -computername ($PCs  |  select -ExpandProperty name)  -ErrorAction SilentlyContinue
 
 
Invoke-Command -Session $s  -ScriptBlock {  
 
     net use z: \\Servre01\Share  
 
     .\officesp2010-kb2687455-fullfile-x64-en-us.exe /quiet /norestart /log:c:\office.txt
 
       }

Reply To: Restarting Script

$
0
0

I tried doing it with a IF statement on the TRUE/FALSE output of the Test-Connection command, but no luck:

#—–Start Ping Target Machine—–#
$Pingcheck = {
Write-Host "Pinging Machine…" -Fore Yellow
$Ping = Test-Connection $machine -Quiet
if ($Ping -eq $true){
Write-Host "Machine Found!" -Fore DarkGreen
}
else{
if ($Ping -eq $false){
Write-Host "Machine Not Found – Check Name" -Fore Red
$machine = Read-Host 'What is the machine name'
&$Pingcheck
}
}
}
 
#—–End Ping Target Machine—–#

Reply To: Install Office Service pack 2

$
0
0

You have a couple of problems, one being that the second-hop from the computer to the file share will be un-authenticated unless you've set up multi-hop delegation already. The second is that the installer may not run correctly without a user being logged on at the time; you'll need to test that.

Reply To: Managing .mof files. How do you avoid making multiple .mofs for the same node?

Viewing all 13067 articles
Browse latest View live