Module Web Administration gives out an un-mutable error - powershell

Running the following lines of PowerShell code (on a WIN 2008 R2 server, with administrator rights):
try {
Import-Module webadministration -ErrorAction Stop
}
catch {
"ERROR : $( $Error[ 0 ].ToString() )"
}
Will throw an error onto the console, and will not actually pass it to the catch block:
Process should have elevated status to access iis configuration data
The above error is displayed as is except the color is red on the PowerShell console. To be clear - There is no other text being displayed except for the above Error. The $Error[ 0 ] is not populated as well.
It almost seems like the Error did not generate from the PowerShell script, but from an external process/script.
Is there any way to suppress this error? Even after supplying the ErrorAction preference in the try-catch block, the error still displays.
Additionally, The following will NOT work:
Import-Module webadministration -ErrorAction Stop
Import-Module webadministration | Out-Null
Import-Module webadministration 2>&1 | Out-Null
$null = Import-Module webadministration
Import-Module webadministration -ErrorAction SilentlyContinue
$ErrorActionPreference = 'SilentlyContinue'
Import-Module webadministration
Of note, the Import-Module webadministration command works after loading the second time in the same PowerShell session! Meaning,
# First Go
Import-Module webadministration
# error thrown on first go
# Second Go
Import-Module webadministraion
# Second go works! It loads the 'webadministration' module

Related

JiraPS printing linebreaks instead of results

I have a problem when using the JiraPS Module in a script.
When executing the script below I receive a line-break instead of an actual result. The weird thing is, when executing the script twice, once without the Get-JiraProject -Project 'exampleBoard' at the bottom and once with only the Get-JiraProject -Project 'exampleBoard' everything works fine and I get the correct output. When using Get-JiraProject in the script which outputs all projects with read-access I get a line-break for every project.
param ($jirauser)
$ServerURi = 'https://company.atlassian.net'
if (!(
(Get-Module BetterCredentials -ListAvailable) -and
(Get-Module JiraPS -ListAvailable)
)) {
$Force = $True
}
if ($Force) {
# Force the installation of the latest version of the modules
Install-Module -Name BetterCredentials -Scope CurrentUser -AllowClobber -Force
Install-Module -Name JiraPS -Scope CurrentUser -Force
}
# Set Jira server and create session
Import-Module JiraPS -Force
Set-JiraConfigServer $ServerURi
# Get credentials with "BetterCredentials" and store them if they are new
Import-Module BetterCredentials -Force
$cred = Get-Credential -UserName $jirauser -Store
#Session Creation
Write-Output "Creating a session"
$session = New-JiraSession -Credential $cred
if ($session) {
Write-Output $session
}
Get-JiraProject -Project 'exampleBoard'
The output looks as follows:
The value of jirauser is: example#company.com
Creating a session
Username WebSession
-------- ----------
example#company.com Microsoft.PowerShell.Commands.WebRequestSession
I tried the following already:
Running the script inside WSL and PWSH to work around Execution Policies
Using / not using BetterCredentials
Split the code in two (as described above) and ran it twice
Writing the output of Get-JiraProject into a variable and printing the variable instead
Using New-Object System.Management.Automation.PSCredential to create the credentials manually
Sleep for a few seconds after authenticating

trying to run powershell script silently failing

