Quantcast
Channel: Windows PowerShell forum
Viewing all 21975 articles
Browse latest View live

Changing (clustered) VM heartbeat monitoring via Powershell

$
0
0

Hi guys, 

Does anyone know if this is possible? I asked in the clustering forums but had no joy. I want to disable the O/S heartbeat monitoring for all machines, programmatically. I do not have SCVMM. 

Cheeers. 


How to replace a regular exepresion in a string in power shell

$
0
0

Hi,

Not able to replace "\X25" with "%" in powershell script.

$new = $inst1
$word = '\X25'

also tried

$word = "\X25"

$replacement = "%"
$newText = $new -replace $word,$replacement

following error has been occurred:

The regular expression pattern \X25 is not valid.

At C:\TWClient-Build\rgx.ps1:15 char:1

+ $newText = $new -replace $word,$replacement

+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidOperation: (\X25:String) [], RuntimeException

    + FullyQualifiedErrorId : InvalidRegularExpression

Thank You

timer.elapsed event addition

$
0
0
I need to execute javaw.exe process and monitor it in windows task manger 
if this process was killed then it will automatically UP after some time interval say 5 seconds
and it is writing all logs in log file, 
how to add scheduler in below script 
:eg. I need to add all below code under timer.elapsed event 
Clear-Host
$Logfile = "C:\himanshu\Logs\$(gc env:computername).log"
$exePath="C:\Windows\System32\notepad.exe"
$isRunning = (get-wmiobject win32_process | ?{  $_.Path -eq $exePath}  | measure-object | % { $_.Count }) -gt 0
$timespan=0
if(!(Test-Path -Path $Logfile)){
    new-item -Path $Logfile –itemtype file
}


do{
    $timespan++ 
if($isRunning -and ($time -gt 0)) 
{
    $isRunning
    $b="YES"
    LogWrite $b 
    }
    else
{
    $isRunning
    "opening notepad"
    #Start-Process -FilePath java.exe -ArgumentList -jar,C:\HP\AHCMail\AHC-2.9\AHCheck.jar,-classpath,$Env:CLASSPATH -NoNewWindow
    $Start = ([wmiclass]"win32_process").Create($exePath)
$b="NO"
    LogWrite $b
}
}
while($timespan -lt 0)



Function LogWrite
{
   Param ([string]$logstring,[string]$a)
   $a=Get-Date
   Add-content $Logfile -value ($a + "############" + $logstring)
}




Combining 2 PowerShell Commands for One Output

$
0
0

Folks, novice here and I am trying to combine the following commands into one output (if possible)...any guidance? Thanks!

Get-ADUser -Filter 'teletexterminalidentifier -like "*"'|Select-Object name,teletexterminalidentifier|Export-Csv c:\profile_set1.csv

Get-ADUser | select SamAccountName,Enabled | Out-File C:\AcctStatus.csv

In other words, is there a way to pipe these into one command and one set of results (one file)?

Thanks!

Odd Parsing Error w/ Powershell Script

$
0
0

What am I doing wrong??

function New-SchedTask
{
	$TaskName = Read-Host 'What would you like to name this job? Seperate words in name with an underscore ( _ ), be concise.'
	mkdir C:\Jobs\$TaskName | out-null
    	$Freq = "None"
	While ( $Freq -eq "None" ) {
		$RequestedFreq = Read-Host  "What frequency would you like this task to run? (Daily, Weekly, Monthly)"
		Switch ( $RequestedFreq.ToUpper() ) {"Daily" { "You picked Daily" ; $Freq = "-Daily" }"Weekly" { "You picked Weekly" ; $Freq = "-Weekly" }"Monthly" { "You picked Monthly" ; $Freq = "-Weekly -WeeksInterval 4" }
			default { "Default is Daily" ; $Freq = "-Daily"}
			}
		}
	$Day = Read-Host 'Which day of the week would you like this task to run on? (i.e. Monday or Monday,Tuesday,Wednesday. Note the lack of spaces after the comma when using multiple days)'
	$Time = Read-Host 'What time of day would you like this job to run? Please use 12 hour time with am or pm (i.e. 6am or 2pm).'
	$TaskTrigger = New-ScheduledTaskTrigger $Freq -At $Time -DaysOfWeek $Day
	$TaskAction = New-ScheduledTaskAction -Execute "PowerShell.exe" -Argument "C:\Jobs\$TaskName\$TaskName.script.ps1"
	Register-ScheduledTask -Action $TaskAction -Trigger $Tasktrigger -TaskName "$TaskName" -User "Administrator" -RunLevel Highest
	Write-Host "File transfer task, $TaskName, created and scheduled for $Day at $Time"
}
New-SchedTask

