I'm trying to get the below format printed for few of our servers:
[serverName]|[siteName]|[appPoolName]|[appPoolState]|[appPoolRecycleSchedule]
This is what I've gotten so far:
$Pool = Get-ChildItem IIS:\AppPools
foreach ( $p in $Pool )
{
$app_pool = $p.Name
$timing = Get-ItemProperty IIS:\\AppPools\$app_pool -name recycling.periodicRestart.schedule.collection
Write-Host "$($compName)|$($app_pool)|$($p.state)|$($timing.value)"
}
How do I get the site name in here?
Thanks,
Arun
I was able to get this working - thanks to a whole bunch of websites!.
$Pool = Get-ChildItem IIS:\AppPools
foreach ( $p in $Pool )
{
$app_pool = $p.Name
$apps = (Get-WebConfigurationProperty "/system.applicationHost/sites/site/application[`
#applicationPool='$app_pool']" "machine/webroot/apphost" -name path).ItemXPath
$site = ''
foreach ($s in $apps) {
$name = $s -replace "\/system.applicationHost\/sites\/site\[\#name='", ""
$name = $name -replace "' and \#id='\d{1,10}'\]\/application\[\#path='", ""
$name = $name -replace "'\]",""
if($site -eq ''){
$site = $name
}
else{
$site = $site + ", " + $name
}
}
if($site -eq "")
{
$site = "NotFound"
}
$timing = Get-ItemProperty IIS:\\AppPools\$app_pool -name recycling.periodicRestart.schedule.collection
Write-Host "$($compName)|$($app_pool)|$($p.state)|$($timing.value)|$($site)"
}
Related
so I m having this issue with getting my results to write out to an Out-file.
The problem I m having is, if new file item does exist, the error message I m getting is saying the path is null.
Please review the script and let me know your thoughts
thanks
$sScriptVersion = "1.0"
$dir = $PSScriptRoot
$svrlist += $dir + '\' + 'serverlist.txt'
$folder = 'search'
$computername = Get-Content $svrlist
$drv_array = #()
$new_drv_array =#()
$SearchStr = "error"
$log_pth = 'ProgramData\something\something\something\logs'
$file_logs = #()
$log_pth = #()
$log_nme = #()
$srchpath = #()
foreach($server in $computername)
{
$disks = Get-WmiObject -ComputerName $server -Class Win32_LogicalDisk -Filter "DriveType = 3";
foreach($disk in $disks)
{
$drv_array += $disk.DeviceID;
}
$driv =Foreach-Object {$drv_array -replace ":", "$"}
foreach($drv in $driv)
{
$new_drv_array += '\\'+ $server + '\'+ $drv +'\'+ $log_pth
}
}
Foreach($tst_pth in $new_drv_array )
{
$dvr_testpath = test-path $tst_pth
$srchpath += $tst_pth + '\'+ "*.*"
if ($dvr_testpath -eq $false)
{
write-host "This path does not exist " $tst_pth
}
else
{
write-host "This path does exist" $tst_pth
$Sel = Select-String -pattern $SearchStr -Context 2, 3 -path $srchpath
$out_file = New-item -ErrorAction ignore -itemtype File (join-path $dir1 $log_nme)
This is the part I'm having the issues with
$tst = Test-Path $out_file
if($tst -eq $false)
{
write-host "writing out parsed log file"
if($Sel -ne $null)
{
$Sel| Out-File $out_file
}
}
else
{
write-host " parsed log file does exist"
if($Sel -ne $null)
{
$Sel| Out-File -Append $out_file
}
}
}
}
I am quite new to powershell. I am trying to remote to PCs in a csv file and extract the status of a registry key. However I get the error
"Unexpected token '-ArgumentList' in expression or statement." when I try to execute. And I am not pretty sure on the syntax of the Invoke-Command, can one of your pls verify if it is correct? Appreciate your help.
So basically, what I intend to do is, get computer names, specify an output path which I will be then using inside the invoke command. Testing the online status of the PC, checking the required registry value and writing it to the file.
$computers = Get-Content "C:\Temp\AutoSug\Computers.txt"
$output_path = "C:\Temp\AutoSug\output.csv"
foreach($computer in $computers)
{
Test-Connection -computername $computer -Quiet
If (Test-Connection $computer -count 1 -quiet)
{
Invoke-Command -computer $computer -ScriptBlock
{
param(
$output_path
)
$hostname = (Get-CIMInstance CIM_ComputerSystem).Name
$objExcel = New-Object -ComObject Excel.Application
if ($objExcel.Version -eq "15.0")
{
$HKEY_USERS = Get-ChildItem REGISTRY::HKEY_USERS | where-object { ($_.Name -like "*S-1-5-21*") -and ($_.Name -notlike "*_Classes") }
$Users = #()
$value = #()
foreach ($User in $HKEY_USERS)
{
$PROFILESID = Get-ChildItem REGISTRY::"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" | Where-Object { $_.name -like "*" + $USER.PSChildName + "*" }
$SID = $PROFILESID.PSChildName
foreach ($value in $SID)
{
$key = Get-Item REGISTRY::HKEY_USERS\$VALUE\Software\Microsoft\Office\15.0\Outlook\Preferences -ErrorAction SilentlyContinue
$gold = $key.property
if($gold -like 'ShowAutoSug')
{
$grail = (Get-ItemProperty REGISTRY::HKEY_USERS\$VALUE\Software\Microsoft\Office\15.0\Outlook\Preferences).ShowAutoSug
$objSID = New-Object System.Security.Principal.SecurityIdentifier($value)
$objUser = $objSID.Translate([System.Security.Principal.NTAccount])
$hostname, $objUser, $value , $grail | Add-Content $output_path
}
else
{
$objSID = New-Object System.Security.Principal.SecurityIdentifier($value)
$objUser = $objSID.Translate([System.Security.Principal.NTAccount])
$hostname,$objUser, $value , "The Auto Complete is not disabled" | Add-Content $output_path
}
}
}
}
if ($objExcel.Version -eq "14.0")
{
$HKEY_USERS = Get-ChildItem REGISTRY::HKEY_USERS | where-object { ($_.Name -like "*S-1-5-21*") -and ($_.Name -notlike "*_Classes") }
$Users = #()
$value = #()
foreach ($User in $HKEY_USERS)
{
$PROFILESID = Get-ChildItem REGISTRY::"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" | Where-Object { $_.name -like "*" + $USER.PSChildName + "*" }
$SID = $PROFILESID.PSChildName
foreach ($value in $SID)
{
$key = Get-Item REGISTRY::HKEY_USERS\$VALUE\Software\Microsoft\Office\14.0\Outlook\Preferences -ErrorAction SilentlyContinue
$gold = $key.property
if($gold -like 'ShowAutoSug')
{
$grail = (Get-ItemProperty REGISTRY::HKEY_USERS\$VALUE\Software\Microsoft\Office\14.0\Outlook\Preferences).ShowAutoSug
$objSID = New-Object System.Security.Principal.SecurityIdentifier($value)
$objUser = $objSID.Translate([System.Security.Principal.NTAccount])
$hostname, $objUser, $value , $grail | Add-Content -path $output_path
}
else
{
$objSID = New-Object System.Security.Principal.SecurityIdentifier($value)
$objUser = $objSID.Translate([System.Security.Principal.NTAccount])
$hostname,$objUser, $value , "The Auto Complete is not disabled" | Add-Content $output_path
}
}
}
}
if ($objExcel.Version -eq "12.0")
{
$HKEY_USERS = Get-ChildItem REGISTRY::HKEY_USERS | where-object { ($_.Name -like "*S-1-5-21*") -and ($_.Name -notlike "*_Classes") }
$Users = #()
$value = #()
foreach ($User in $HKEY_USERS)
{
$PROFILESID = Get-ChildItem REGISTRY::"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList" | Where-Object { $_.name -like "*" + $USER.PSChildName + "*" }
$SID = $PROFILESID.PSChildName
foreach ($value in $SID)
{
$key = Get-Item REGISTRY::HKEY_USERS\$VALUE\Software\Microsoft\Office\12.0\Outlook\Preferences -ErrorAction SilentlyContinue
$gold = $key.property
if($gold -like 'ShowAutoSug')
{
$grail = (Get-ItemProperty REGISTRY::HKEY_USERS\$VALUE\Software\Microsoft\Office\12.0\Outlook\Preferences).ShowAutoSug
$objSID = New-Object System.Security.Principal.SecurityIdentifier($value)
$objUser = $objSID.Translate([System.Security.Principal.NTAccount])
$hostname, $objUser, $value , $grail | Add-Content $output_path
}
else
{
$objSID = New-Object System.Security.Principal.SecurityIdentifier($value)
$objUser = $objSID.Translate([System.Security.Principal.NTAccount])
$hostname,$objUser, $value , "The Auto Complete is not disabled" |Add-Content $output_path
}
}
}
}
} -ArgumentList $output_path
}
else
{
$status = 'Offline'
$computer , $status | Add-Content $output_path
}
}
To fix your error, simply cut -ArgumentList $output_path and put it before -ScriptBlock like:
Invoke-Command -computer $computer -ArgumentList $output_path -ScriptBlock ....
function Get-LoggedOnUsers ($server) {
if($server -eq $null){
$server = "localhost"
}
$users = #()
# Query using quser, 2>$null to hide "No users exists...", then skip to the next server
$quser = quser /server:$server 2>$null
if(!($quser)){
Continue
}
#Remove column headers
$quser = $quser[1..$($quser.Count)]
foreach($user in $quser){
$usersObj = [PSCustomObject]#{Server=$null;Username=$null;SessionName=$null;SessionId=$Null;SessionState=$null;LogonTime=$null;IdleTime=$null}
$quserData = $user -split "\s+"
#We have to splice the array if the session is disconnected (as the SESSIONNAME column quserData[2] is empty)
if(($user | select-string "Disc") -ne $null){
#User is disconnected
$quserData = ($quserData[0..1],"null",$quserData[2..($quserData.Length -1)]) -split "\s+"
}
# Server
$usersObj.Server = $server
# Username
$usersObj.Username = $quserData[1]
# SessionName
$usersObj.SessionName = $quserData[2]
# SessionID
$usersObj.SessionID = $quserData[3]
# SessionState
$usersObj.SessionState = $quserData[4]
# IdleTime
$quserData[5] = $quserData[5] -replace "\+",":" -replace "\.","0:0" -replace "Disc","0:0"
if($quserData[5] -like "*:*"){
$usersObj.IdleTime = [timespan]"$($quserData[5])"
}elseif($quserData[5] -eq "." -or $quserData[5] -eq "none"){
$usersObj.idleTime = [timespan]"0:0"
}else{
$usersObj.IdleTime = [timespan]"0:$($quserData[5])"
}
# LogonTime
$usersObj.LogonTime = (Get-Date "$($quserData[6]) $($quserData[7]) $($quserData[8] )")
$users += $usersObj
}
return $users
}
function LogOutUser {
$test = Get-LoggedOnUsers
$count = 0
$nameArray = #()
$sessionArray = #()
$logonTimeArray = #()
foreach($line in $test){
$field1 = $line.Username
$field2 = $line.SessionID
$field3 = $line.LogonTime
$nameArray += $field1
$sessionArray += $field2
$logonTimeArray += $field3
$count+=1
}
$session1 = [INT]$sessionArray[0]
$session2 = [INT]$sessionArray[1]
Write-Host $nameArray
Write-Host $sessionArray
Write-Host $logonTimeArray
Write-Host $count
Write-Host $session1
Write-Host $session2
if(($count -gt 1) -and ($session2 -gt $session1 )){
logoff $session1
}
}
Get-LoggedOnUsers
LogOutUser
this code works in the ISE but it does not work when running from the console, what is happening? It does exactly what i want it to do through the ISE but when I try running as a scheduled task it doesn't work also it doesnt work when trying to run with console. i have tried powershell.exe -noexit -file c:\logofftest1.ps1 but still no success
I have a telnet script as function, that behaves well, if it is called directly.
If I try to call it in a loop, it starts to misbehave.
This code is working fine for me:
$HostList = Import-CSV ".\list.csv" -Header IP,Script,SNMP -Delimiter (";")
ForEach ($item in $HostList)
{
Write-Host "Connecting to: $item" -NoNewline
$Script = Get-Content (".\Scripts\" + $item.Script + ".txt")
Get-Telnet -RemoteHost $item.IP -SNMPLoc $item.SNMP -Login $login -PassWord $password -Commands $Script
}
The following changes seems to break the script, as I want to make the contril file more dynamic:
$login = Read-Host 'Please provide the login? '
$password = Read-Host -AsSecureString 'Please provide the password? '
Import-CSV ".\list.csv" -Delimiter (";") | Foreach-Object {
[String[]] $VarValues = ""
foreach ($item in $_.PSObject.Properties)
{
if ($item.Name.Contains("IP"))
{
$HostName = $item.Value
}
if ($item.Name.Contains("Script"))
{
$Script = Get-Content (".\Scripts\" + $item.Value + ".txt")
}
if (!$item.Name.Contains("IP") -and !$item.Name.Contains("Script"))
{
$VarValues += $item.Name + "#" + $item.Value
}
}
Get-Telnet -RemoteHost $HostName -Login $login -PassWord $password -Commands $Script -Vars $VarValues
}
If I call Get-Telnet the function on is own, it's still working.
As I don't known, how many possible columns might be in the control file (.\list.csv), is there any other way, to create $VarValues list from the file?
I changed it to >
$data = Import-CSV $ControlFile -Delimiter (";")
$OutputPath = $OutputPath + "%{0}.txt"
Clear-Host
foreach ($obj in $data)
{
[String[]] $VarValues = ""
foreach ($item in $obj.psobject.properties)
{
$Key = $item.name
$Value = $item.value
switch ($Key)
{
"IP" { $HostName = $Value }
"Script" { $Script = Get-Content ($ScriptPath + $Value + ".txt") }
default { $VarValues += $Key + "#" + $Value }
}
}
Get-Telnet -RemoteHost $HostName -Login $login -PassWord $password -Commands $Script -Vars $VarValues
}
That seems to do the trick and the idea to use switch makes things even easier.
Something might be off with the W2K itself - as soon as the pipe is gone - all goes well.
I have a powershell script that parses a lotus notes INI file and replaces text inside the file. But only the replaced text is showing up in the output file.
# Example of PowerShell -replace parameter
## Get-DistinguishedName -- look up a DN from a user's (login) name
function Get-DistinguishedName {
Param($UserName)
$ads = New-Object System.DirectoryServices.DirectorySearcher([ADSI]'')
$ads.filter = "(&(objectClass=Person)(samAccountName=$UserName))"
$s = $ads.FindOne()
return $s.GetDirectoryEntry().DistinguishedName
}
clear-Host
set-executionpolicy remotesigned
$original_file = '.\notes.ini'
$destination_file = '.\notes2.ini'
$OS = Get-WmiObject -Class win32_OperatingSystem -namespace "root\CIMV2" -ComputerName .
$username = [Environment]::UserName
$userprofile = $env:userprofile
$fullname = Get-DistinguishedName($username) | %{$data = $_.split(","); $data[0].Substring(3)}
write-Host "Creating $userprofile"
if (($OS.Version -eq "5.1.2600") -or ($OS.Version -eq "5.2.3790")) {
$lookupTable = #{
'^SU_FILE_CLEANUP=' = 'SU_FILE_CLEANUP=' + $userprofile + '\Local Settongs\Application Data\smkits'
'%username%' = $username
'%fullname%' = $fullname
'%userprofile%' = $userprofile
'^Directory=' = 'Directory=' + $userprofile + '\Local Settongs\Application Data\Lotus\Notes\Data'}
} else {
$lookupTable = #{
'SU_FILE_CLEANUP=' = 'SU_FILE_CLEANUP=' + $userprofile + '\AppData\Roaming\smkits'
'%username%' = $username
'%fullname%' = $fullname
'%userprofile%' = $userprofile
'Directory=' = 'Directory=' + $userprofile + '\AppData\Local\Lotus\Notes\Data'}
}
Get-Content -Path $original_file | ForEach-Object {
$line = $_
$lookupTable.GetEnumerator() | ForEach-Object {
if ($line -match $_.Key)
{
$line -replace $_.Key, $_.Value
#break
}
}
write-Host $line
} | Set-Content -Path $destination_file
What am I missing
On this line, you are writing he output of the replace operator onto the pipeline, this will then get picked up by Set-Content
$line -replace $_.Key, $_.Value
whereas on this line, you are writing the output to the host (i.e. the powershell console) it will not end up on the pipeline and will not get picked up up Set-Content:
write-Host $line
To fix this, just replace write-host with write-output:
Write-Output $line