I've never seen this one, and a search didn't find this issue. A script that ran last week this way with output is silently failing this week. I checked the file has read/wright/run checked in windows explorer. I tried set-executionpolicy remotesigned at the PS prompt.
This script is run at the windows command prompt like this:
powershell "powershell.exe {c:\temp\crashAfter.ps1}"
(no results)
The other ways I've tried are:
powershell
set-executionpolicy remotesigned
.\crashAfter.ps1
(no results)
I've also tried:
PowerShell -File c:\temp\crashAfter.ps1
(no results both at powershell prompt and at just regular windows command line)
What could cause powershell to fail silently like this? It works to go to the powershell prompt at the command line.
This is the script, which hasn't changed since last time I ran it:
$today=[system.datetime](Get-Date)
$startTime=$today.AddHours(-4)
$events = Get-WinEvent -FilterHashtable #{LogName='Application';ProviderName='Application Error';Data='SearchUI.exe';StartTime=$($startTime);EndTime=$($today);} -ErrorAction SilentlyContinue
foreach ($event in $events)
{
$crashOccurredTime=$event.TimeCreated
$lookForInitStart = $event.TimeCreated.AddMinutes(-2)
$eventInit = {Get-WinEvent -FilterHashtable #{LogName='Application';ProviderName='Application Error';StartTime=$lookForInitStart;EndTime=$crashOccurredTime;} -ErrorAction SilentlyContinue | Where-Object -PipelineVariable Message -Match 'SearchUI'
}
if($eventInit -ne $null)
{
Write-Host "Found SearchUI.exe after SearchUI TimeCreated $($event.TimeCreated) ProviderName $($event.ProviderName) Message $($event.Message)"
}
else
{
Write-Host "none"
}
}
Last Friday when I ran this script, it was using our application that we can use to run scripts, and my results looked like this (not sure what CLIXML is):
#< CLIXML
Found SearchUI.exe after SearchUI TimeCreated 08/08/2022 13:46:45 ProviderName Application Error Message
...

Debug-Job :The job cannot be debugged because the host debugger mode is set to None or Default

I created a sample powershell project with a Script.ps1 file and a Modules\Script1\Script1.psm1 file.
the module file..
# Script1.psm1
function Get-Greeting{
Start-Sleep -Seconds 10
Write-Host "hello from foo";
}
and the script file..
# Script1.ps1
if(-not(Get-Module -Name "Script1")){
Import-Module .\Modules\Script1
}
if(Get-Module -Name "Script1"){
Remove-Module Script1;
Import-Module .\Modules\Script1;
}
Get-Greeting # output: hello from foo
$ajob = Start-Job -ScriptBlock {
Get-Greeting
} -InitializationScript {
if(-not(Get-Module -Name "Script1")){
Import-Module 'C:\Users\suyashs\Documents\Visual Studio 2015\Projects\Playground\PowerShellProject2\PowerShellProject2\Modules\Script1'
}
if(Get-Module -Name "Script1"){
Remove-Module Script1;
Import-Module 'C:\Users\suyashs\Documents\Visual Studio 2015\Projects\Playground\PowerShellProject2\PowerShellProject2\Modules\Script1'
}
}
Debug-Job -Job $ajob
Error appears at last line Debug-Job -Job $ajob
[ERROR] Debug-Job : The job cannot be debugged because the host
debugger mode is set to None or Default. The host debugger mode must
be [ERROR] LocalScript and/or RemoteSript
What i want is that the breakpoint inside my Get-Greeting method gets hit.
I tried searching on the internet but failed to find a solution.
I am using Powershell ISE, Visual Studio 2015 powershell project. Current Powershell version is 5.0
Normal debugging works fine, but as soon as i start some async/multithreaded debugging i.e. using Start-Job i dont see any breakpoint getting hit.
Any help is appreciated.

How do I troubleshoot Powershell user data scripts on AWS EC2?