Running that in the ISE generates the following error:

(Just from running the $Freq section)
What frequency would you like this task to run? (Daily, Weekly, Monthly): Daily
You picked Daily
-Daily
Which day of the week would you like this task to run on? (i.e. Monday or Monday,Tuesday,Wednesday.
 Note the lack of spaces after the comma when using multiple days): Monday
What time of day would you like this job to run? Please use 12 hour time with am or pm(i.e. 6am or 2pm).: 2pm
2pm
-Daily
Monday
New-ScheduledTaskTrigger : Cannot process argument transformation on parameter 'Weekly'. Cannot
convert value "System.String" to type "System.Management.Automation.SwitchParameter". Boolean
parameters accept only Boolean values and numbers, such as $True, $False, 1 or 0.
At line:17 char:42+     $TaskTrigger = New-ScheduledTaskTrigger $Freq -At $Time -DaysOfWeek $Day+                                             ~~~~~+ CategoryInfo          : InvalidData: (:) [New-ScheduledTaskTrigger], ParameterBindingArgume
   ntTransformationException+ FullyQualifiedErrorId : ParameterArgumentTransformationError,New-ScheduledTaskTrigger

Echoing back each variable though, shows me all variables set properly. Am I missing something derpy?

Thanks,

Mike


Trying to find all files or folders with a specific owner recursively

$
0
0

I'm trying to find any file with a specific owner, let's call that owner "domain\account1" I've placed 2 files and a folder at various levels in a directory structure and when I run the following code from the folder those files (or folder) exist in, it works fine:

gci  | Select fullname,@{n='Owner';e={(Get-Acl $_).Owner}} | Where {$_.Owner -eq 'DOMAIN\account1'} 

But when I try to go to a common root of those files (and folder) and add -recurse to the gci, it shows only the folder. Is there something secret/hidden about gci that I need it to force-show, or am I doing something else wrong?

Thanks


zarberg@gmail.com

spawning PowerShell in another session, and calling file with spaces

$
0
0

I'm trying to create a function, that when called, will open another PowerShell window, and provide a "tail" like function via Get-Content. Manually, I can open another session and call Get-Content without issue, but having a hard time getting the syntax right for a function. The big issue is that the file that will be tailed has spaces in the file name.

$logpath = "\\test-app3\_install\logs\TEST-APP4 2015-01-06 08-56AM.log"
c:\windows\System32\WindowsPowerShell\v1.0\powershell.exe -NoProfile -Command "& {Get-Content -path $LogPath -wait}"

I end up with an error like this:

Get-Content : A positional parameter cannot be found that accepts argument '2015-01-06'.At line:1 char:4+ & {get-content -path \\test-app3\_install\logs\TEST-APP4 2015-01-06 08-56AM.log  ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~    + CategoryInfo          : InvalidArgument: (:) [Get-Content], ParameterBindingException    + FullyQualifiedErrorId : PositionalParameterNotFound,Microsoft.PowerShell.Commands.GetContentCommand

I tried wrapping $logpath as `"$logpath`", but no dice.

So I'm sure I just have a minor syntax issue here, but nothing I try is working. Suggestions?

Execution of DSC script with Powershell script

$
0
0

Currently, we have been using release management 2013 and release management deployment agents installed in target servers to execute PowerShell scripts that configure and deploy SharePoint sites.

We have successfully used DSC to do activities like install web servers and configure them. We even want to install SharePoint 2013 via DSC (if that is possible).

With the latest Release Management 2013, we are exploring if we can use DSC approach instead of depending on Release Management Deployment Agents to execute our PowerShell scripts (that configure SharePoint). Do you know if DSC can do that?


How to create multiple shared mailboxes in Office 365 using powershell?

$
0
0

I can successfully create a single shared mailbox with powershell without any problem.

However I have a client who has a requirement to set up 100+ shared mailboxes, with access for a specific user in their company.

Can you tell me how I can script a powershell script to do this?

Thanks in advance

p.s. I will have the required name and email address in a CSV:

eg:

name,friendly name,email address

Bob Jones,Bob Jones,bob.jones@domain.com

Thanks

Darren

Need help in checking server ping and out put the result is if the server is offline. The below script does not test for server availability, so i wanted to add that in the script.

$
0
0

$list = ".\list.txt"
$computers = get-content $list
$thresholdspace = 20 #Set free disk space threshold below in percent (default at 10%)
[int]$EventNum = 3
[int]$ProccessNumToFetch = 10
$ListOfAttachments = @()
$Report = @()
$CurrentTime = Get-Date


Function Get-HostUptime {
    param ([string]$ComputerName)
    $Uptime = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $ComputerName
    $LastBootUpTime = $Uptime.ConvertToDateTime($Uptime.LastBootUpTime)
    $Time = (Get-Date) - $LastBootUpTime
    Return '{0:00} Days, {1:00} Hours, {2:00} Minutes, {3:00} Seconds' -f $Time.Days, $Time.Hours, $Time.Minutes, $Time.Seconds
}


# Assemble the HTML Header and CSS for our Report
$HTMLHeader = @"
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
<html><head><title>My Systems Report</title>
<style type="text/css">
<!--
body {
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
}

    #report { width: 835px; }

    table{
    border-collapse: collapse;
    border: none;
    font: 10pt Verdana, Geneva, Arial, Helvetica, sans-serif;
    color: black;
    margin-bottom: 10px;
}

    table td{
    font-size: 12px;
    padding-left: 0px;
    padding-right: 20px;
    text-align: left;
}

    table th {
    font-size: 12px;
    font-weight: bold;
    padding-left: 0px;
    padding-right: 20px;
    text-align: left;
}

h2{ clear: both; font-size: 130%; }

h3{
    clear: both;
    font-size: 115%;
    margin-left: 20px;
    margin-top: 30px;
}

p{ margin-left: 20px; font-size: 12px; }

table.list{ float: left; }

    table.list td:nth-child(1){
    font-weight: bold;
    border-right: 1px grey solid;
    text-align: right;
}

table.list td:nth-child(2){ padding-left: 7px; }
table tr:nth-child(even) td:nth-child(even){ background: #CCCCCC; }
table tr:nth-child(odd) td:nth-child(odd){ background: #F2F2F2; }
table tr:nth-child(even) td:nth-child(odd){ background: #DDDDDD; }
table tr:nth-child(odd) td:nth-child(even){ background: #E5E5E5; }
div.column { width: 320px; float: left; }
div.first{ padding-right: 20px; border-right: 1px  grey solid; }
div.second{ margin-left: 30px; }
table{ margin-left: 20px; }
-->
</style>
</head>
<body>

"@


foreach ($computer in $computers) {


    $DiskInfo= Get-WMIObject -ComputerName $computer Win32_LogicalDisk | Where-Object{$_.DriveType -eq 3} | Select-Object SystemName, DriveType, VolumeName, Name, @{n='Size (GB)';e={"{0:n2}" -f ($_.size/1gb)}}, @{n='FreeSpace (GB)';e={"{0:n2}" -f ($_.freespace/1gb)}}, @{n='PercentFree';e={"{0:n2}" -f ($_.freespace/$_.size*100)}} | ConvertTo-HTML -fragment
    
    #region System Info
    $OS = (Get-WmiObject Win32_OperatingSystem -computername $computer).caption
    $SystemInfo = Get-WmiObject -Class Win32_OperatingSystem -computername $computer | Select-Object Name, TotalVisibleMemorySize, FreePhysicalMemory
    $TotalRAM = $SystemInfo.TotalVisibleMemorySize/1MB
    $FreeRAM = $SystemInfo.FreePhysicalMemory/1MB
    $UsedRAM = $TotalRAM - $FreeRAM
    $RAMPercentFree = ($FreeRAM / $TotalRAM) * 100
    $TotalRAM = [Math]::Round($TotalRAM, 2)
    $FreeRAM = [Math]::Round($FreeRAM, 2)
    $UsedRAM = [Math]::Round($UsedRAM, 2)
    $RAMPercentFree1 = [Math]::Round($RAMPercentFree, 2)
    $RAMPercentFree = "$($RAMPercentFree1)%"
    #endregion
    
    $CPUAvg = Get-WmiObject -computername $computer win32_processor | Measure-Object -property LoadPercentage -Average | Select Average
    $CPULoad = "$($CPUAvg.Average)%"
    $TopProcesses = Get-Process -ComputerName $computer | Sort WS -Descending | Select ProcessName, Id, WS -First $ProccessNumToFetch | ConvertTo-Html -Fragment
    
    #region Services Report
    $ServicesReport = @()
    $Services = Get-WmiObject -Class Win32_Service -ComputerName $computer | Where {($_.StartMode -eq "Auto") -and ($_.State -eq "Stopped")}

    foreach ($Service in $Services) {
        $row = New-Object -Type PSObject -Property @{
               Name = $Service.Name
            Status = $Service.State
            StartMode = $Service.StartMode
        }
        
    $ServicesReport += $row
    
    }
    
    $ServicesReport = $ServicesReport | ConvertTo-Html -Fragment
    #endregion
        
    #region Event Logs Report
    $SystemEventsReport = @()
    $SystemEvents = Get-EventLog -ComputerName $computer -LogName System -EntryType Error,Warning -Newest $EventNum
    foreach ($event in $SystemEvents) {
        $row = New-Object -Type PSObject -Property @{
            TimeGenerated = $event.TimeGenerated
            EntryType = $event.EntryType
            Source = $event.Source
            Message = $event.Message
        }
        $SystemEventsReport += $row
    }
            
    $SystemEventsReport = $SystemEventsReport | ConvertTo-Html -Fragment
    
    $ApplicationEventsReport = @()
    $ApplicationEvents = Get-EventLog -ComputerName $computer -LogName Application -EntryType Error,Warning -Newest $EventNum
    foreach ($event in $ApplicationEvents) {
        $row = New-Object -Type PSObject -Property @{
            TimeGenerated = $event.TimeGenerated
            EntryType = $event.EntryType
            Source = $event.Source
            Message = $event.Message
        }
        $ApplicationEventsReport += $row
    }
    
    $ApplicationEventsReport = $ApplicationEventsReport | ConvertTo-Html -Fragment
    #endregion
    

    #region Uptime
    # Fetch the Uptime of the current system using our Get-HostUptime Function.
    $SystemUptime = Get-HostUptime -ComputerName $computer
    #endregion

    # Create HTML Report for the current System being looped through
    $CurrentSystemHTML = @"
    <hr noshade size=3 width="100%">
    <div id="report">
    <p><h2>$computer Report</p></h2>
    <h3>System Info</h3>
    <table class="list">
    <tr>
    <td>System Uptime</td>
    <td>$SystemUptime</td>
    </tr>
    <tr>
    <td>OS</td>
    <td>$OS</td>
    </tr>
    <tr>
    <td>Average CPU Utilization </td>
    <td>$CPULoad</td>
    </tr>
    <tr>
    <td>Total RAM (GB)</td>
    <td>$TotalRAM</td>
    </tr>
    <tr>
    <td>Free RAM (GB)</td>
    <td>$FreeRAM</td>
    </tr>
    <tr>
    <td>Percent free RAM</td>
    <td>$RAMPercentFree</td>
    </tr>
    </table>
    
            
    <h3>Disk Info</h3>
    <table class="normal">$DiskInfo</table>
    <br></br>
    
    <div class="first column">
    <h3>System Processes - Top $ProccessNumToFetch Highest Memory Usage</h3>
    <p>The following $ProccessNumToFetch processes are those consuming the highest amount of Working Set (WS) Memory (bytes) on $computer</p>
    <table class="normal">$TopProcesses</table>
    </div>
    <div class="second column">
    
    <h3>System Services - Automatic Startup but not Running</h3>
    <p>The following services are those which are set to Automatic startup type, yet are currently not running on $computer</p>
    <table class="normal">
    $ServicesReport
    </table>
    </div>
    
    <h3>Events Report - The last $EventNum System/Application Log Events that were Warnings or Errors</h3>
    <p>The following is a list of the last $EventNum <b>System log</b> events that had an Event Type of either Warning or Error on $computer</p>
    <table class="normal">$SystemEventsReport</table>

    <p>The following is a list of the last $EventNum <b>Application log</b> events that had an Event Type of either Warning or Error on $computer</p>
    <table class="normal">$ApplicationEventsReport</table>
"@
    # Add the current System HTML Report into the final HTML Report body
    $HTMLMiddle += $CurrentSystemHTML
    
    }


# Assemble the closing HTML for our report.
$HTMLEnd = @"
</div>
</body>
</html>
"@


# Assemble the final report from all our HTML sections
$HTMLmessage = $HTMLHeader + $HTMLMiddle + $Outputreport +$HTMLEnd
# Save the report out to a file in the current path
$HTMLmessage | Out-File ((Get-Location).Path + "\report.html")

Update-FormatData won't load my ps1xml ISE theme file

$
0
0

Hi,

I've created a ps1xml theme file for Powershell ISE, using the "manage themes" UI in the options of the ISE.
This theme loads perfectly when I import it on machines using the "manage themes" UI.

But when I try to load the theme programmatically using the following command, I get an error.  

update-formatdata C:\MyTheme.StorableColorTheme.ps1xml

The error is :

Update-FormatData : Errors occurred while loading the format data file: 
C:\MyTheme.StorableColorTheme.ps1xml, Error at XPath  in file C:\MyTheme.StorableColorTheme.ps1xml: StorableColorTheme is an un
known node.
At line:1 char:1
+ Update-FormatData -AppendPath C:\MyTheme.StorableColorTheme.ps1xml ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Update-FormatData], RuntimeException
    + FullyQualifiedErrorId : FormatXmlUpdateException,Microsoft.PowerShell.Commands.UpdateFormatDataCommand

I've tested this on multiple machines in our network and the error is the same. Could I be missing some XML or framework related updates ? Any ideas ?

Regards Vincent

Generate files - tweak the $i variable

$
0
0

Hallo,

using

for ($i=1;$i -le 6000;$i++){new-item testing_$i.txt -type file} I will generate 6000 files.
What tweaks I need to do, if I wanna have them in the format "testing_0001.txt" => "testing_6000.txt " and not testing_1 => testing_6000 .. so the $i will be always 4-digit ?

Additional values needs to be added at the begining of the HTML report generated in the below script.

$
0
0

Hi,

I want to add some website status and share path availability check on top of  the report generated in the below script, can some one please assist .

$list = ".\list.txt"
$computers = get-content $list
$thresholdspace = 20 #Set free disk space threshold below in percent (default at 10%)
[int]$EventNum = 3
[int]$ProccessNumToFetch = 10
$ListOfAttachments = @()
$Report = @()
$CurrentTime = Get-Date

Function Get-HostUptime {
    param ([string]$ComputerName)
    $Uptime = Get-WmiObject -Class Win32_OperatingSystem -ComputerName $ComputerName
    $LastBootUpTime = $Uptime.ConvertToDateTime($Uptime.LastBootUpTime)
    $Time = (Get-Date) - $LastBootUpTime
    Return '{0:00} Days, {1:00} Hours, {2:00} Minutes, {3:00} Seconds' -f $Time.Days, $Time.Hours, $Time.Minutes, $Time.Seconds
}

# Assemble the HTML Header and CSS for our Report
$HTMLHeader = @"
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">
<html><head><title>My Systems Report</title>
<style type="text/css">
<!--
body {
font-family: Verdana, Geneva, Arial, Helvetica, sans-serif;
}

    #report { width: 835px; }

    table{
    border-collapse: collapse;
    border: none;
    font: 10pt Verdana, Geneva, Arial, Helvetica, sans-serif;
    color: black;
    margin-bottom: 10px;
}

    table td{
    font-size: 12px;
    padding-left: 0px;
    padding-right: 20px;
    text-align: left;
}

    table th {
    font-size: 12px;
    font-weight: bold;
    padding-left: 0px;
    padding-right: 20px;
    text-align: left;
}

h2{ clear: both; font-size: 130%; }

h3{
    clear: both;
    font-size: 115%;
    margin-left: 20px;
    margin-top: 30px;
}

p{ margin-left: 20px; font-size: 12px; }

table.list{ float: left; }

    table.list td:nth-child(1){
    font-weight: bold;
    border-right: 1px grey solid;
    text-align: right;
}

table.list td:nth-child(2){ padding-left: 7px; }
table tr:nth-child(even) td:nth-child(even){ background: #CCCCCC; }
table tr:nth-child(odd) td:nth-child(odd){ background: #F2F2F2; }
table tr:nth-child(even) td:nth-child(odd){ background: #DDDDDD; }
table tr:nth-child(odd) td:nth-child(even){ background: #E5E5E5; }
div.column { width: 320px; float: left; }
div.first{ padding-right: 20px; border-right: 1px  grey solid; }
div.second{ margin-left: 30px; }
table{ margin-left: 20px; }
-->
</style>
</head>
<body>

"@


foreach ($computer in $computers) {


    $DiskInfo= Get-WMIObject -ComputerName $computer Win32_LogicalDisk | Where-Object{$_.DriveType -eq 3} | Select-Object SystemName, DriveType, VolumeName, Name, @{n='Size (GB)';e={"{0:n2}" -f ($_.size/1gb)}}, @{n='FreeSpace (GB)';e={"{0:n2}" -f ($_.freespace/1gb)}}, @{n='PercentFree';e={"{0:n2}" -f ($_.freespace/$_.size*100)}} | ConvertTo-HTML -fragment

    #region System Info
    $OS = (Get-WmiObject Win32_OperatingSystem -computername $computer).caption
    $SystemInfo = Get-WmiObject -Class Win32_OperatingSystem -computername $computer | Select-Object Name, TotalVisibleMemorySize, FreePhysicalMemory
    $TotalRAM = $SystemInfo.TotalVisibleMemorySize/1MB
    $FreeRAM = $SystemInfo.FreePhysicalMemory/1MB
    $UsedRAM = $TotalRAM - $FreeRAM
    $RAMPercentFree = ($FreeRAM / $TotalRAM) * 100
    $TotalRAM = [Math]::Round($TotalRAM, 2)
    $FreeRAM = [Math]::Round($FreeRAM, 2)
    $UsedRAM = [Math]::Round($UsedRAM, 2)
    $RAMPercentFree1 = [Math]::Round($RAMPercentFree, 2)
    $RAMPercentFree = "$($RAMPercentFree1)%"
    #endregion

    $CPUAvg = Get-WmiObject -computername $computer win32_processor | Measure-Object -property LoadPercentage -Average | Select Average
    $CPULoad = "$($CPUAvg.Average)%"
    $TopProcesses = Get-Process -ComputerName $computer | Sort WS -Descending | Select ProcessName, Id, WS -First $ProccessNumToFetch | ConvertTo-Html -Fragment

    #region Services Report
    $ServicesReport = @()
    $Services = Get-WmiObject -Class Win32_Service -ComputerName $computer | Where {($_.StartMode -eq "Auto") -and ($_.State -eq "Stopped")}

    foreach ($Service in $Services) {
        $row = New-Object -Type PSObject -Property @{
               Name = $Service.Name
            Status = $Service.State
            StartMode = $Service.StartMode
        }

    $ServicesReport += $row

    }

    $ServicesReport = $ServicesReport | ConvertTo-Html -Fragment
    #endregion

    #region Event Logs Report
    $SystemEventsReport = @()
    $SystemEvents = Get-EventLog -ComputerName $computer -LogName System -EntryType Error,Warning -Newest $EventNum
    foreach ($event in $SystemEvents) {
        $row = New-Object -Type PSObject -Property @{
            TimeGenerated = $event.TimeGenerated
            EntryType = $event.EntryType
            Source = $event.Source
            Message = $event.Message
        }
        $SystemEventsReport += $row
    }

    $SystemEventsReport = $SystemEventsReport | ConvertTo-Html -Fragment

    $ApplicationEventsReport = @()
    $ApplicationEvents = Get-EventLog -ComputerName $computer -LogName Application -EntryType Error,Warning -Newest $EventNum
    foreach ($event in $ApplicationEvents) {
        $row = New-Object -Type PSObject -Property @{
            TimeGenerated = $event.TimeGenerated
            EntryType = $event.EntryType
            Source = $event.Source
            Message = $event.Message
        }
        $ApplicationEventsReport += $row
    }

    $ApplicationEventsReport = $ApplicationEventsReport | ConvertTo-Html -Fragment
    #endregion


    #region Uptime
    # Fetch the Uptime of the current system using our Get-HostUptime Function.
    $SystemUptime = Get-HostUptime -ComputerName $computer
    #endregion

    # Create HTML Report for the current System being looped through
    $CurrentSystemHTML = @"
    <hr noshade size=3 width="100%">
    <div id="report">
    <p><h2>$computer Report</p></h2>
    <h3>System Info</h3>
    <table class="list">
    <tr>
    <td>System Uptime</td>
    <td>$SystemUptime</td>
    </tr>
    <tr>
    <td>OS</td>
    <td>$OS</td>
    </tr>
    <tr>
    <td>Average CPU Utilization </td>
    <td>$CPULoad</td>
    </tr>
    <tr>
    <td>Total RAM (GB)</td>
    <td>$TotalRAM</td>
    </tr>
    <tr>
    <td>Free RAM (GB)</td>
    <td>$FreeRAM</td>
    </tr>
    <tr>
    <td>Percent free RAM</td>
    <td>$RAMPercentFree</td>
    </tr>
    </table>


    <h3>Disk Info</h3>
    <table class="normal">$DiskInfo</table>
    <br></br>

    <div class="first column">
    <h3>System Processes - Top $ProccessNumToFetch Highest Memory Usage</h3>
    <p>The following $ProccessNumToFetch processes are those consuming the highest amount of Working Set (WS) Memory (bytes) on $computer</p>
    <table class="normal">$TopProcesses</table>
    </div>
    <div class="second column">

    <h3>System Services - Automatic Startup but not Running</h3>
    <p>The following services are those which are set to Automatic startup type, yet are currently not running on $computer</p>
    <table class="normal">
    $ServicesReport
    </table>
    </div>

    <h3>Events Report - The last $EventNum System/Application Log Events that were Warnings or Errors</h3>
    <p>The following is a list of the last $EventNum <b>System log</b> events that had an Event Type of either Warning or Error on $computer</p>
    <table class="normal">$SystemEventsReport</table>

    <p>The following is a list of the last $EventNum <b>Application log</b> events that had an Event Type of either Warning or Error on $computer</p>
    <table class="normal">$ApplicationEventsReport</table>
"@
    # Add the current System HTML Report into the final HTML Report body
    $HTMLMiddle += $CurrentSystemHTML

    }

# Assemble the closing HTML for our report.
$HTMLEnd = @"
</div>
</body>
</html>
"@

# Assemble the final report from all our HTML sections
$HTMLmessage = $HTMLHeader + $HTMLMiddle + $Outputreport +$HTMLEnd
# Save the report out to a file in the current path
$HTMLmessage | Out-File ((Get-Location).Path + "\report.html")

                                                                                           

Show user detail for ActiveUserReports

$
0
0

I use, Get-CsActiveUserReport | Format-List

to show me how many active users are logged in to lync online 

example output

------------

ActiveUsers                   : 73
ActiveIMUsers                 : 0
ActiveAudioUsers              : 0
ActiveVideoUsers              : 0
ActiveApplicationSharingUsers : 0
ActiveFileTransferUsers       : 0

What i want to be able to do is drill down into the activeUsers :73 to show me which users are actively using this service. Would anyone know if this is possible and the best method I could use.

Many thanks

Modify Powershell Script

$
0
0

Hello

How can I modify this script to target all Users OU in one domain to move all disabled accounts from each Users OU to move to the Disabled Users OU?

Search-ADAccount –AccountDisabled –UsersOnly –SearchBase “OU=Users,OU=test,OU=domain,DC=domain,DC=com”  | Move-ADObject –TargetPath “OU=Disabled Users,DC=domain,DC=com”

The above script will work for but only for one OU, I need it to target all OU=Users OU.

Thanks


Automatically create ODBC DSN connection with special port and password. Add-OdbcDsn cmdlet

$
0
0

Hi,

I first posted a question in the SQL forum but I'm posting it here instead because its a Powershell question.

In a non-persitent VDI enviroment we are trying to automatically create a ODBC DSN connection to a SQL server.

We are using Windows 8.1 so we also have Powershell 4 together with the add-odbcdsn cmdlet. 

But when trying to add set -SetPropertyValue for network port different than default and a password we get an error.

here is the command:

Add-OdbcDsn -Name test -DriverName "SQL Server" -DsnType User -SetPropertyValue @("PWD=test", "SERVER=10.0.0.1")

and here is the error message:

Add-OdbcDsn : Attempt to set the {UID or PWD} key of a DSN. These keys should not be stored in the registry for securit
y reason. Provide the credential information at runtime via SQLDriverConnect, SQLConnect or SQLBrowseConnect.
At line:1 char:1+ Add-OdbcDsn -Name test -DriverName "SQL Server" -DsnType User -SetPropertyValue @ ...+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : InvalidArgument: (MSFT_OdbcDsnTask:Root/Microsoft/...SFT_OdbcDsnTask) [Add-OdbcDsn], Cim
   Exception+ FullyQualifiedErrorId : MI RESULT 4,Add-OdbcDsn

NB!:  this command does not contain a port number, but when adding it without a password(PWD string) we just the default port.

Filter Get-ChildItem on TargetPath?

$
0
0

With Get-ChildItem is it possible to filter on a shortcut's TargetPath? I did a Get-Member on a shortcut and I don't see anything there that looks promising, so I am filtering to just get shortcuts, then looping and evaluating 

if (($Shell.CreateShortcut($Shortcut.FullName)).TargetPath -eq $Document)

where $Document is the TargetPath I am looking for. And it works. But I wonder if there is a pipeline way to do it, rather than the loop?

PS Script to traverse entire registry / search values / then delete them

$
0
0

Get-ChildItem -path HKLM:\SOFTWARE\ -Recurse | Get-ItemProperty | Where-Object {$_.ItemProperty -in "Cisco","cisco","anyconnect","Anyconnect"} | Remove-Item

I have tried so many variations of this at this point I am almost kind of lost in all of it at this point.

What I am trying to accomplish it to search through each key of the registry, and also each value for each key. If the key or the value contain anything relating to cisco anyconnect then I want to delete the value, and also delete the key.

I cant seem to construct the proper Where-Object statement to get just the values isolated that contain anything cisco related.

Im also not sure if even once I was able to isolate those if piping them to Remove-Item would even work. Others had said to try Remove-ItemProperty, but again I was unable to try and filter out just the keys/values relating to anyconnect to get this all working.

Just looking for some possible suggestions / guidance at this point.

Comparing 2 multidimensional arrays

$
0
0

Hi,

I have 2 arrays:

$A=@((1,A,D),(2,B,K),(3,C,X),(4,D,L))
$B=@((1,A,D),(2,B,K),(2S,J,T),(3,C,X),(4,D,L))

In fact those arrays contain around 300 values each.

I would like comparing only the second field of each item so for Array A: A,B,C,D and array B: A,B,J,C,D

What is the most efficient way to compare both arrays? In this exemple, in array B the value J is the new one.

I tried Compare-Object but it is comparing not the whole array but just side-by-side.

Thanks,

Loading display names in array

$
0
0

Hi,

I would like comparing registry display names before and after a software installation.

So the function below is :

1. loading display names

2. Then I create manually a registry display names

3. I load again the display names

4. And I am running a comparison between previous and after installation.

The display names, I created is Vcredist2005. So the comparison should return Vcredist2005.

But I get only the last value of the arrays. Why??

Function Get-DisplayName {
	Begin {
			[string[]]$regKeyApplications = 'HKLM:SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall',
			'HKLM:SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall'
	}
	Process {
			[psobject[]]$installedApplication = @()
			ForEach ($regKey in $regKeyApplications) {

				$installedApplication += Get-ChildItem $regKey | foreach { Get-ItemProperty $_.PSPath } `
				| select DisplayName `
				| Where {$_.DisplayName -ne $null}| Sort-Object DisplayName

			}

	$installedApplication=$installedApplication | Sort-Object DisplayName
	Write-Output $installedApplication

	}

	End {

	}
}
$a=Get-DisplayName
$a.Count
#Add a false display name in the registry before continuing running.
#I added Vcredist2005
pause
$b=Get-DisplayName
$b.Count
Compare-Object -ReferenceObject $B -DifferenceObject $A 

Thanks,


Viewing all 21975 articles
Browse latest View live


Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>