I need some way to be able to run the below script as Administrator.
Script to get the Security Event log:
$DateAfter = (Get-Date).AddDays(-1)
$DateBefore = (Get-Date)
$EventLogTest = Get-EventLog -LogName Security -InstanceId 4625 -Before $DateBefore -After $DateAfter -Newest 5
$WinEventTest = Get-WinEvent -FilterHashtable #{ LogName = 'Security'; Id = 4625; StartTime = $DateAfter; EndTime = $DateBefore } -MaxEvents 5
Write-Host "$EventLogTest result is: "
$EventLogTest
Write-Host "$WinEventTest result is: "
$WinEventTest
I have compiled the below snippets, but somehow, the result is not displayed or nothing?
Combined Script:
$Role = "Domain Admins"
$CurrentLoginPrincipal = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent())
$IsDomainAdminGroupMember = $CurrentLoginPrincipal.IsInRole($Role)
$IsLocalComputerAdminMember = $CurrentLoginPrincipal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
If( -not ($IsDomainAdminGroupMember -and $IsLocalComputerAdminMember) ) {
Write-Warning "You are not running this as $($Role) and Local Administrator of $($ENV:COMPUTERNAME).$($ENV:USERDNSDOMAIN). The script will be re-executed as Local Administrator"
Try {
Start-Process PowerShell -Verb RunAs "-NoProfile -ExecutionPolicy Bypass -Command `"cd '$pwd'; & '$PSCommandPath';`"" -Verbose
}
Catch {
Write-Warning -Message "[PROCESS] Something wrong happened"
Write-Warning -Message $Error[0].Exception.Message
$out.Details = $_.Exception.Message
Write-Host " ERROR: $($out.Details)" -ForegroundColor Red
}
}
Else {
#a user running the script has the Domain Admins and Local PC Admin rights
Write-Host " $($CurrentLoginPrincipal.Identity.Name.ToString()) is currently member of $($Role) and Local Administrator of $($ENV:COMPUTERNAME).$($ENV:USERDNSDOMAIN) " -ForegroundColor Green
}
$DateAfter = (Get-Date).AddDays(-1)
$DateBefore = (Get-Date)
$EventLogTest = Get-EventLog -LogName Security -InstanceId 4625 -Before $DateBefore -After $DateAfter -Newest 5
$WinEventTest = Get-WinEvent -FilterHashtable #{ LogName = 'Security'; Id = 4625; StartTime = $DateAfter; EndTime = $DateBefore } -MaxEvents 5
Write-Host "$EventLogTest result is: "
$EventLogTest
Write-Host "$WinEventTest result is: "
$WinEventTest
However, it is still not executing as Administrator to get the result displayed. How can I fix this?
First thing I noticed is that your if condition is wrong. It uses -and where that should be or (because either a Domain admin OR a local Administrator can run this)
Next, the arguments for Start-Process are incorrect. Personally, I like using the -ArgumentList as array.
Finally, in the catch block you use an undefined variable $out with an equally undefined property $out.Details. In the code below I have changed that to simply re-throw the exception.
Starting from where the if..else is:
if( -not ($IsDomainAdminGroupMember -or $IsLocalComputerAdminMember) ) {
Write-Warning "You are not running this as $($Role) or Local Administrator of $($ENV:COMPUTERNAME).$($ENV:USERDNSDOMAIN). The script will be re-executed as Local Administrator"
# give the user some time to see this message
Start-Sleep 4
# Build base arguments for powershell.exe as string array
$argList = '-NoLogo', '-NoProfile', '-NoExit', '-ExecutionPolicy Bypass', '-File', ('"{0}"' -f $PSCommandPath)
# Add script arguments if any
$argList += $MyInvocation.BoundParameters.GetEnumerator() | ForEach-Object {"-$($_.Key)", "$($_.Value)"}
try {
Start-Process PowerShell.exe -Verb Runas -WorkingDirectory $pwd -ArgumentList $argList -Verbose -ErrorAction Stop
# exit the current script.
exit # Use return if you want to keep this instance open aswell
}
catch {
throw
}
}
else {
#a user running the script has the Domain Admins and Local PC Admin rights
Write-Host " $($CurrentLoginPrincipal.Identity.Name.ToString()) is currently member of $($Role) and Local Administrator of $($ENV:COMPUTERNAME).$($ENV:USERDNSDOMAIN) " -ForegroundColor Green
}
Related
I am taking over a process (originally created by a vendor) that creates and configures a VM. The process can either create a VM in hyperv on a physical host, or in vsphere. This is a powershell script called migrate-storeservers.ps1.
As part of the configuration, migrate-storeservers.ps1 calls a script locally on the VM that performs database validation (Validate-StoreServerDB.ps1). In the event that the VM is created in vsphere, we only want certain validation tasks to run.
I added a vsphere switch to the Migrate-StoreServers.ps1, and added logic to the function that calls the database validation script.
Vsphere switch at top of script:
[cmdletbinding()]
Param (
[Parameter(Mandatory=$true)]$Store,
[switch]$FinalizeVm,
[switch]$Vsphere,
[switch]$SqlSafe,
[switch]$FullAuto,
[switch]$TestRun,
$ErrorActionPreference = "Stop"
)
Function that calls database validation script, where $taskArgs are set based on Vsphere switch being used or not:
function validateDatabase($newServer, $newVmSession, $validateScript, $userScript, $moduleFile, $outLog){
$global:currentTask = "Database Validation"
Write-Debug "Current Task: $global:CurrentTask"
Write-Host "Starting database validation on server: $newServer"
$startTime = Get-Date
Write-Host "Start time: $startTime" -ForegroundColor Green
stageAaronsLiteModule -inModuleFile $moduleFile -inSession $newVmSession
$dateString = Get-Date -Format "yyyyMMddTHHmmss"
$logName = $("DBValidate_" + $newServer.ToUpper() + "_" + $dateString + ".log")
if($Vsphere){
$taskArg = "-NoProfile -ExecutionPolicy Unrestricted -File {0} -Store {1} -LogPath {2} -LogFile {3} -Vsphere {4}" `
-f $validateScript, $newServer, $outLog, $logName, $Vsphere
} else{
$taskArg = "-NoProfile -ExecutionPolicy Unrestricted -File {0} -Store {1} -LogPath {2} -LogFile {3}" `
-f $validateScript, $newServer, $outLog, $logName
}
executeTask -inTaskName "DatabaseValidation" -inPsSession $newVmSession -inUserScript $userScript -inTaskArg $taskArg `
-inMessage "Database Validation Script is starting. This takes about 2 minutes" -inCred $cred
Start-Sleep -Seconds 5
$logFound = copyLogToSource -inServer $newServer -inLog $($outLog + "\" + $logName) -outLogPath $LocalLogPath
if(-not($logFound)){
exitScript -inMessage "ERROR: Unable to find/copy log file" -failed $true
}
Start-Sleep 5
parseLogForErrors -inLog $($LocalLogPath + "\" + $logName) -errorString "TerminatingError"
$endTime = (Get-Date) - $startTime
Write-Host "Validate Database completed in: $endTime" -ForegroundColor Green
}
In the validation script being called by the function I added a vsphere switch and logic that sets the tasks list based on if the vsphere switch is used.
[cmdletbinding()]
Param (
[Parameter(Mandatory=$true)]$Store,
[Parameter(Mandatory=$true)]$LogPath,
[Parameter(Mandatory=$true)]$LogFile,
[switch]$Vsphere,
$ErrorActionPreference = "Stop"
)
########### Start Global Variable Section ###########
$sqlInstance = ($Store.ToUpper() + "\POS")
$sqlDatabase = "master"
$sqlConnectionTimeout = 60
$sqlQueryTimeout = 240
if($Vsphere){
$tasks = #(
"GoNoGo_Store2016_Upgrade_10_CheckServerName",
"GoNoGo_Store2016_Upgrade_20_CheckSQLVersion",
"GoNoGo_Store2016_Upgrade_30_CheckDBOnline",
"GoNoGo_Store2016_Upgrade_50_CheckDBExists"
)
} else{
$tasks = #(
"GoNoGo_Store2016_Upgrade_10_CheckServerName",
"GoNoGo_Store2016_Upgrade_20_CheckSQLVersion",
"GoNoGo_Store2016_Upgrade_30_CheckDBOnline",
"GoNoGo_Store2016_Upgrade_40_CheckSysMergeArcticles",
"GoNoGo_Store2016_Upgrade_50_CheckDBExists",
"GoNoGo_Store2016_Upgrade_60_CheckReplicationStatus"
)
}
My question is does the logic in the migrate-storeservers.ps1 look like it will pass the vsphere switch correctly to the validate-storeserverdb.ps1?
I am rather new to more advanced powershell like this and am concerned that the $taskArg for when the Vsphere switch is used are maybe not formatted correctly to pass the vsphere switch. The $taskArg for if the switch is not used was how the script was formatted before I added the switch logic.
Any input will be greatly appreciated.
This question already has answers here:
How to pass a variable to new console window in Powershell
(2 answers)
Closed last year.
I have a script that opens a powershell console as admin and do sth in eventlog.
I have two variables that i the new admin-PS console needs.
[string] $PiEventLog = "'Company Name Prv.Limt'"
[String] $PiEventLogSource = "'XY-Test'"
I am opening the new PS-Console like this
start powershell -Verb runas {
If(Get-EventLog -List | ?{$_.Log -like $PiEventLog}){
Write-Host "EventLog already exists." -ForegroundColor Yellow
}
else{
New-EventLog -LogName $PiEventLog -Source $PiEventLogSource -ErrorAction Stop
Write-Host "EventLog was successfully created." -ForegroundColor Green
}
Read-Host "Press any key to close the console..."
}
If i try to execute the script, i get the following error:
The argument for the parameter "LogName" cannot be checked. The
argument is NULL or empty. Specify an argument that is not NULL or
empty and re-execute the command.
anyone got an idea, how i can give those two variables to the new PS-console, without having to set two different variables in the new console?
I believe this should work, it's easier if you use a Here-String. Since you're using the -like operator, I would assume you're looking for a Log that "contains" the input given in $PiEventLog, in that case, you should use wildcard characters: -like "*$PiEventLog*".
param(
[string] $PiEventLog = 'Company Name Prv.Limt',
[String] $PiEventLogSource = 'XY-Test'
)
$command = #"
If(Get-EventLog -List | Where-Object Log -Like '*$PiEventLog*'){
Write-Host 'EventLog already exists.' -ForegroundColor Yellow
}
else{
New-EventLog -LogName $PiEventLog -Source $PiEventLogSource -ErrorAction Stop
Write-Host 'EventLog was successfully created.' -ForegroundColor Green
}
Read-Host "Press any key to close the console..."
"#
Start-Process powershell -Verb RunAs -ArgumentList '-c', $command
Then you call this script like:
PS /> ./script.ps1 -PiEventLog 'something' -PiEventLogSource 'something'
I'm writing a PowerShell script that uses parameters / arguments and needs to be run as administrator but I'm trying to make it as user-friendly as possible so I'm trying to write it so that if it wasn't run as administrator then it can auto-elevate itself and preserve the original parameters (only switches and strings).
I was not able to find a solution online, hence this post.
I managed to accomplish this by "stringifying" $PsBoundParameters then using that with Start-Process PowerShell -Verb Runas -ArgumentList.
Note: $PsBoundParameters uses the parameters of the current scope ("root" vs inside a function, for example) so if you need to reference the command-line parameters (as I do) then you'll need to either use this variable outside of a function or first pass the variable to the function (as I've done here).
I've created a demonstration of this:
Param(
[switch]$ExampleSwitch,
[string]$ExampleString
)
Function Restart ($AllParameters, $Admin) {
$AllParameters_String = "";
ForEach ($Parameter in $AllParameters.GetEnumerator()){
$Parameter_Key = $Parameter.Key;
$Parameter_Value = $Parameter.Value;
$Parameter_Value_Type = $Parameter_Value.GetType().Name;
If ($Parameter_Value_Type -Eq "SwitchParameter"){
$AllParameters_String += " -$Parameter_Key";
} Else {
$AllParameters_String += " -$Parameter_Key $Parameter_Value";
}
}
$Arguments = "-File `"" + $PSCommandPath + "`" -NoExit" + $AllParameters_String;
If ($Admin -Eq $True){
Start-Process PowerShell -Verb Runas -ArgumentList $Arguments;
} Else {
Start-Process PowerShell -ArgumentList $Arguments;
}
}
$RanAsAdministrator = ([Security.Principal.WindowsPrincipal] [Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator);
Write-Host "ExampleSwitch value:" $ExampleSwitch;
Write-Host "ExampleString value:" $ExampleString;
Write-Host "";
If ($RanAsAdministrator -Eq $True){
Write-Host "Running as administrator: Yes.";
} Else {
Write-Host "Running as administrator: No.";
}
$Elevate = Read-Host "Restart as current user or admin? (u/a)";
Write-Host "";
If ($Elevate -Like "u"){
Restart $PsBoundParameters;
} ElseIf ($Elevate -Like "a") {
Restart $PsBoundParameters -Admin $True;
}
Start-Sleep -Seconds 9999;
Param(
[Switch]$MySwitch,
[String]$MyString,
[Switch]$NoExit
)
If (!([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole] "Administrator")) {
$PSHost = If ($PSVersionTable.PSVersion.Major -le 5) {'PowerShell'} Else {'PwSh'}
Start-Process -Verb RunAs $PSHost (#(' -NoExit')[!$NoExit] + " -File `"$PSCommandPath`" " + ($MyInvocation.Line -split '\.ps1[\s\''\"]\s*', 2)[-1])
Break
}
Write-Host "MySwitch:" $MySwitch;
Write-Host "MyString:" $MyString;
Explanation:
($MyInvocation.Line -split '\.ps1[\s\''\"]\s*', 2)[-1]) will resolve the current parameters
$MyHost determines the current PowerShell Host (PowerShell for Windows or PowerShell Core) and use the same host for the elevated window.
The -NoExit switch will prevent the elevated window to automatically close
Example:
.\RunAsAdministrator.ps1 -MyString "Test 123" -MySwitch -NoExit
Thought I would share this quick function I made for myself, feel free to adapt it and improve it according to your needs.
Sometimes you want to run commands as the logged on user of a remote computer.
As you know, some commands show output for the user who runs it and if you run the same command with Invoke-Command, it won't return the user's information, but yours). Get-Printer is an example amongst many others.
There is no easy, quick way of running commands as the logged on user natively without any third-party apps like PsExec or others so I made this quick function that uses VBS, PS1 and Scheduled Task to make it happen.
It runs completly silently for the user (thanks to the VBS) and the output is shown in your console. Please note it assumes the remote computer has a C:\TEMP.
Created in a Windows 10, powershell v 5.1.17763.503 environement.
I don't pretend it's final and perfect, it's the simplest way I found to do what is needed and I just wanted to share it with you guys as it can be very useful!
Check the comments for explanation of the code and feel free to use it as you wish. Please share your version as I'm curious to see people improve it. A good idea would be to make it support multiple computers, but as I said it's a quick function I did I don't have too much time to put into refining it.
That being said, I had no problems using it multiple times as is :)
*Output returned is in form of a string, if you want to have a proper object, add '| ConvertFrom-String' and play with it :)
PLEASE NOTE: The surefire way of grabbing the username of who is currently logged on is via QWINSTA (since Win32_ComputerSystem - Username is only reliable if a user is logged on LOCALLY, it won't be right if a user is using RDP/RemoteDesktop). So this is what I used to grab the username, however, please note that in our french environement the name of the username property in QWINSTA is "UTILISATEUR",so you have to change that to your needs (english or other language) for it to work. If I remember correctly, it's "USERNAME" in english.
On this line:
$LoggedOnUser = (qwinsta /SERVER:$ComputerName) -replace '\s{2,22}', ',' | ConvertFrom-Csv | Where-Object {$_ -like "*Acti*"} | Select-Object -ExpandProperty UTILISATEUR
See code in the answer below.
function RunAsUser {
Param ($ComputerName,$Scriptblock)
#Check that computer is reachable
Write-host "Checking that $ComputerName is online..."
if (!(Test-Connection $ComputerName -Count 1 -Quiet)) {
Write-Host "$ComputerName is offline" -ForegroundColor Red
break
}
#Check that PsRemoting works (test Invoke-Command and if it doesn't work, do 'Enable-PsRemoting' via WMI method).
#*You might have the adjust this one to suit your environement.
#Where I work, WMI is always working, so when PsRemoting isn't, I enable it via WMI first.
Write-host "Checking that PsRemoting is enabled on $ComputerName"
if (!(invoke-command $ComputerName { "test" } -ErrorAction SilentlyContinue)) {
Invoke-WmiMethod -ComputerName $ComputerName -Path win32_process -Name create -ArgumentList "powershell.exe -command Enable-PSRemoting -SkipNetworkProfileCheck -Force" | Out-Null
do {
Start-Sleep -Milliseconds 200
} until (invoke-command $ComputerName { "test" } -ErrorAction SilentlyContinue)
}
#Check that a user is logged on the computer
Write-host "Checking that a user is logged on to $ComputerName..."
$LoggedOnUser = (qwinsta /SERVER:$ComputerName) -replace '\s{2,22}', ',' | ConvertFrom-Csv | Where-Object {$_ -like "*Acti*"} | Select-Object -ExpandProperty UTILISATEUR
if (!($LoggedOnUser) ) {
Write-Host "No user is logged on to $ComputerName" -ForegroundColor Red
break
}
#Creates a VBS file that will run the scriptblock completly silently (prevents the user from seeing a flashing powershell window)
#"
Dim wshell, PowerShellResult
set wshell = CreateObject("WScript.Shell")
Const WindowStyle = 0
Const WaitOnReturn = True
For Each strArg In WScript.Arguments
arg = arg & " " & strArg
Next 'strArg
PowerShellResult = wshell.run ("PowerShell " & arg & "; exit $LASTEXITCODE", WindowStyle, WaitOnReturn)
WScript.Quit(PowerShellResult)
"# | out-file "\\$ComputerName\C$\TEMP\RAU.vbs" -Encoding ascii -force
#Creates a script file from the specified '-Scriptblock' parameter which will be ran as the logged on user by the scheduled task created below.
#Adds 'Start-Transcript and Stop-Transcript' for logging the output.
$Scriptblock = "Start-Transcript C:\TEMP\RAU.log -force" + $Scriptblock + "Stop-Transcript"
$Scriptblock | out-file "\\$ComputerName\C$\TEMP\RAU.ps1" -Encoding utf8 -force
#On the remote computer, create a scheduled task that runs the .ps1 script silently in the user's context (with the help of the vbs)
Write-host "Running task on $ComputerName..."
Invoke-Command -ComputerName $ComputerName -ArgumentList $LoggedOnUser -ScriptBlock {
param($loggedOnUser)
$SchTaskParameters = #{
TaskName = "RAU"
Description = "-"
Action = (New-ScheduledTaskAction -Execute "wscript.exe" -Argument "C:\temp\RAU.vbs C:\temp\RAU.ps1")
Settings = (New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -StartWhenAvailable -DontStopOnIdleEnd)
RunLevel = "Highest"
User = $LoggedOnUser
Force = $true
}
#Register and Start the task
Register-ScheduledTask #SchTaskParameters | Out-Null
Start-ScheduledTask -TaskName "RAU"
#Wait until the task finishes before continuing
do {
Write-host "Waiting for task to finish..."
$ScheduledTaskState = Get-ScheduledTask -TaskName "RAU" | Select-Object -ExpandProperty state
start-sleep 1
} until ( $ScheduledTaskState -eq "Ready" )
#Delete the task
Unregister-ScheduledTask -TaskName "RAU" -Confirm:$false
}
Write-host "Task completed on $ComputerName"
#Grab the output of the script from the transcript and remove the header (first 19) and footer (last 5)
$RawOutput = Get-Content "\\$ComputerName\C$\temp\RAU.log" | Select-Object -Skip 19
$FinalOutput = $RawOutput[0..($RawOutput.length-5)]
#Shows output
return $FinalOutput
#Delete the output file and script files
Remove-Item "\\$ComputerName\C$\temp\RAU.log" -force
Remove-Item "\\$ComputerName\C$\temp\RAU.vbs" -force
Remove-Item "\\$ComputerName\C$\temp\RAU.ps1" -force
}
#____________________________________________________
#Example command
#Note: Sometimes Start-Transcript doesn't show the output for a certain command, so if you run into empty output, add: ' | out-host' or '| out-default' at the end of the command not showing output.
$Results = RunAsUser -ComputerName COMP123 -Scriptblock {
get-printer | Select-Object name,drivername,portname | Out-host
}
$Results
#If needed, you can turn the output (which is a string for the moment) to a proper powershell object with ' | ConvertFrom-String'
I've spent hours trying to pin down this problem. I'm running a PowerShell to verify if various services are running. I want to run it every 5 minutes from Windows Task Scheduler.
It checks services on other servers, and some on the same machine on which it is running. When I run it under task scheduler, under the same userid that I'm running interactive I get different results. Interactively, shows all the services on local machine are running. When run through task scheduler, it tells me that service is not found.
This is just a fragment of a larger program. I get the server/service names from a CSV file, then at the end it sends a nice HTML email. I added the Add-Content to create a trace file to prove this happening.
foreach ($line in $csv) {
$reportStatus = ""
$ServerCount = $ServerCount + 1
#$Service = (get-service -Name $line.ServiceName -ComputerName $line.ServerName)
#this is slower than above, but it gives us the processId which we can use to find out what time the service/process started
write-host "Verifying: " $line.ServerName $line.ServiceName
$myDate = Get-Date
Add-Content D:\scripts\ServiceMonitorTrace.txt "$myDate $($line.ServerName) $($line.ServiceName)"
$Service = (get-wmiobject win32_service -ComputerName $line.ServerName -filter "name = '$($line.ServiceName)'")
if ($Service -eq $null)
{
$reportStatus = "Service Not Found: name = '$($line.ServiceName)'"
$trColor = "Yellow"
$ErrorCount = $ErrorCount + 1
$CriticalErrorCount = $CriticalErrorCount + 1
$CreationDate = "NA"
Write-Host "----> $reportStatus "
Add-Content D:\scripts\ServiceMonitorTrace.txt "$myDate $reportStatus"
}
}
New Simpler Version (has exact same issue):
$Service = (get-wmiobject win32_service -ComputerName "DAL-BIZ-APP01" -filter "name = 'LanManServer'")
if ($Service -eq $null)
{
$reportStatus = "Service not found"
}
else
{
$reportStatus = "Service found"
}
$myDate = Get-Date
Write-Host $reportStatus
Add-Content D:\scripts\ServiceTestTrace.txt "$myDate $reportStatus"
Interactive Results:
10/31/2013 09:34:00 DAL-BIZ-APP01 MSDTC
10/31/2013 09:34:00 DAL-BIZ-APP01 BTSSvc$BizTalkHost_QT_Default
Scheduled Job Results:
10/31/2013 09:25:42 DAL-BIZ-APP01 MSDTC
10/31/2013 09:25:42 Service Not Found: name = 'MSDTC'
10/31/2013 09:25:42 DAL-BIZ-APP01 BTSSvc$BizTalkHost_QT_Default
I run it from a command file that contains this:
powershell -command "& 'D:\Scripts\ServerMonitor.ps1'" d:\Scripts\ServerMonitorConfig.csv
Running the command file from a non-admin command prompt window or the scheduler also seems to have different results.
New Simpler Version if someone want to try, just substitute two computer names:
$Service = (get-wmiobject win32_service -ComputerName "DAL-BIZ-APP01" -filter "name = 'LanManServer'")
if ($Service -eq $null)
{
$reportStatus = "Service not found"
}
else
{
$reportStatus = "Service found"
}
$myDate = Get-Date
Write-Host $reportStatus
Add-Content D:\scripts\ServiceTestTrace.txt "$myDate DAL-BIZ-APP01 $reportStatus"
$Service = (get-wmiobject win32_service -ComputerName "DAL-BIZ-APP02" -filter "name = 'LanManServer'")
if ($Service -eq $null)
{
$reportStatus = "Service not found"
}
else
{
$reportStatus = "Service found"
}
$myDate = Get-Date
Write-Host $reportStatus
Add-Content D:\scripts\ServiceTestTrace.txt "$myDate DAL-BIZ-APP02 $reportStatus"
Results:
10/31/2013 16:07:48 DAL-BIZ-APP01 Service found
10/31/2013 16:07:48 DAL-BIZ-APP02 Service found
10/31/2013 16:08:03 DAL-BIZ-APP01 Service not found
10/31/2013 16:08:03 DAL-BIZ-APP02 Service found
16:07:48 was from command prompt, 16:08:03 was from task scheduler.
I added this to code:
if ($error -ne $null)
{
Write-Host "----> $($error[0].Exception) "
Add-Content $TraceFilename "$myDate TRCE1 $($error[0].Exception)"
}
Now I'm able to see the reason that was getting swallowed:
11/13/2013 11:35:37 TRCE1 System.Management.ManagementException:
Access denied at System.Management.ManagementException.ThrowWithExtendedInfo(ManagementStatus
errorCode) at
System.Management.ManagementObjectCollection.ManagementObjectEnumerator.MoveNext()
at Microsoft.PowerShell.Commands.GetWmiObjectCommand.BeginProcessing()
I have not yet figured out the "Access Denied", but at least I'm happy I see the true error now, i.e. the reason the result of "get-wmiobject win32_service..." was null.
I'm following up with the "Access Denied" in a new thread here:
Access Denied - get-wmiobject win32_service (Powershell)