Powershell unexpected token - powershell

have a great 2013. I am getting my hands wet on my first PS Script and I am stuck on a very common error, the "Unexpected Token" error. I've searched the internet, but could not find an answer, so please help me out.
If ($_.Voorvoegsel.Trim() -ieq "") {
$dn = $_.Voornaam.Trim() + " "
$dn += $_.Achternaam.Trim()
$email = $_.Voornaam.substring(0,1).ToLower() + "."
$email+= $_.Achternaam.Trim().ToLower() + "#test.nl
} Else {
$dn = $_.Voornaam.Trim() + " "
$dn += $_.Voorvoegsel.Trim() + " "
$dn += $_.Achternaam.Trim()
$email = $_.Voornaam.substring(0,1).ToLower() + "."
$email += $_.Voorvoegsel.Replace(" ","").ToLower()
$email += $_.Achternaam.Trim().ToLower() + "#test.nl
}
The strange thing is that it errors on the $_.Voorvoegsel variable in the else statement:
Unexpected token '
$dn += $_.Voorvoegsel.Trim()
$dn += ' in expression or statement.
At C:\Users\Public\Documents\PSImportTest.ps1:42 char:12
+ $dn = $_ <<<< .Voornaam.Trim() + " "
+ CategoryInfo : ParserError: (
$dn += $_....m()
$dn += :String) [], ParseException
+ FullyQualifiedErrorId : UnexpectedToken
Anyone out there who sees what my blind spot is here?

It may be that you are missing an end quote on line 5:
$email += $_.Acternaam.Trim().ToLower() + "#test.nl"
It looks like you also may be missing one on line 12. Powershell may think the rest of the code, until the next quote character, is part of your string literal.

Related

PAssing an array to a hash table, single item array failing