I am trying to run a powershell script from the user data box when creating an ec2 instance from a custom AMI. I have enabled user data execution on the config before creating the ami.
This is what i put into user data
<powershell>
c:\scripts\github-download.ps1 someuser somepassword
</powershell>
The script it is calling is shown below.
Param($gituser, $gitpass)
C:\Users\Administrator\AppData\Local\GitHub\shell.ps1
git clone https://"$gituser":"$gitpass"#github.com/somegitrepo |out-null
I have no idea why this isn't working. Am i doing something wrong here? Any help really appreciated.
Instead of calling the user data using the <powsershell> tag, call PowerShell itself using the <script> tag. You gain command line control over its invocation, and can control execution policy and other command line settings directly:
<script>
PowerShell -ExecutionPolicy Bypass -NoProfile -File c:\scripts\github-download.ps1 -user USER -password PASSWORD
</script>
In your script, setup the beginning and end sections of your script as below:
# Server script called from userdata in this format
# <script>
# PowerShell -ExecutionPolicy Bypass -NoProfile -File c:\scripts\github-download.ps1 -user USER -password PASSWORD
# </script>
param (
[string]$user = $(throw "-user is required."),
[string]$password = $(throw "-password is required."),
)
Start-Transcript -Path C:\userscriptlog.txt
Import-Module WebAdministration
if ([System.Diagnostics.EventLog]::SourceExists("Userdata") -eq $False) {
New-Eventlog -Logname Application -Source 'Userdata'
}
Write-Eventlog -Logname Application -Source 'Userdata' -EventId 1 -EntryType Information -Message 'Begining post-deployment configuration script'
-- YOUR MAIN SCRIPT HERE --
Write-Eventlog -Logname Application -Source 'Userdata' -EventId 1 -EntryType Information -Message 'Post-deployment configuration script complete'
Stop-Transcript
For error handling in your script, you need to use robust exception handling and logging for each command, again to make troubleshooting and debugging easy. This block simply gets the current instance ID, but note the exception handling and logging built in:
# get instance-id
try {
$InstanceId = (Invoke-WebRequest http://169.254.169.254/latest/meta-data/instance-id).content
} catch {
$_.Exception.message | out-file c:\InstanceId_error.log
Write-Host "FATAL: InstanceId exception"
Exit
}
if (!$InstanceId) {
Write-Host "FATAL: InstanceId is null"
Exit
} else {
$InstanceId | out-file C:\InstanceId.txt
Write-Host "InstanceId: $InstanceId"
}
Try that approach to any command or shell invocation that you need to implement.
This powershell script 'wrapper' for user data scripts allows optional command line parameters, produces a transcript of execution, and logs events to the Windows event log, to confirm basic execution of the script.
It will provide a flexible framework for any Powershell based user data script, allow for easy debugging and testing.
| out-null silences any errors that could be happening with git clone so you won't know what is wrong unless you pipe the error somewhere else or just don't use | out-null.
I would manually run the command on the EC2 instance without the | out-null before you try and use user data to automate anything.

Cmdlets not found in command line but available in ISE

I'm trying to create an IIS application and app pool using PowerShell on a Windows Server 2008 R2 VM. The powershell script is as follows:
Param(
[string] $branchName,
[string] $sourceFolder
)
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
[Security.Principal.WindowsBuiltInRole] "Administrator"))
{
Write-Warning "You do not have Administrator rights to run this script. `nPlease re-run this script as an Administrator."
Exit
}
$appPool = $branchName
$site = "Default Web Site"
#Add APPPool
New-WebAppPool -Name $appPool -Force
#Create Applications
New-WebApplication -Name $branchName -Site $site -PhysicalPath $sourceFolder - ApplicationPool $appPool -Force
If I run the script in the PowerShell ISE it works fine but if I run it from a command line (or a batch file using the command line) I get the error
The term New-WebAppPool is not recognized as the name of a cmdlet... etc.
Is there a way that the web administration cmdlets could be installed in the ISE but not the command line?
Assuming that you're using PowerShell v2 (the default version installed with Server 2008 R2) it's as #jisaak suspected: you need to import the module WebAdministration explicitly in your code:
Import-Module WebAdministration
ISE seems to do that automatically.
Another option would be to upgrade to PowerShell v4, which also automatically imports modules when one of their exported cmdlets is used.
For anyone interested, the answer was painfully simple. As suggested, the solution was to import the module, but there was an issue was that it wasn't available after closing the console and reopening it. To solve this I simply had to add the line into the powershell itself so it imports the module at every runtime.
Param(
[string] $branchName,
[string] $sourceFolder)
if (-NOT ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole(`
[Security.Principal.WindowsBuiltInRole] "Administrator"))
{
Write-Warning "You do not have Administrator rights to run this script.`nPlease re-run this script as an Administrator."
Exit
}
$appPool = $branchName
$site = "Default Web Site"
*Import-Module WebAdministration*
#Add APPPool
New-WebAppPool -Name $appPool -Force
#Create Applications
New-WebApplication -Name $branchName -Site $site -PhysicalPath $sourceFolder - ApplicationPool $appPool -Force