I have 2 scripts as follows that gets websites for IIS.
IIS 6 -
$website = Get-WmiObject -Class IIsWebServerSetting -Namespace "root\microsoftiisv2" | Select ServerComment | Format-Table -HideTableHeaders | out-file c:\website.txt
$b = Get-Content -Path C:\website.txt
$b | ForEach {$_.TrimEnd()} | ? {$_.trim() -ne '' } > C:\website.txt
$b = Get-Content -Path C:\website.txt
#(ForEach ($a in $b) {$a.Replace(' ', '')}) > C:\website.txt
Get-Content C:\website.txt
IIS 7+
Import-Module webadministration
$a = Get-Website | Select-Object Name
$a | ForEach-Object {
$_.name = $_.name.replace(" ","")
}
$a | Format-Table -HideTableHeaders | Out-File $DeviceDrive\Apps\NetprobeNT\Auto-monitor\Website.txt
$b = Get-Content -Path $DeviceDrive\Apps\NetprobeNT\Auto-monitor\Website.txt
$b | ForEach {$_.TrimEnd()} | ? {$_.trim() -ne '' } > $DeviceDrive\Apps\NetprobeNT\Auto-monitor\Website.txt
$b = Get-Content -Path $DeviceDrive\Apps\NetprobeNT\Auto-monitor\Website.txt
#(ForEach ($a in $b) {$a.Replace(' ', '')}) > $DeviceDrive\Apps\NetprobeNT\Auto-monitor\Website.txt
I have a different script for IIS 6 (Windows 2003 hosts) because webadministration module is not available for II6.
I need to add an if statement that will add logic to run the correct code dependent on the host operating system and if W3SVC service (World Wide Web Publishing Service) is present (running or stopped). Something along the lines
IF W3SVC is present
Check host operating system
IF operating system = Windows 2003
Run II6 code
Else
Run II7+ code
I don't know where to begin with this script. PowerShell and scripting is new to me and this is part of my first script I am creating. Any help will be greatly appreciated.
I can get the host operating system but confused on how I would put logic into it to get the results I need.
(Get-WmiObject Win32_OperatingSystem).Name
Use Caption rather than Name. Other than that you simply plug the routine into your pseudocode:
if ((Get-WmiObject Win32_OperatingSystem).Caption -eq 'Windows 2003') {
# Run II6 code
} else {
# Run II7+ code
}
For the service you can use the Get-Service cmdlet:
if (Get-Service -Name w3svc -ErrorAction SilentlyContinue) {
...
}
or Get-WmiObject on the Win32_Service class if the Get-Service cmdlet isn't available in PowerShell v2 (not sure about that):
if (Get-WmiObject Win32_Service -Filter "Name='w3svc'") {
...
}
Related
Firstly, I have a csv file with a list of programs that should be included with the default installation of Windows. The CSV looks like this.
Name;Version;Vendor;InstallDate
64 Bit HP CIO Components Installer;18.2.4;Hewlett-Packard;20210902
7-Zip 18.05 (x64 edition);18.05.00.0;Igor Pavlov;20210812
Adobe Acrobat Reader DC;20.006.20034;Adobe Systems Incorporated;20210903
Secondly, I have a powershell script that tries to compare the list of programs on a remote computer with the list of programs in the CSV file (by Name, Version and Vendor). It is supposed to output only the non matching programs.
The comparing part works perfectly, but now I would like to color the lines of output which match by Name and Vendor, but not by Version. How would I go about doing that?
This is my powershell script.
$programs =#()
$programs = Get-WmiObject –computername <ComputerName> -Class Win32_Product
foreach($program in $programs) {
foreach($defprogram in Import-Csv -Path "...\defprograms.csv" -Delimiter ';') {
if ($program.Name -eq $defprogram.Name -And $program.Version -eq $defprogram.Version -And $program.Vendor -eq $defprogram.Vendor) {
$programs = $programs -ne $program }
}}
$programs | sort-object Name | format-table -AutoSize Name,Version,Vendor,InstallDate
And this is the output of fore mentioned script.
In the example in the output, I would like to make the '64 Bit HP CIO Components Installer' colored red.
64 Bit HP CIO Components Installer 15.2.1 Hewlett-Packard 20210909
Canon Laser Printer/Scanner/Fax Extended Survey Program 2.1.2 CANON INC. 20210216
Not a nice solution, but do the job :
$a = #"
Name;Version;Vendor;InstallDate
64 Bit HP CIO Components Installer;18.2.4;Hewlett-Packard;20210902
7-Zip 18.05 (x64 edition);18.05.00.0;Igor Pavlov;20210812
Adobe Acrobat Reader DC;20.006.20034;Adobe Systems Incorporated;20210903
"#
$b = $a | Convertfrom-Csv -Delimiter ';'
$b | % {Write-Host "$($_.name);" -ForegroundColor Red -NoNewline; Write-Host "$($_.Vendor);" -NoNewline; Write-Host $($_.Installdate) ;}
You can do this by reading the CSV with default programs you need to colorize.
Then create a regex string of their .Name property. Use Format-Table as usual, but append Out-String -Stream so you can capture the resulting lines in a variable
# your code here:
$programs = #(Get-WmiObject –computername <ComputerName> -Class Win32_Product)
foreach($program in $programs) {
foreach($defprogram in Import-Csv -Path "...\defprograms.csv" -Delimiter ';') {
if ($program.Name -eq $defprogram.Name -And $program.Version -eq $defprogram.Version -And $program.Vendor -eq $defprogram.Vendor) {
$programs = $programs -ne $program }
}
}
# read the default programs and create a regex string of their Name fields
$defprograms = Import-Csv -Path "...\defprograms.csv" -Delimiter ';'
$redprograms = '({0})' -f (($defprograms.Name | ForEach-Object { [regex]::Escape($_) }) -join '|')
# Format-Table the array of objects and capture the resulting lines in variable `$table`
$table = $programs | Sort-Object Name | Format-Table -AutoSize Name,Version,Vendor,InstallDate | Out-String -Stream
# next loop through these lines and find lines that match any of the default program names
switch -Regex ($table) {
"^$redprograms\s*" {
Write-Host $_.Substring(0, $matches[1].Length) -NoNewline -ForegroundColor Red
Write-Host $_.Substring($matches[1].Length)
}
default { $_ }
}
Output would then look something like
I will create (with PowerShell script) a table and add the result(Positive/negative) to it.
I have a text file computers.txt, in which all PCs are listed.
Like this
CSNAME Hotfixinfo
PC1 is installed
PC2 is not installed
PC3 is installed
etc.
With my actual script I can only see the positive result.
Get-Content .\computers.txt | Where {
$_ -and (Test-Connection $_ -Quiet)
} | foreach {
Get-Hotfix -Id KB4012212 -ComputerName $_ |
Select CSName,HotFixID |
ConvertTo-Csv |
Out-File "C:\$_.csv"
}
I'd suggest parsing through and handling the positive and negative results (also faster than the pipeline ForEach-Object):
:parse ForEach ($Computer in (Get-Content C:\Path\computers.txt))
{
If (Test-Connection $Computer -Quiet)
{
$Result = Get-Hotfix -Id KB4012212 -ComputerName $Computer -ErrorAction 'SilentlyContinue'
If ($Result)
{
$Result |
Select-Object -Property CSName,HotFixID |
ConvertTo-Csv -NoTypeInformation |
Out-File "C:\$Computer.csv"
Continue :parse
}
"`"CSName`",`"HotFixID`"`r`n`"$Computer`",`"NUL`"" |
Out-File "C:\$Computer.csv"
} Else { Write-Host 'Unable to connect to $Computer' }
}
I wrote a script that would fetch all the services running under an account name.
This part works fine except I want to add results to an existing csv. Add-content is messing up with my format. Please help as i am new here.
script:
$servers = #("a", "b")
$domain = "abc.com"
foreach($server in $servers){
$serverFQDN = $server+"."+"$domain"
Invoke-Command -computername $serverFQDN{
param($server)
Write-host "On" + $server -ForegroundColor Yellow
Get-WMIObject Win32_Service | Where-Object {$_.startname -match "ciqdev*" }
# | where-object {$_.state -eq "running"}
}-argumentlist $server | select pscomputername,caption | export-Csv Z:\RT\myCSV.csv
}
Use -Append :
export-Csv Z:\RT\myCSV.csv -Append
I can't get this code to work:
Get-ChildItem hklm:\software\microsoft\windows\currentversion\uninstall | ForEach- Object {Get-ItemProperty $.pspath} |
Where-Object { $.DisplayName -Eq 'Microsoft Lync 2013'} | Select-Object DisplayVersion
What am i doing wrong?
This one works fine, both of them are in regedit, I am aware that this example is not en wow6432node, could that be the problem?
Get-ChildItem hklm:\software\microsoft\windows\currentversion\uninstall | ForEach-Object {Get-ItemProperty $.pspath} |
Where-Object { $.DisplayName -Eq 'Microsoft Security Client'} | Select-Object DisplayVersion
You had several syntax errors. In such cases, I try to resolve the one-liner into multiple steps and write a .ps1 file to spot the error(s). Copy this into a file of your choice:
$a = Get-ChildItem hklm:\software\microsoft\windows\currentversion\uninstall
$b = $a | ForEach-Object { Get-ItemProperty $_.pspath}
$c = $b | Where-Object { $_.DisplayName -Eq 'Microsoft Lync 2013'}
$d = $c | Select-Object DisplayVersion
write-host `$d.length $d.length
write-host content of `$d
$d
write-host
write-host intermediate results were:
write-host `$c.length $c.length
write-host `$b.length $b.length
write-host `$a.length $a.length
pause
I get no results left after step $c in my case, because I do not have Microsoft Lync 2013 installed:
PS> .\test.ps1
$d.length 0
content of $d
intermediate results were:
$c.length 0
$b.length 976
$a.length 992
Drücken Sie die Eingabetaste, um den Vorgang fortzusetzen...:
How do I properly use $_ in out-file? Here's my code:
get-content computers.txt |
Where {$_ -AND (Test-Connection $_ -Quiet)} |
foreach { Get-Hotfix -computername $_ } |
Select CSName,Description,HotFixID,InstalledBy,InstalledOn |
convertto-csv | out-file "C:\$_.csv"
I'm trying to execute a get-hotfix for all the computers listed in the text file then I want them to be exported to CSV with the computer name as the filename.
You need one pipeline to process the computers.txt files, and a nested one inside the foreach to process the list of hotfixes for each computer:
get-content .\computers.txt |
Where {$_ -AND (Test-Connection $_ -Quiet)} |
foreach {
Get-Hotfix -computername $_ |
Select CSName,Description,HotFixID,InstalledBy,InstalledOn |
convertto-csv | out-file "C:\$_.csv"
}
Edit: Changed computers.txt to .\computers.txt, as this is required for local paths in powershell
i can see with this:
get-content .\computers.txt | Where {$_ -AND (Test-Connection $_ -Quiet)} | foreach{ Get-Hotfix -id KB4012212 -computername $_ | Select CSName,Description,HotFixID,InstalledBy,InstalledOn | convertto-csv | out-file "C:\$_.csv" }
i can see only in which PC is the fix (KB4012212) installed.
it's possible to see the following
CSNAME Fix(Inst/NotInst)
PC1 FIxInstalled
PC2 FixNotinstalled
PC3 FixnotInstalled
..
..
etc
I monkeyed with this for a while and nothing I found on-line worked until I used this combo.
I used the method is this thread but it was SO slow and I wanted to learn more about using jobs so this is what ended up working for me on Windows 7 PS Ver 4.
All other options were either too slow or did not return data from the remote system.
$VMs = get-content C:\WinVms.txt #Generate your hostnames list however you deem best.
foreach ($vm in $vms)
{
Write-Host "Attempting to get hotfixes on:" $vm
invoke-command -computername $vm -ScriptBlock {start-job -scriptblock {(get-hotfix | sort installedon)[-1]} | wait-job | receive-job} -AsJob
}
start-sleep 60 # give it a minute to complete
get-job | ? { $_.state -eq "Completed"} | receive-job -keep | export-csv c:\temp\win-patch.csv
you can check your failures too like this:
get-job | ? { $_.state -eq "Failed"}