I have just encountered a very weird error: whenever I just add an empty line in a ps1 file which is otherwise working really fine, my script generates errors.
Here is the setup:
Because I had dependencies issues, I now have an Includes.ps1 file with that content:
$ScriptDirectory = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
. ("$ScriptDirectory\HelperFunctions.ps1")
. ("$ScriptDirectory\BuildParameters.ps1")
. ("$ScriptDirectory\Platform.ps1")
. ("$ScriptDirectory\Configuration.ps1")
. ("$ScriptDirectory\Action.ps1")
. ("$ScriptDirectory\Backup.ps1")
I have a Package.ps1 file which includes that file, and does the stuff of instanciating the needed classes and make them work together:
$ScriptDirectory = Split-Path -Path $MyInvocation.MyCommand.Definition -Parent
. ("$ScriptDirectory\Includes.ps1")
Clear-Host
$Parameters = New-Object -TypeName "BuildParameters"
$user_variables_path = "./UserVariables.ps1"
if ( Test-Path $user_variables_path )
{
. $user_variables_path
}
$Parameters.ValidateParameters()
$PlatformClass = $PlatformFactory.MakePlatform( $Parameters.Platform )
$PlatformClass.ValidateParameters( $Parameters )
$ConfigurationClass = $ConfigurationFactory.MakeConfiguration( $Parameters.Configuration )
$ConfigurationClass.ValidateParameters( $Parameters )
$ActionClass = $ActionsFactory.MakeAction( $Parameters.Action, $PlatformClass, $ConfigurationClass, $Parameters )
$ActionClass.ValidateParameters()
$Backup = [ Backup ]::new( $Parameters, $PlatformClass )
$Backup.ValidateParameters();
$ActionClass.Execute()
if ( $Parameters.BackupVersion )
{
$Backup.BackupVersion()
}
Here is the Platforms.ps1 file which gives me errors when I edit it:
class Platform
{
[Boolean] $CanBePatched
[Boolean] $CanCompressData
Platform()
{
$this.CanBePatched = $false
$this.CanCompressData = $true
}
[void] ValidateParameters( [BuildParameters] $Parameters )
{
}
}
class PlatformWin64 : Platform
{
PlatformWin64()
{
}
}
class PlatformXboxOne : Platform
{
PlatformXboxOne()
{
}
}
class PlatformSwitch : Platform
{
PlatformSwitch()
{
$this.CanBePatched = $true
}
[void] ValidateParameters( [BuildParameters] $Parameters )
{
if ( [string]::IsNullOrEmpty( $Parameters.Region ) )
{
WriteErrorAndExit( "You need to specify a region for the PS4" )
}
}
}
class PlatformPS4 : Platform
{
PlatformPS4()
{
$this.CanBePatched = $true
$this.CanCompressData = $false
}
[void] ValidateParameters( [BuildParameters] $Parameters )
{
if ( [string]::IsNullOrEmpty( $Parameters.Region ) )
{
WriteErrorAndExit( "You need to specify a region for the PS4" )
}
}
}
class PlatformFactory
{
[Platform] MakePlatform( [String] $name )
{
return (New-Object -TypeName "Platform$name")
}
}
$PlatformFactory = [PlatformFactory]::new()
When I change the contents of that file, even by adding empty lines, running the script gives me those errors:
Cannot convert argument "Platform", with value: "PlatformWin64", for
"MakeAction" to type "Platform": "Cannot convert the "PlatformWin64" value
of type "PlatformWin64" to type "Platform"."
At F:\Projects\RWC\BuildScripts\Utils\Package.ps1:55 char:1
+ $ActionClass = $ActionsFactory.MakeAction( $Parameters.Action, $Platf ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
You cannot call a method on a null-valued expression.
At F:\Projects\RWC\BuildScripts\Utils\Package.ps1:56 char:1
+ $ActionClass.ValidateParameters()
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Cannot convert argument "Platform", with value: "PlatformWin64", for
".ctor" to type "Platform": "Cannot convert the "PlatformWin64" value of
type "PlatformWin64" to type "Platform"."
At F:\Projects\RWC\BuildScripts\Utils\Package.ps1:58 char:1
+ $Backup = [ Backup ]::new( $Parameters, $PlatformClass )
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
You cannot call a method on a null-valued expression.
At F:\Projects\RWC\BuildScripts\Utils\Package.ps1:59 char:1
+ $Backup.ValidateParameters();
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At F:\Projects\RWC\BuildScripts\Utils\Package.ps1:61 char:1
+ $ActionClass.Execute()
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At F:\Projects\RWC\BuildScripts\Utils\Package.ps1:65 char:5
+ $Backup.BackupVersion()
+ ~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Well it turns out I had to close the powershell command line and run it again to have my modifications not generate any errors.
That post helped me find the cause...
Related
$findPDF = Get-ChildItem -Path "$fileDrive" -Filter *.pdf -r
$findDOCX = Get-ChildItem -Path "$fileDrive" -Filter *.docx -r
$pullFiles += $findPDF
$pullFiles += $findDOCX
#[array]$pullFiles
#$pullFiles.length
$holdPath = #()
for($i = 0; $i -lt $pullFiles.length; $i++){
#get the full path of each document
$fullPath = Resolve-Path $pullFiles.fullname[$i]
#stores the information in a global array
$holdPath += $fullPath.path
}
#$holdPath
<#
.DESCRIPTION Uses the word.APPLICATION object to open and convert the word documents into .txt.
#>
#https://stackoverflow.com/questions/13402898/how-can-i-use-powershell-to-save-as-a-different-file-extension
#wdFormatDOSTextLineBreaks 5 Microsoft DOS text with line breaks preserved.
foreach($fi in $holdPath){
$Doc = $word.Documents.Open($fi.name)
$NameDOCX = ($Doc.name).replace("docx","txt")
$Doc.saveas([ref] $NameDOCX, [ref] 5)
$NamePDF = ($Doc.name).replace("pdf","txt")
$Doc.saveas([ref] $NamePDF, [ref] 5)
$Doc.close()
}
The problem Statement
The program needs to get any pdf and doc/x file and convert it to a .txt file. Now, I am able to recursively search and pull all .docx and .pdf documents from the file system. Now, I just need to convert them.
The Error
You cannot call a method on a null-valued expression.
At C:\Users\p617824\Documents\files\powershell\fileExtRename.ps1:38 char:2
+ $Doc = $word.Documents.Open($fi.name)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\Users\p617824\Documents\files\powershell\fileExtRename.ps1:40 char:2
+ $NameDOCX = ($Doc.name).replace("docx","txt")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
[ref] cannot be applied to a variable that does not exist.
At C:\Users\p617824\Documents\files\powershell\fileExtRename.ps1:41 char:2
+ $Doc.saveas([ref] $NameDOCX, [ref] 5)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (NameDOCX:VariablePath) [], RuntimeException
+ FullyQualifiedErrorId : NonExistingVariableReference
You cannot call a method on a null-valued expression.
At C:\Users\p617824\Documents\files\powershell\fileExtRename.ps1:43 char:2
+ $NamePDF = ($Doc.name).replace("pdf","txt")
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
[ref] cannot be applied to a variable that does not exist.
At C:\Users\p617824\Documents\files\powershell\fileExtRename.ps1:44 char:2
+ $Doc.saveas([ref] $NamePDF, [ref] 5)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (NamePDF:VariablePath) [], RuntimeException
+ FullyQualifiedErrorId : NonExistingVariableReference
You cannot call a method on a null-valued expression.
At C:\Users\p617824\Documents\files\powershell\fileExtRename.ps1:46 char:2
+ $Doc.close()
+ ~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
$word variable are not initialized, and your are complicated for Nothing (without offense you). Modify all your script like this :
$fileDrive ="C:\temp"
$word = new-object -ComObject Word.Application
Get-ChildItem -Path $fileDrive -file -r -Include "*.docx", "*.pdf" | %{
$Doc = $word.Documents.Open($_.FullName)
$NameDOC = $_.FullName.replace(".docx",".txt").replace(".pdf",".txt")
$Doc.saveas([ref] $NameDOC, [ref] 5)
$Doc.close()
}
$word.Quit()
But i have doubt on convert pdf to .txt with Word application like this... I think you should use itextsharp libray like here
I'm attempting to set and clear a session variable in a PowerShell module:
function Set-Variable
{
[CmdletBinding()]
param(
[string]$Value = $PSCmdlet.SessionState.PSVariable.Get('Value').Value
)
# if `Value` not supplied on the command line and not available in the session, prompt for it
if (!$PSCmdlet.SessionState.PSVariable.Get('Value') -And !$Value) {
$Value = Read-Host "Value"
}
# if `Value` has been supplied on the command line, save it in the session
if ($Value) {
$PSCmdlet.SessionState.PSVariable.Set('Value',$Value)
}
}
Export-ModuleMember Set-Variable
function Remove-Variable {
$PSCmdlet.SessionState.PSVariable.Remove('Value')
# also throws an exeception
# $PSCmdlet.SessionState.PSVariable.Set('Value',$null)
}
Export-ModuleMember Remove-Variable
Setting the value works as expect, however, removing the variable or setting its value to null produces an error:
PS> Remove-Variable
You cannot call a method on a null-valued expression.At
C:\Users\XXXX\Documents\WindowsPowerShell\Modules\foo\foo.psm1:39 char:5
+ $PSCmdlet.SessionState.PSVariable.Remove('Value')
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
and:
You cannot call a method on a null-valued expression.At
C:\Users\XXXX\Documents\WindowsPowerShell\Modules\foo\foo.psm1:37 char:5
+ $PSCmdlet.SessionState.PSVariable.Set('Value',$null)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Is there a way to do this?
Hi I am trying to connect to sharepoint online and publish calender using the data from a SQL Table and I am getting the following exception , please advise.The same code works fine with slight modification on a on prem sharepoint server I have added sharepointonline for the authentication but it is failing with the error.
[System.Reflection.Assembly]::LoadFile ("C:\MOSSLibrary\Microsoft.SharePoint.Client.dll") | Out-Null
[System.Reflection.Assembly]::LoadFile("C:\MOSSLibrary\Microsoft.SharePoint.Client.Runtime.dll") | Out-Null
$username = "XXXXXX"
$url = "XXXXXX"
$pass= cat C:\text.txt | ConvertTo-SecureString
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)
$Creds = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username,$Pass)
$Context.Credentials = $Creds
$web = $Context.Web
$Context.Load($web)
$Context.Load($splist)
$splist = $Context.web.Lists.GetByTitle("XXXX")
$ItemCreateInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
####Some Data coming from SQL Server DB into $table########
$table = $result.Tables[0];
foreach ($row in $table)
{
Write-Host $row.Item("changetitle") $row.Item("status");
$Item1 = $splist.AddItem($ItemCreateInfo)
$Item1["Title"] = "test"
Write-host $date
$Item1.Update()
$Context.ExecuteQuery()
}
Exception
New-Object : A constructor was not found. Cannot find an appropriate
constructor for type Microsoft.SharePoint.Client.ClientContext. At
C:\MOSSLibrary\testingpublish.ps1:15 char:12 + $Context = New-Object
Microsoft.SharePoint.Client.ClientContext($site ... +
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : ObjectNotFound: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand
The property 'Credentials' cannot be found on this object. Verify
that the property exists and can be set. At
C:\MOSSLibrary\testingpublish.ps1:17 char:1 + $Context.Credentials =
$Creds + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound You cannot call a method on a null-valued expression. At
C:\MOSSLibrary\testingpublish.ps1:20 char:1 + $Context.Load($web) +
~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At
C:\MOSSLibrary\testingpublish.ps1:21 char:1 + $Context.Load($splist)
+ ~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull You cannot call a method on a null-valued expression. At
C:\MOSSLibrary\testingpublish.ps1:22 char:1 + $splist =
$Context.web.Lists.GetByTitle("XXXXXXX") +
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (:) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
It seems Assemblies are not loading correctly.
[System.Reflection.Assembly]::LoadFile ("C:\MOSSLibrary\Microsoft.SharePoint.Client.dll") | Out-Null
[System.Reflection.Assembly]::LoadFile("C:\MOSSLibrary\Microsoft.SharePoint.Client.Runtime.dll") | Out-Null
Instead of above, try following
Add-Type -Path "C:\MOSSLibrary\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\MOSSLibrary\Microsoft.SharePoint.Client.Runtime.dll"
PS: Make sure that C:\MOSSLibrary\ contains following two .dll's
Microsoft.SharePoint.Client.dll
Microsoft.SharePoint.Client.Runtime.dll
i have a problem with my PS code, i have to start my tests on browsers every tuesday in teamcity! and i wrote the function which goes on my server with credentials and try to make my tests on it
function HTTP-GetRequest($url, $username, $password)
{
$properties = Resolve-Path "C:\Users\Uladzimir_Vaitsiakho\Documents\CI\Build\CI_2.0\vsphere\properties.ps1"
Write-Host $properties
. $properties
$webRequest = [System.Net.WebRequest]::Create($url)
$webRequest.Credentials = New-Object System.Net.NetworkCredential -ArgumentList $username, $password
$webRequest.PreAuthenticate = $true
$webRequest.Headers.Add("AUTHORIZATION", "Basic");
[System.Net.WebResponse] $resp = $webRequest.GetResponse();
$rs = $resp.GetResponseStream();
[System.IO.StreamReader] $sr = New-Object System.IO.StreamReader -argumentList $rs;
[string] $results = $sr.ReadToEnd();
return $results
}
if (($today.DayOfWeek) -eq "Tuesday")
{
if ($env:Browser -eq "Firefox"){
$url = "http://1111111/httpAuth/action.html?add2Queue=bt6&&env.name=Browser&env.value=Chrome"
HTTP-GetRequest $url, $teamcity_username, $teamcity_password
Write-Host $teamcity_password
Write-Host $teamcity_username
}
if ($env:Browser -eq "Chrome"){
$url = "http://11111/httpAuth/action.html?add2Queue=bt6&&env.name=Browser&env.Value=InternetExplorer"
HTTP-GetRequest $url, $teamcity_username, $teamcity_password
}
}
And have got the next output with troubles, but file with properties and credentials i gave to my function, what's can be wrong?!
Cannot convert argument "0", with value: "System.Object[]", for "Create" to type "System.Uri": "Cannot convert the "System.Object[]" value of type "System.Object[]" to type "System.Uri"."
At C:\Users\Uladzimir_Vaitsiakho\Documents\qw.ps1:6 char:47
+ $webRequest = [System.Net.WebRequest]::Create <<<< ($url)
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
Property 'Credentials' cannot be found on this object; make sure it exists and is settable.
At C:\Users\Uladzimir_Vaitsiakho\Documents\qw.ps1:7 char:14
+ $webRequest. <<<< Credentials = New-Object System.Net.NetworkCredential -ArgumentList $username, $password
+ CategoryInfo : InvalidOperation: (Credentials:String) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
Property 'PreAuthenticate' cannot be found on this object; make sure it exists and is settable.
At C:\Users\Uladzimir_Vaitsiakho\Documents\qw.ps1:10 char:14
+ $webRequest. <<<< PreAuthenticate = $true
+ CategoryInfo : InvalidOperation: (PreAuthenticate:String) [], RuntimeException
+ FullyQualifiedErrorId : PropertyNotFound
You cannot call a method on a null-valued expression.
At C:\Users\Uladzimir_Vaitsiakho\Documents\qw.ps1:11 char:25
+ $webRequest.Headers.Add <<<< ("AUTHORIZATION", "Basic");
+ CategoryInfo : InvalidOperation: (Add:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\Users\Uladzimir_Vaitsiakho\Documents\qw.ps1:13 char:58
+ [System.Net.WebResponse] $resp = $webRequest.GetResponse <<<< ();
+ CategoryInfo : InvalidOperation: (GetResponse:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\Users\Uladzimir_Vaitsiakho\Documents\qw.ps1:14 char:31
+ $rs = $resp.GetResponseStream <<<< ();
+ CategoryInfo : InvalidOperation: (GetResponseStream:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
New-Object : Constructor not found. Cannot find an appropriate constructor for type System.IO.StreamReader.
At C:\Users\Uladzimir_Vaitsiakho\Documents\qw.ps1:15 char:43
+ [System.IO.StreamReader] $sr = New-Object <<<< System.IO.StreamReader -argumentList $rs;
+ CategoryInfo : ObjectNotFound: (:) [New-Object], PSArgumentException
+ FullyQualifiedErrorId : CannotFindAppropriateCtor,Microsoft.PowerShell.Commands.NewObjectCommand
You cannot call a method on a null-valued expression.
At C:\Users\Uladzimir_Vaitsiakho\Documents\qw.ps1:16 char:35
+ [string] $results = $sr.ReadToEnd <<<< ();
+ CategoryInfo : InvalidOperation: (ReadToEnd:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
Currently the call to HTTP-GetRequest is passing an array of objects ($url, $teamcity_username , $teamcity_password) to the function. Remove the commas from your function call:
HTTP-GetRequest $url $teamcity_username $teamcity_password
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--
}