I have the file below, which accepts an array of servers. Works well when there are multiple items in the array, and I note the answer that a user suggested in a previous post, which was to put a , in front of the values if its a single item array, trying that with a hash table just doesnt worked. I have tried various options without much luck.
param ([array[]]$servers = $(throw "Input array of servers.") , $folder )
$x = $servers
$k = 'serverid','servername','locationid','appid' # key names correspond to data positions in each array in $x
$h = #{}
For($i=0;$i -lt $x[0].length; $i++){
$x |
ForEach-Object{
[array]$h.($k[$i]) += [string]$_[$i]
}
}
$all_server_ids = $h['Serverid']
foreach ($server_id in $all_server_ids)
{
$severid = $h["serverid"][$all_server_ids.indexof($server_id)]
$servername = $h["servername"][$all_server_ids.indexof($server_id)]
$locationid = $h["locationid"][$all_server_ids.indexof($server_id)]
Write-Output "This $severid and this $servername and this $locationid"
}
Running the below.
.\test.ps1 -servers ,('72','Server1\DEV2','1.0') -folder "F:\files"
Getting the error
Cannot index into a null array.
+ $servername = $h["servername"][$all_server_ids.indexof($server_i ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray
Cannot index into a null array.
+ $locationid = $h["locationid"][$all_server_ids.indexof($server_i ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : NullArray
The issue here is that, I need the script to work with multiple items in the array or a single item.

Getting txt not found error when running this script

I get this error when running this script:
Exception calling "Matches" with "1" argument(s): "Value cannot be
null. Parameter name: input" At V:\compiler\shitter2.ps1:3 char:1
+ $tables = $regex.matches((GC v:\compiler\test.txt -raw)).groups.value
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodInvocationException
+ FullyQualifiedErrorId : ArgumentNullException
Here is the script code:
$Path = 'V:\compiler\po.htm'
[regex]$regex = "(?s)<TABLE ID=.*?</TABLE>"
$tables = $regex.matches((GC v:\compiler\test.txt -raw)).groups.value
ForEach($String in $tables){
$table = $string.split("`n")
$CurTable = #()
$CurTableName = ([regex]'TABLE ID="
([^"]*)"').matches($table[0]).groups[1].value
$CurTable += ($table[1] -replace "</B></TH><TH><B>",",") -replace "</?
(TR|TH|B)>"
$CurTable += $table[2..($table.count-2)]|ForEach{$_ -replace "</TD>
<TD>","," -replace "</?T(D|R)>"}
$CurTable | convertfrom-csv | export-csv "$CurTableName.csv" -notype
}
You probably forgot the access the entry using [1]:
$tables = $regex.matches((GC v:\compiler\test.txt -raw)).groups[1].value

Issue with Powershell parsing in 4.0

I am having issues with the snippet below with Powershell 4.0 on 2012 R2:
$query = 'ASSOCIATORS OF {Win32_DiskDrive.DeviceID="' +
$disk.DeviceID.replace('\','\\') +
'"} WHERE AssocClass=Win32_DiskDriveToDiskPartition'
On my Windows 7 laptop running Powershell 2.0 this works fine both in the Powershell cli and in a .ps1 script. In Powershell 4.0 if I run it in the cli it works fine, but if I run it out of a .ps1 script I get:
You cannot call a method on a null-valued expression.
At C:\temp\perf.ps1:94 char:1
+ $part_query = 'ASSOCIATORS OF {Win32_DiskDrive.DeviceID="' + $disk.DeviceID.rep ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: ( [], ParentContainsErrorRecordException
+ FullyQualifiedErrorId : InvokeMethodOnNull
After some debug I think the issue is with .replace('\\','\\\').
I have tried .replace('\\\','\\\\\\\') but I get the same error.
Full code:
$diskdrives = get-wmiobject Win32_DiskDrive | sort Index
foreach ( $disk in $diskdrives ) {
write $disk
$scsi_details = 'SCSI ' + $disk.SCSIBus + ':' +
$disk.SCSILogicalUnit + ':' +
$disk.SCSIPort + ':' +
$disk.SCSITargetID
#$part_query = 'ASSOCIATORS OF {Win32_DiskDrive.DeviceID="' + $disk.DeviceID.replace('\','\\') + '"} WHERE AssocClass=Win32_DiskDriveToDiskPartition'
$part_query = 'ASSOCIATORS OF {Win32_DiskDrive.DeviceID="' + $disk.DeviceID.replace('\\','\\\') + '"} WHERE AssocClass=Win32_DiskDriveToDiskPartition'
$partitions = #( get-wmiobject -query $part_query |
sort StartingOffset )
foreach ($partition in $partitions) {
$vol_query = 'ASSOCIATORS OF {Win32_DiskPartition.DeviceID="' +
$partition.DeviceID +
'"} WHERE AssocClass=Win32_LogicalDiskToPartition'
$volumes = #(get-wmiobject -query $vol_query)
foreach ( $volume in $volumes) {
$allDiskInfo += $($volume.name + ' ' +
$volume.FileSystem + ' ' + $disk.Index + ' '
) | Out-String -stream
} # end foreach vol
} # end foreach part
} # end foreach disk
When I declared $disks I made it [string]. What I think happened is that Powershell 2.0 coerced it back to the system object but Powershell 4.0 must have stronger typing rules and was not coercing it from what I declared it as. Once I took [string] out of the declaration, it works on 4.0.
Thanks for the responses!!

powershell error-CategoryInfo : InvalidOperation: (split:String) [], RuntimeException

$Analog_File = "c:\temp\test\mt.txt"
#(Get-Item $Analog_File).length
if((Test-Path(-not $Analog_File)) -or ((Get-Item $Analog_File).length -eq 0kb))
{
exit
}
$m = Select-String -pattern ",T" c:\temp\test\mt_1.txt
#$m.length #Get the number of rows
For ($i=0; $i -le $m.length; $i++)
{
$s1 = $m[$i] -split ":"
$s1[2]
if ([int]$s1[2] -ge 9) #le = less than, ge = greater than, eq = equal to
{
$s2 = $s1[3] -split ","
$compid = $s2[2].split('''')[0] + "." + $s2[3].split('''')[0] + "." + $s2[4].split('''')[0] + "." + $s2[5].split('''')[0]
$matches = (Select-String -pattern $compid c:\temp\test\mt_1.txt).line
#($matches.split(';')[0])
#($matches.split(';')[0]).split(',')[0]
#($matches.split(';')[0]).split(',')[1]
if ($s2[6] -eq "T")
{
#$s2[2].split('''')[1]
#"Not in Service"
#"!" + ($matches.split(';')[0]).split(',')[0] + "!" + ($matches.split(';')[0]).split(',')[1] + "!0!" >> $fname
}
if ($s2[7] -eq "T")
{
#"Alarm inhibit"
#"!" + ($matches.split(';')[0]).split(',')[0] + "!" + ($matches.split(';')[0]).split(',')[1] + "!1!" >> $fname
}
if ($s2[8] -eq "T")
{
#"Manual update"
#"!" + ($matches.split(';')[0]).split(',')[0] + "!" + ($matches.split(';')[0]).split(',')[1] + "!2!" >> $fname
}
}
}
the error message:
You cannot call a method on a null-valued expression.
At line:17 char:31
$compid = $s2[2].split <<<< ('''')[0] + "." + $s2[3].split('''')[0] + "." + $s2[4].split('''')[0] + "." + $s2[5].split('''')[0]
CategoryInfo : InvalidOperation: (split:String) [], RuntimeException
FullyQualifiedErrorId : InvokeMethodOnNull
what can i do??

Powershell for SharePoint >> getting we!rd error

I keep getting following error on this code:
#Setup default variables
$webUrl = Get-SPWeb -Identity "http://CiscoIntranet/sites/VOIP"
$list = $webUrl.GetList("http://CiscoIntranet/sites/VOIP/ForwardTech")
[System.Reflection.Assembly]::LoadWithPartialName(”Microsoft.SharePoint”)
function ProcessMove {
param($folderUrl)
$folder = $web.GetFolder($folderUrl)
foreach ($file in $folder.Files)
{
[Microsoft.SharePoint.SPFile]$spFile = $file;
$docset=$($file.Counterparty2);
$destinationFolderUrl = "http://CiscoIntranet/sites/VOIP/ForwardTech/" + $docset;
$spFile.MoveTo($destinationFolderUrl + $file.Name, $true);
$webUrl.Update();
}
}
#Move root Files
ProcessMove($list.RootFolder.Url)
You cannot call a method on a null-valued expression.
At C:\PS\MoveFiles.ps1:8 char:28
+ $folder = $web.GetFolder <<<< ($folderUrl)
+ CategoryInfo : InvalidOperation: (GetFolder:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Method invocation failed because [Microsoft.SharePoint.SPListItemCollection] doesn't contain a method named 'MoveTo'.
At C:\PS\MoveFiles.ps1:13 char:23
+ $list.Items.MoveTo <<<< ($destinationFolderUrl + $file.Name, $true);
+ CategoryInfo : InvalidOperation: (MoveTo:String) [], RuntimeException
+ FullyQualifiedErrorId : MethodNotFound
This is the working code...
$siteURL="http://CiscoIntranet/sites/VOIP"
$docLib = "ForwardTech"
$site=Get-SPSite $siteURL
$web=$site.RootWeb
$collFiles=$web.GetFolder($docLib).Files
$count=$collFiles.Count
while($count -ne 0)
{
$item = $collFiles[$count-1].Item
$DocSet = $item["Region"]
Write-Host "$DocSet is the doc set. $collFiles[$count-1].Name is name"
$collFiles[$count-1].MoveTo($siteURL + "/" + $docLib + "/" + $DocSet + "/" + $collFiles[$count-1].Name, $true)
$count--
}