I'm trying to teach myself Azure Powershell scripting and have an ultimate goal of setting up a script that reads in an Excel Spreadsheet with specifications for Azure VMs to create (things like, type of VM, tags, timezone, which AD group to add it to, etc). If anybody has any tutorial references for this, that would be very helpful.
Currently, I'm falling on my face on what should be something relatively simple. Exporting functions. I have opened Powershell ISE and tried to run the following code (taken from one of the examples I found on MSDN):
Function New-Test
{
Write-Output 'I am New-Test function'
}
Export-ModuleMember -Function New-Test
function Validate-Test
{
Write-Output 'I am Validate-Test function'
}
function Start-Test
{
Write-Output 'I am Start-Test function'
}
Set-Alias stt Start-Test
Export-ModuleMember -Function Start-Test -Alias stt
But I get an error saying:
"Export-ModuleMember: Object Reference not set to an instance of an object"
I have tried saving this code out to a ps1 file named test and then navigating to the directory it's in and running "./test.ps1" but the same error comes up.
Any idea on what I'm doing wrong here? There is surely something fundamental that I am missing here.
I ran into this error, too. For myself, I found out that the "Export-ModuleMember" can't have any line breaks between it and the end of the last function bracket.
Examples:
Import-Module Object Reference Error:
function Test-Import{
Write-Host "import function success"
}
Export-ModuleMember -Function Test-Import
Import-Module, no errors:
function Test-Import{
Write-Host "import function success"
}
Export-ModuleMember -Function Test-Import
In my case the solution was to reference the psm1 instead of the ps1 ind the psd1 file
# Script module or binary module file associated with this manifest.
RootModule = 'pf-rootscript.psm1'
instead of
# Script module or binary module file associated with this manifest.
RootModule = 'pf-rootscript.ps1'
When you plan to write a lot of code in PowerShell scripts, then setting up your module and controlling what you export (or not) using Export-ModuleMember is the right thing to do. So if you're planning on building your own module to consume in further PowerShell scripts, then you're on the right track.
You haven't mentioned anything about the module definition or how/where exactly you are consuming these functions, so I think you are probably missing the part where you define your module first.
You can follow a step by step guide for doing that here: PowerShell: Building a Module, one microstep at a time
Related
With Azure Release Pipeline, in a task using the PowerShell Script, I am able to set values of variables and pass to next task using the command
Write-Host '##vso[task.setvariable variable=varResourceExists;isOutput=true;something'
However, when I put this similar command in a task that uses Azure PowerShell, this command is no longer allowed, the task produces a warning:
2019-10-22T00:23:14.3080614Z ##[warning]'##vso[task.setvariable
variable=varResourceExists;isOutput=true;something' contains logging
command keyword '##vso', but it's not a legal command. Please see the
list of accepted commands:
https://go.microsoft.com/fwlink/?LinkId=817296
As a result, the variable varResourceExists cannot be set by my task. I have also tried a conventional PowerShell set value by doing
$varResourceExists = 'something'; # this also does not work
Is there a way I can set this value in Azure Powershell script so that the next task can reference it?
##vso[task.setvariable variable=varResourceExists;isOutput=true;something is not correct syntax. You're missing a closing ].
It should be ##vso[task.setvariable variable=varResourceExists;isOutput=true;]something
Here is how I solved my topic. In the pipeline Azure PowerShell task, I can have code such as Write-Host '##vso[task.setvariable variable=varResourceExists;isOutput=true;]False';
In the Output Variable option, I set a Reference Name "step1":
Output Variable
Then in the next step, I can do a conditional check using a Custom Condition:
Custom Condition
I can also reference the variable in my code such as Write-Host "The step1.varResourceExists says: $(step1.varResourceExists)";
I am trying to customize the output of my pipeline release through setting some env variables into a task.
I found the following link:
https://learn.microsoft.com/en-us/azure/devops/pipelines/scripts/logging-commands?view=azure-devops&tabs=powershell
which however does not seem to work.
What I am doing is simply to create a pipeline with a single task (either bash or PS), and there declaring the commands specified in the link through the inline version of the task.
Has anyone already successfully managed to make these commands work?
Do I do something wrong and/or incomplete?
Does anyone have a better way to customise the pipeline with relevant information from a task? E.g. through the release name, or the description and/or tag of the specific release?
Edit:
Write-Host "##vso[task.setvariable variable=sauce;]crushed tomatoes"
Write-Host "##vso[task.setvariable variable=secretSauce;issecret=true]crushed tomatoes with garlic"
Write-Host "Non-secrets automatically mapped in, sauce is $env:SAUCE"
Write-Host "Secrets are not automatically mapped in, secretSauce is $env:SECRETSAUCE"
Write-Host "You can use macro replacement to get secrets, and they'll be masked in the log: $(secretSauce)"
this is the code, copy and pasted. Now I tried also with the script, and it does not work either.
I use an hosted windows agent.
When you set a new variable with the logging command the variable is available only in the next tasks and not in the same task.
So, split your script to 2 tasks, in the second task put the last 3 lines and you will see that the first task works:
this also puzzled me for a while, in the end i found out that if you want to modify the $env:path you can call the special task called task.prependpath by using the special logging command syntax like "##vso[task.prependpath]local directory path". you can find more of this kind of special commands from their source :
https://github.com/microsoft/azure-pipelines-tasks/blob/master/docs/authoring/commands.md
I'm writing a powershell script to create VM using New-AzureRmResourceGroupDeployment cmdlet, which is as below.
New-AzureRmResourceGroupDeployment -Name VmDeployment `
-TemplateFile C:\template\template.json `
-TemplateParameterFile C:\template\parameters.json
This is used create a VM. In parameters.json , there are some parameters like virtualMachineName, networkInterfaceName etc which are hardcoded.
Now I'm trying to automate these scripts , i.e they run on there own from a tool , when ever some condition is met.
My requirement here is , whenever this script runs, it has to increase the number in the VMName . Suppose the VM Name is now VMName1, it has to be VMName2 when the script runs next time. Similarly VMName3 when the script runs next time. Since the virtualMachineName parameter is hardcoded, this is not happening now. Is there anyway I can pass virtualMachineName as a parameter in the script itself rather than taking it from the json file.
Any guidance is highly appreciated.Thanks!
You can definitely do this, and fortunately there are a handful of ways too.
Pass inline parameters. It says in the Azure PowerShell docs for Templates that you can use inline parameters with a local parameter file and the inline parameters take precedence. Relevant paragraph:
You can use inline parameters and a local parameter file in the same deployment operation. For example, you can specify some values in the local parameter file and add other values inline during deployment. If you provide values for a parameter in both the local parameter file and inline, the inline value takes precedence.
This is valuable because it provides you explicit control over the VM Name parameter, but it is up to the caller (you in this case) to pass an inline parameter. Please note this only works with local parameter files and not remote files (i.e. -TemplateParameterFile and not -TemplateParameterUri). The resulting command would look something like:
New-AzureRmResourceGroupDeployment -Name VmDeployment `
-TemplateFile C:\template\template.json `
-TemplateParameterFile C:\template\parameters.json `
-virtualMachineName VMName42
Modify original parameters.json. You can write some PowerShell/Python/Favorite-scripting-language to parse paramters.json, find the VM Name parameter, find the integer suffix, increment it, and overwrite the file with the new version. This has the benefit of not having to remember to pass an inline parameter, and you won't have to track the version number anywhere as it is already stored in parameters.json. This has one major drawback: it modifies the original JSON which can be dangerous.
Copy parameters.json and modify temporary copy. You can write a script to copy parameters.json to another temporary JSON file and then increment the VM Name parameter during the copy just like in option 2. Pass this temporary file to New-AzureRmResourceGroupDeployment. This has the benefit of not modifying the original parameters.json file but requires you to track the version number somewhere (e.g. another local file, a command line parameter, environment variables, etc.).
For simplicity, I would recommend option 1. It already works out-of-the-box and does not require any external scripts.
I've been writing a script to connect to SharePoint online, create a document library and add some AD accounts to the permission. I've written all the code using snippets I have found through many searches but am having an issue with the permissions part.
I keep getting an error when adding the user and permission type to roledefinitionbinding.
The error is:
Collection has not been initialized at line 0 char 0.
Here is my code
$collRdb = new-object Microsoft.SharePoint.Client.RoleDefinitionBindingCollection($ctx)
$collRdb.Add($role)
$collRoleAssign = $web.RoleAssignments;
$ctx.Load($principal)
$collRoleAssign.Add($principal, $collRdb)
$ctx.ExecuteQuery()
The issue is when it runs $collRoleAssign.Add($principal, $collRdb) part and stop with the error above.
I would really appreciate a hand with this before my PC get launched out of the window.
Thanks
Mark
EDIT
All of the code is taken from this page:
http://jeffreypaarhuis.com/2012/06/07/scripting-sharepoint-online-with-powershell-using-client-object-model/
The only change is i'm using the get principal fun instead of the get group, but not sure if that's what has done it. I'm very new to powershell.
Thanks
I don't think you can add something into $collRoleAssign if it's not loaded before.
You get an error because it has null value.
I would have wrote it like this:
$collRoleAssign = $web.RoleAssignments
$ctx.Load($collRoleAssign)
Comment: I suppose you already set $principal before
$ctx.Load($principal)
Comment: here I suppose $collRdb is set and loaded
$collRoleAssign.Add($principal, $collRdb)
$ctx.ExecuteQuery()
By the way there is a ";" in your code which should not be there
I didn't try it but that should help!
Sylvain
I have created a powershell module (.psm1) file that includes a few other powershell scripts. We use it for sharepoint.
So basically, here's what happens:
I have a deploy script that retrieves the module location from the registry
It loads the module using the Import-Module cmdlet (using -force switch)
This module in turn loads the Sharepoint 2010 snap in and a few other scripts that I created
It runs runs a deployment script that references functions from the included scripts
It also runs a command line application and sends the output directly to the screen
The script will usually work the first time. However, after a few number of tries the commandline tool will stop working and sending output to the screen altogether. And if I try to run a commandline tool (not a cmd-let) after running my script, it don't worky anymore: no output, nothing is done. Its just the same as hitting enter on a blank prompt. anything powershell specific or running GUI applications will work fine but running any console application will not produce any concievable results. the only solution to this, is to just close my powershell and open it again. it will work for usually once and I will have to close it again. our users certainly wont be happy about that..
The most 'notable' things on the script:
scriptblocks are used extensively (for logging), a script block is sent to a handler that executes it using invokecommand and logs the step
its manipulating sharepoint objects
all objects are properly disposed of
no static variables are created nor changed
There are a few global variables shared across all scripts
What I have tried:
I striped my code to a bare minimum: loading an xml file, and restaring a few windows services but I'm still getting this intermittently. I have no idea which part of the code could cause this. I would love to post the code, but our company policy forbids me to. so my aplogies..
Update as per the comment below:
here's roughly how I use codeblocks. I have this function below that is used everytime I want to make the user aware of a task that I'm executing and what it outcome is.
function DoTask($someString, $scriptBlock, $param)
{
try
{
OutputTaskDescription $someString
InvokeCommand $scriptBlock -ArgumentList $param
OutputResultOK
}
catch
{
OutputResultError $_.tostring()
}
}
it could then be used like this:
$stringVar = "something"
$SpSite = new-spsite
deploySomething 'Deploying something' -param $spsite -ScriptBlock {
dosomethingToObject $stringvar
dosomethingToObject $spSite.Name
}
it would then output something like:
Deploying Something ------------- OK
Deploying Something ------------- ERROR
Also notice that I pass the $spsite in the argument list and I just use the string directly. I still don't understand how this works but it seems like I can access all primitive typed variables even without passing them as arguments but I have to pass more complex objects are params, else they dont have any value.
Update:
after much searching and days of pain. I have found others with the same pain. My code exhibits the same exact symptoms as described here:
http://connect.microsoft.com/PowerShell/feedback/details/496326/stability-problem-any-application-run-fails-with-lastexitcode-1073741502
I guess there is no solution yet to this problem.
After a little while I've noticed that if I've ran some very memory intensive functions, I too have gotten that behavior where everything you try to execute just goes to the prompt again. I'd recommend setting Set-PsDebug -Trace 2 to see what those functions are actually doing. I fixed my issue by doing this and figuring out how to make my functions more efficient.