I am trying to run simple power-shell command to call json file to deploy some resources on Azure but it give me the same errors each time I try to run the file.The error message I am getting is -
New-AzDeployment : Cannot retrieve the dynamic parameters for the cmdlet. Invalid property identifier character: �. Path '', line 2, position 0.
At line:1 char:1
+ New-AzDeployment -Name $DeploymentName -Location uksouth -TemplateUri ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidArgument: (:) [New-AzDeployment], ParameterBindingException
+ FullyQualifiedErrorId : GetDynamicParametersException,Microsoft.Azure.Commands.ResourceManager.Cmdlets.Implementation.NewAzureDeploymentCmdlet
below is the powershell, I am trying to run -
$DeploymentSubscription = "Visual Studio Enterprise with MSDN"
$DeploymentRSG = "xyz"
$DeploymentName = "vvv"
$ParameterRoute = "D:\xyz\json\VM\"
$ParameterFile = $ParameterRoute + "Build.json"
$TemplateFileRoute = "D:\xyz\VM\"
$TemplateFileName = "Deploy_RG_Resources.json"
$TemplateFile = $TemplateFileRoute + $TemplateFileName
$TemplateFileURi = $TemplateFileRoute + $TemplateFileName
New-AzResourceGroupDeployment -Name $DeploymentName -ResourceGroupName $DeploymentRSG -DeploymentDebugLogLevel All -Verbose -TemplateUri $TemplateFileURi -TemplateParameterFile $ParameterFile
Thanks
That error is very specific.
What you are passing is valid. The help files for the cmdlet shows this command in action.
New-AzResourceGroupDeployment
$newAzResourceGroupDeploymentSplat = #{
TemplateParameterFile = "D:\Azure\Templates\EngSiteParams.json"
TemplateObject = $TemplateObject
ResourceGroupName = "ContosoEngineering"
}
New-AzResourceGroupDeployment #newAzResourceGroupDeploymentSplat
Note the fully qualified UNC to the .json file.
But you are doing this..
$ParameterFile = $ParameterRoute + "Build.json"
... and based on your post, that is not the path to your .json file.
Try using -TemplateFile as parameter instead of -TemplateUri if your Template file in on local machine.
This is resolved now .Issue was with the JSON template syntax.Quite weird though I have validate the template many times
Related
I use a command to read a JSON file, this all works perfectly, until the file becomes large.
I currently have a JSON file of about 1.5GB. I read the file using Powershell using the following command:
get-content -Path C:\TEMP\largefile.json | out-string | ConvertFrom-Json
It returns the following error:
out-string : Exception of type 'System.OutOfMemoryException' was thrown.
+ ... oices = get-content -Path C:\TEMP\largefile.json | out-string | Conve ...
+ ~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Out-String], OutOfMemoryException
+ FullyQualifiedErrorId : System.OutOfMemoryException,Microsoft.PowerShell.Commands.OutStringCommand
I've increased the memory as shown here:
get-item wsman:localhost\Shell\MaxMemoryPerShellMB
WSManConfig: Microsoft.WSMan.Management\WSMan::localhost\Shell
Type Name SourceOfValue Value
---- ---- ------------- -----
System.String MaxMemoryPerShellMB 8096
Any ideas on how to process this?
Edit (additions based on comments):
When I remove the out-string I get this error:
ConvertFrom-Json : Exception of type 'System.OutOfMemoryException' was thrown.
+ ... oices = get-content -Path C:\TEMP\largefile.json | ConvertFrom-Json ...
+ ~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Out-String], OutOfMemoryException
+ FullyQualifiedErrorId : System.OutOfMemoryException,Microsoft.PowerShell.Commands.OutStringCommand
The Powershell version that I have is: 5.1.17763.1490
The file contains multiple columns regarding PDF files. These files are exported via an API into a JSON so it contains the file metadata such as owner and when it was created but also the actual PDF file in the column Body which later will be decoded to an actual PDF file. The structure is as followed:
[{"Id":"ID","ParentId":"parent","Name":"filename","OwnerId":"owner","CreatedDate":"date","Body":"*******"}
{"Id":"ID","ParentId":"parent","Name":"filename","OwnerId":"owner","CreatedDate":"date","Body":"*******"}
{"Id":"ID","ParentId":"parent","Name":"filename","OwnerId":"owner","CreatedDate":"date","Body":"*******"}
{"Id":"ID","ParentId":"parent","Name":"filename","OwnerId":"owner","CreatedDate":"date","Body":"*******"}
{"Id":"ID","ParentId":"parent","Name":"filename","OwnerId":"owner","CreatedDate":"date","Body":"*******"}
]
Thank for the details.
For this issue I would try to convert each line separately and stream that through your process:
Get-Content C:\TEMP\largefile.json | ForEach-Object {
$_ = $_.Trim().TrimStart('[').TrimEnd(']')
if ($_) { $_ | ConvertFrom-Json }
}
As already suggested, I wouldn't be surprised if these memory issues wouldn't appear in PowerShell core. if possible, I recommend you to also give that a try.
So I have the following script I am trying to run which keeps erroring out
. .\stshortcut.ps1 |
Get-Shortcut . |
Where Target -eq "cmd.exe" |
%{$myPath, $myNewName = $null;
Write-Warning "Processing $($_.Link)";
If (-Not (Test-Path .\BadShortcuts -PathType Container)) {New-Item -
WhatIf -ItemType Directory BadShortcuts | Out-Null};
[string]$myPath = $_.Arguments.Split()[-1] -replace '"';
[string]$myNewName = $_.Link -replace "\.lnk$";
Rename-Item -WhatIf -Force -Path $myPath -NewName $myNewName;
(Get-Item -Force $myNewName).Attributes = '';
Move-Item -WhatIf $_.LinkPath .\BadShortcuts;}`
the error I get is as follows
The term 'Get-Shortcut' is not recognized as the name of a cmdlet,
function, script file, or operable program. Check the spelling of the
name, or if a path was included, verify that the path is correct and try
again.
At C:\Shared\APPS\FixShortcutX2.ps1:1 Char 13
+ Get Shortcut <<<<< . |
+ CategoryInfor : ObjectNotFound: (Get-Shortcut:String)[],
CommandNotFoundException
+ FullyQualifiedErrorID : CommandNotFoundException
the stshortcut.ps1 script has the get-shortcut and set-shortcut functions and are called to do such - I got this script from
https://www.reddit.com/r/PowerShell/comments/4su2jg/zeroday_malware_renamed_folders_on_a_shared_drive/
which is an answer script to fix a macro virus from a word doc attachment - sent from a spoofed email address -
Any assistance is GREATLY appreciated
EDITx2 after some further helpful advice and editing I now am receiving the following
Where-Object : Cannot bind parameter 'FilterScript' . Cannot convert the "Target" value of type "System.String" to type "System.Management.Automation.ScriptBlock".
At C:\Shared\Apps\FixShortcutX2.ps1:3 char:6
+ Where <<<<< Target -eq "cmd.exe" |
+CategoryInfo : InvalidArgument: (:) [Where-Object], ParameterBindingException
+ FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.WhereObjectCommand
You need to dot-source stshortcut.ps1 before you can use Get-Shortcut.
Change the first line:
.\stshortcut.ps1 |
To
. .\stshortcut.ps1
I'm trying to use SMO to restore a database via Powershell, however when I try to define and use a server object it gives me the following error:
Cannot convert argument "srv", with value: "[MJNHNX4]", for "SqlRestore" to type "Microsoft.SqlServer.Management.Smo.Server": "Cannot convert the "[MJNHNX4]" value of type
"Microsoft.SqlServer.Management.Smo.Server" to type "Microsoft.SqlServer.Management.Smo.Server"."
At line:38 char:1
+ $smoRestore.SqlRestore($server)
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
Here is my code in full (there's not a lot to it):
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SMO") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoExtended") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.ConnectionInfo") | Out-Null
[System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.SmoEnum") | Out-Null
#clear screen
cls
#get backup file
$backupFile = "D:\databases\Perfmon.bak"
$servername = "MJNHNX4"
$server = New-Object Microsoft.SqlServer.Management.Smo.Server($servername)
$backupDevice = New-Object ("Microsoft.SqlServer.Management.Smo.BackupDeviceItem") ($backupFile, "File")
$smoRestore = new-object("Microsoft.SqlServer.Management.Smo.Restore")
#settings for restore
$smoRestore.NoRecovery = $false;
$smoRestore.ReplaceDatabase = $true;
$smoRestore.Action = "Database"
#show every 10% progress
$smoRestore.PercentCompleteNotification = 10;
$smoRestore.Devices.Add($backupDevice)
#read db name from the backup file's backup header
$smoRestoreDetails = $smoRestore.ReadBackupHeader($server)
#display database name
"Database Name from Backup Header : " + $smoRestoreDetails.Rows[0]["DatabaseName"]
$smoRestore.Database = $smoRestoreDetails.Rows[0]["DatabaseName"]
#restore
$smoRestore.SqlRestore($server)
"Done"
The error occurs regardless of what I try to pass to Microsoft.SqlServer.Management.Smo.Server and I'm really not sure why it would be giving me that particular error. I've read through the TechNet articles on the Server Constructor and I really have no idea what's going on there. Any ideas?
After some further testing and reading about the SMO syntax, it looks like I don't need to define the $server as a new object. Instead, just passing the name of the server to $server works fine.
I have a powershell script "test.ps1" which takes a json string as a command line input & tries to parse it.
The powershell script is as below -
param(
[string]$json = $(throw 'test')
)
$currentPath = Get-Location
[Reflection.Assembly]::LoadFile("$currentPath\Newtonsoft.Json.dll")
$result = [Newtonsoft.Json.Linq.JObject]::Parse($json)
foreach($unit in $result["DevResults"]) {Write-Host $unit.TechnologyName.ToString()}
But it is giving me the below error -
PS C:\Users\aghosh.RJFDEV\Documents> ./test.ps1 '{"DevResults":[{"TechnologyName":"TFS","RuleName":"Alt CI ID for ESB","OutputValue":"ESClientCenter"},{"TechnologyName":"TFS","RuleName":"TFS Team Project Name","OutputValue":"ClientCenter"}],"QaResults":[{"TechnologyName":"TFS","RuleName":"Alt CI ID for ESB","OutputValue":"ESClientCenter"},{"TechnologyName":"TFS","RuleName":"TFS Team Project Name","OutputValue":"ClientCenter"}],"PreProdResults":[{"TechnologyName":"TFS","RuleName":"Alt CI ID for ESB","OutputValue":"ESClientCenter"},{"TechnologyName":"TFS","RuleName":"TFS Team Project Name","OutputValue":"ClientCenter"}],"ProdResults":[{"TechnologyName":"TFS","RuleName":"Alt CI ID for ESB","OutputValue":"ESClientCenter"},{"TechnologyName":"TFS","RuleName":"TFS Team Project Name","OutputValue":"ClientCenter"},{"TechnologyName":"TFS","RuleName":"Process Template","OutputValue":"Raymond James CMMI V3.5"}]}'
GAC Version Location
--- ------- --------
False v2.0.50727 C:\Users\aghosh.RJFDEV\documents\Newtonsoft.Json.dll
You cannot call a method on a null-valued expression.
At C:\Users\aghosh.RJFDEV\Documents\test.ps1:13 char:82
+ foreach($unit in $result["DevResults"]) {Write-Host $unit.TechnologyName.ToString <<<< ()}
+ CategoryInfo : InvalidOperation: (ToString:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
You cannot call a method on a null-valued expression.
At C:\Users\aghosh.RJFDEV\Documents\test.ps1:13 char:82
+ foreach($unit in $result["DevResults"]) {Write-Host $unit.TechnologyName.ToString <<<< ()}
+ CategoryInfo : InvalidOperation: (ToString:String) [], RuntimeException
+ FullyQualifiedErrorId : InvokeMethodOnNull
My powershell version is 2.0 & the Json.Net library version is 3.5.
Please help me with the error or please suggest any other suitable approach.
Thanking in advance.
Change this line:
foreach($unit in $result["DevResults"]) {Write-Host $unit.TechnologyName.ToString()}
To this:
foreach($unit in $result["DevResults"]) {Write-Host $unit["TechnologyName"].ToString()}
I want to have access to the same message that Powershell prints when you send an error record to the output stream
Example:
This is the exception message At
C:\Documents and
Settings\BillBillington\Desktop\psTest\exThrower.ps1:1
char:6
+ throw <<<< (New-Object ArgumentException("This is the
exception"));
+ CategoryInfo : OperationStopped: (:) [],
ArgumentException
+ FullyQualifiedErrorId : This is the exception
I when a get the last ErrorRecord by doing $Error[0] I can't seem to figure out how to get this information in a simple way
I found this 'Resolve-Error' function from the community extensions here which does roughly what I want but it prints a huge semi-formatted list of stuff I don't need that I have to then strip
Is there way of accessing the message that Powershell uses or failing that a simpler way of getting hash of the values I care about so I can put them into a string in a format of my choosing?
How about:
$x = ($error[0] | out-string)
Is that what you wanted?
If you want a bit shorter message (more user friendly sometimes?) than #tomasr suggests this will do:
$error[0].ToString() + $error[0].InvocationInfo.PositionMessage
You will get something like:
Cannot find path 'C:\TEMP\_100804_135716\missing' because it does not exist.
At C:\TEMP\_100804_135716\test.ps1:5 char:15
+ Get-ChildItem <<<< missing
This technical info will be excluded:
+ CategoryInfo : ObjectNotFound: (C:\TEMP\_100804_135716\missing:String) [Get-ChildItem], ItemNotFoundException
+ FullyQualifiedErrorId : PathNotFound,Microsoft.PowerShell.Commands.GetChildItemCommand
I took it a bit further because I didn't like the multilines from $error[0].InvocationInfo.PositionMessage.
Function FriendlyErrorString ($thisError) {
[string] $Return = $thisError.Exception
$Return += "`r`n"
$Return += "At line:" + $thisError.InvocationInfo.ScriptLineNumber
$Return += " char:" + $thisError.InvocationInfo.OffsetInLine
$Return += " For: " + $thisError.InvocationInfo.Line
Return $Return
}
[string] $ErrorString = FriendlyErrorString $Error[0]
$ErrorString
You can look at what else is availible to construct your own String via:
$Error | Get-Member
$Error[0].InvocationInfo | Get-Member
Foreach ($Errors in $Error){
#Log Eintrag wird zusammengesetzt und in errorlog.txt geschrieben
"[$Date] $($Errors.CategoryInfo.Category) $($Errors.CategoryInfo.Activity) $($Errors.CategoryInfo.Reason) $($Errors.CategoryInfo.TargetName) $($Errors.CategoryInfo.TargetType) $($Errors.Exception.Message)" |Add-Content $Path\errorlog.txt -Encoding UTF8
}
You can also do this and you will get all Informations about the Error
Similar to #tomasr, but shorter:
$($error[0])
For all errors in a script:
$($error)