Quantcast
Channel: PowerShell.com – PowerShell Scripts, Tips, Forums, and Resources
Viewing all 6937 articles
Browse latest View live

Restricting access to cmdlets and parameters

$
0
0

Hello, can someone please help with the following.

I know with PS Remoting and PSConfig file you can restrict which cmdlets and which parameters on those cmdlets a given user can execute. However I understand this relies on the fact the user in question if using PSRemoting

Lets say I have a PowerShell module (any module) on my Local PC and the module has a number of cmdlets that let you run its commands against a remote computer. Now if possible I want to restrict which cmdlet and which parameters from that module a given user can execute (in the same way as using PSConfig) but without using PSRemoting. e.g. running cmdlets locally on PC.

Thanks

AAnotherUser

 


HTML Table colour seperation advice

$
0
0

Hi All

This is a script to find if an email address is valid or not and also if it is valid produce some information. This is outputed to 2 Csv files  


This part of the code creates two tables in html one for valid address and one for invalid address and exports to html file, this works fine.

My query is these tables are the same colour. How can i change the layout colours for each table so they are different but stillsent the output to one html file.

 
 
$("<span style=""color:Red"">      Address NOT VALID </span><br><br>")
$($errorList | ConvertTo-Html -Fragment)
$("<span style=""color:Red""> </span><br><br>")
 
$("<span style=""color:blue"">     Address Valid </span><br><br>")
$($validUsers | ConvertTo-Html -Fragment)



*****
userlist = Get-Content "c:\userlist.txt"
 
foreach ($user in $userlist)
{
    $error.Clear()
    $validUser = Get-Recipient $user | Select-Object Displayname, Database, PrimarySmtpAddress,name,RecipientType,DistinguishedName
    if (@($error).Count -gt 0)
    {
        $userData = @{"Invalid Address"=$user}   
        New-Object -TypeName PSObject -Property $userData -OutVariable invalidUser | Out-Null
        $errorlist += $invalidUser
        $error.Clear()
    }
    else
    {
        $validUsers += $validUser
    }
}
 
if (($errorList | Measure-Object).Count -gt 0)
 
{
$errorList | export-csv "$reportcsvEmailaddexistsnot" -NoTypeInformation
}
$validUsers | Export-Csv "$reportcsvEmailaddexists" -NoTypeInformation
 
$Report =
@"
<!DOCTYPE HTML>
<html>
<Head>
<style>
table, th, td {
font-family: calibri,arial,verdana;
color: white;
border: 2px solid white;
border-collapse: collapse;
background-color: #66CCFF;
}
</style>
</head>
 
$("<span style=""color:Red"">      Email does Exist</span><br><br>")
$($errorList | ConvertTo-Html -Fragment)
$("<span style=""color:Red""> </span><br><br>")
 
$("<span style=""color:blue"">     Email ADDRESS DOES Exist</span><br><br>")
$($validUsers | ConvertTo-Html -Fragment)
 
 
</body>
</html>
 
"@
 
$report | out-file c:\report.html

permission powershell remoting

$
0
0

How can i set permission for powershell remoting without the UI?

PowerShell GUI Problems - MultiThreading & Freezing GUI

$
0
0

Hi,

When i run my powershell script (its has GUI) the form freez and do you have any idea how i can avoid it?

I have added [System.Windows.Forms.Application]::DoEvents() but it still not working. 

 

Please help :-)

try
	{[System.Windows.Forms.Application]::DoEvents()$buttonStart.Enabled = $false$buttonStop.Enabled = $false$buttonRefresh.Enabled = $false$LabelStatus.Text = ""$richtextboxInfo.Text = ""$WebEsServices1 = List-Services
		Load-DataGridView -DataGridView $datagridview1 -Item $WebEsServices1$MemWMI = Get-WmiObject -Class Win32_Operatingsystem -ComputerName $global:Servername -Credential $Global:Credential$TotalMemory = [Math]::Round($MemWMI.totalVisibleMemorySize / 1mb, 2)$RemMemory = [Math]::Round(($TotalMemory - 4) * 1GB / 1MB, 2)#$FreeMemory = [Math]::Round($MemWMI.FreePhysicalMemory / 1mb, 2)$richtextboxInfo.AppendText("Total Memory: $TotalMemory GB`n")$richtextboxInfo.AppendText("`n")$Pro = Invoke-Command -ComputerName $global:Servername -Credential $Global:Credential -ScriptBlock { Get-Process -Name Java* -ErrorAction 'Stop' }$TotalJavaMem = 0foreach ($itemin$Pro)
		{[System.Windows.Forms.Application]::DoEvents()$Storlek = [Math]::Round($item.workingset64 / 1mb)$richtextboxInfo.AppendText("$($item.ProcessName): $Storlek MB`n")$TotalJavaMem += $Storlek
		}$RemainingTotalJavaMem = [Math]::Round(($RemMemory - $TotalJavaMem))$richtextboxInfo.AppendText("`n")$richtextboxInfo.AppendText("Used Memory: $TotalJavaMem MB")$richtextboxInfo.AppendText("`n")$richtextboxInfo.AppendText("Remaining Memory: $RemainingTotalJavaMem MB")if ($RemainingTotalJavaMem -le 0)
		{$LabelStatus.ForeColor = 'Red'$LabelStatus.Text = "Not OK"
		}else
		{$LabelStatus.ForeColor = 'Green'$LabelStatus.Text = "OK"
		}
	}catch[System.Net.WebException], [System.Exception]
	{$ErrorMSg = $_.Exception.Message#[void][reflection.assembly]::Load("System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")[void][System.Windows.Forms.MessageBox]::Show("$ErrorMsg", "Error!")
	}$buttonStart.Enabled = $true$buttonStop.Enabled = $true$buttonRefresh.Enabled = $true

Parsing specific groups and outputting select attributes

$
0
0

Hi all,

Still trying to get my feet wet with PS.  Have a need to search AD for any groups with a specific term in the group name then return the users of those groups as well as if the accounts are enabled.  I know there are always multiple ways of solving a problem with scripting so I'm looking for guidance on how make my script more efficient as well as acheive what I'm trying to do.  So my initial script is below:

######## Function to find groups with the word Admin in it #####
Function GRPWITHADMIN
{
 $ADMGROUPS = get-adgroup -filter {Name -like "*Admin*"} | sort | Select Name
}

############## Function to Expand Group Membership #############
Function GMEMExpanded
{
 $colMembers=GRPWITHADMIN
 Foreach ($colMember in $colMembers)
 {
  $objUName = get-aduser $colMember | select Name
  $objEnabledStatus = get-aduser $colMember | select Enabled
 }
$colMembersExpanded
}
############################### MAIN ###########################
$SelGroups = GRPWITHADMIN
Foreach ($SelGroup in $SelGroups)
{
   Write-Host ""
  Write-Host "Enumerating $SelGroup.." -foregroundColor yellow
   $colMembersExpanded = @()
    $members = GMEMExpanded $SelGroup
   ForEach ($user in $members)
    {
    $user.Name
    "Status: "$user.Enabled
    }
}
$colMembersExpanded | Export-CSV ".\AllAdminUsers.csv"

 

Obviously the script is not complete.  I stopped at the end when cycling through the members where I realized that I don't have an easy way to pull the user attribute without some how loading it/tying it to the user.  The ForEach $user array, i'm trying to use $user.Name when, looking at it, there is now way the "Name" AD attribute is defined anywhere so that call is useless as far as the script goes.   I guess this is where my lack of knowledge comes in.

So my ultimate outcome would be to query AD with any group with the string "Admin" in it.  Take those groups, enumerate the users and then output the results to something like:

Group Name: WebAdmins
User: jsmith_admin; Enabled: True
User: psmith_admin1; Enabled: False

Group Name: DBAdmins
User: mchen.admin; Enabled: True

etc....

Thanks in advance for the guidance.

Mods: Please delete this thread

$
0
0

Mods, please delete this thread...wrong forum

Getting different results from code

$
0
0

Both of the follow scripts work.   Script 1 will show me machines that are online in GREEN and it will show me the machines that can't ping in ORANGE.  (why orange I don't know since I did not say too)  But Script 2 only returns the machines that it can ping.  if it can't ping then it does not show me that machine in the output.   Script 1 returns 25 total machines, Script 2 returns only 22 machines (3 are off line).  In Script 2 I have tried moving my closing bracket '}' to re position the ELSE and it still does not give the desired output.   What am I missing here?

 

# script 1 ##################################

$PCName = (Get-ADComputer -Filter * -SearchBase "OU=1200 Baker,OU=CorpWorkstations,dc=Acme,dc=org").Name

foreach ($machine in $PCName) {if (test-Connection -ComputerName $machine -Count 2 -Quiet ) {write-Host "$machine is alive and Pinging " -ForegroundColor Green}  else{ Write-Warning "$machine seems dead not pinging"}}

# Script 2   ##################################

$PCName = (Get-ADComputer -Filter * -SearchBase "OU=1200 Baker,OU=CorpWorkstations,dc=Acme,dc=org").Name 

foreach($machine in $PCName) {if (test-Connection -ComputerName $machine -Count 2 -Quiet )                                 { Get-WmiObject win32_operatingsystem  -ComputerName $machine | select csname, @{LABEL='LastBootUpTime' ;EXPRESSION={$_.ConverttoDateTime($_.lastbootuptime)}}}

                             else { Write-Warning "$machine seems dead not pinging" -ForegroundColor Green}}

Problem forking a loop

$
0
0
Hi all, I wrote a script to do a one-off check against a remote machine if a specific kb is installed. I want it to loop if response to a read-host is either y or s. choosing "y" works as expected but if I choose s i run into an issue with it returning to the beginning but falling outside the loop. Below is my code. If you read through it, you will see what i'm trying to do. I commented out the actions if "s" is selected because i'm thinking i'm constructing my functions/loop wrong or missing something. Any suggestions would be appreciated. Thanks.
# This script will check if a particular hotfix is installed on the remote system.
# Usage: checkhotfix.ps1

cls
Write-Host"~~~~~~~~ Remote Hotfix Check ~~~~~~~"-foregroundcolor Cyan
#Function to obtain computername and check if host is online
Function KBCHECK
{
$objCom=Read-Host'Enter the remote computer name'
If (test-connection-computername$objCom-Quiet)
{
SAMECHECK
}
Else{
Write-Host$objCom"is Offline"-foregroundcolor Red
}
}
#Function to do the actual checking of the KB. When prompted for hotfix, enter only the KB number without the "KB"
Function SAMECHECK
{
$KB=Read-Host'Enter the KB to check. Enter just the number without the "KB"'
$KB="KB"+$KB
Write-Host"Thank you. Checking if patch is installed..."-foregroundcolor Cyan
If ($Patch=Get-Hotfix-computername$objCom | Select HotfixID,Description,InstalledOn | sort InstalledOn | ?{$_.HotfixID-eq$KB})
{
Write-Host"Patch is installed"-ForegroundColor Green
$Patch
Write-Host"Done."-ForegroundColor Cyan
}
Else{
Write-Host"This patch KB"$KB" is not installed on the remote machine or is not applicable"-ForegroundColor Red
}
}
# Loop while responding yes or same
Do
{
KBCHECK
$response=Read-Host"Check another computer? Enter ,, or for the same computer"
}
while ($response-eq"y")
######ElseIf ($response -eq "s")
######{
######}
EXIT

Using -Not with If

$
0
0

I have some code that is checking an HL7-type file for certain segments.  I read chunks of the file into a byte array.  The objective here is to validate that some specific segments exist in the file.

First I need to verify there are header and trailer records:

If ($bytes -match 'HDR|' -And $bytes -match 'TRL|')

If it passes that test, I then need to verify another pair of segments.  The issue here is that if they exist, I don't need to do anything, but if either or both of them do not exist, set a flag.  I can't figure out the correct format for using -Not.  I have tried every combination of parenthesis around these, but its not working.  Here's the current attempt:

If (-Not ($bytes -match 'CHD|' -And $bytes -match 'CTR|')) {$BadFile = $true}

Of course, I could write it this way, but as I said, if this evaluates as true, there's nothing to do:

If ($bytes -match 'CHD|' -And $bytes -match 'CTR|') {nothing to do}
Else {$BadFile = $true}

What am I missing with using -Not?

Help Creating Powershell Password Reset Utility

$
0
0

Hi All,

 

Hoping to get some help on this AD Password Reset utility. I'm building a form using .Net objects but when I execute the script it runs the set-adaccountpassword cmdlet before I have a chance to select variable values for password and Username from dropdown. I cant seem to get the execution order of the code correct. Please Help! 

CODE:

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")

[void] [System.Reflection.Assembly]::LoadWithPartialName('Microsoft.Visualbasic')  

 

$Form = New-Object System.Windows.Forms.Form    

$Form.Size = New-Object System.Drawing.Size(600,275)

$form.Name="UCEDC Password Reset"  

$form.BackColor="lightGreen"

$form.Text="Company Password Reset Utility"

 

 

 

############################################## Start functions

 

 

 

#$computer=$DropDownBox.SelectedItem.ToString() #populate the var with the value you selected

 

 

############################################## end functions

 

############################################## Start drop down boxes

 

$DropDownBox = New-Object System.Windows.Forms.ComboBox

$DropDownBox.Location = New-Object System.Drawing.Size(20,50) 

$DropDownBox.Size = New-Object System.Drawing.Size(180,20) 

$DropDownBox.DropDownHeight = 200 

$Form.Controls.Add($DropDownBox) 

 

$wksList=@(get-aduser -filter *| select-object -ExpandProperty samaccountname)

 

foreach ($wks in $wksList) {

                      $DropDownBox.Items.Add($wks)

                              } #end foreach

$passworchange=$DropDownBox.SelectedItem

 

 

############################################## end drop down boxes

 

 

 

$Button = New-Object System.Windows.Forms.Button 

$Button.Location = New-Object System.Drawing.Size(400,30) 

$Button.Size = New-Object System.Drawing.Size(110,80) 

$Button.Text = "Reset Password"

 

 

$button.add_click({[Microsoft.VisualBasic.interaction]::inputbox("Enter a Password","Password",$passworchange) })

 

##$Button.Add_Click({procInfo})

 

$Form.Controls.Add($Button) 

 

 

 

Set-ADAccountPassword -Identity $username -NewPassword $passworchange

 

 

 

 

 

 

############################################## Start text fields

 

$outputBox = New-Object System.Windows.Forms.TextBox 

$outputBox.Location = New-Object System.Drawing.Size(10,150) 

$outputBox.Size = New-Object System.Drawing.Size(565,200) 

$outputBox.MultiLine = $True 

$outputBox.ScrollBars = "Vertical" 

$outputBox.text= $passworchange

$Form.Controls.Add($outputBox) 

 

############################################## end text fields

 

############################################## Start buttons

 

 

############################################## end buttons

 

$Form.Add_Shown({$Form.Activate()})

[void] $Form.ShowDialog()

String Question

$
0
0

Is it possible to list multiple system under a -identity parameter on one line, without using a txt file? I am trying to write a script with a set number of computer the will be check everytime the script is ran. So there will be no external file. Below is the script, but I just cant figure out the multiple system part

$Option = Read-Host 'which network loaners would you like to check? (skyzone or homezone)'

if ($Option -eq "skyzone") { ForEach-Object {Get-ADComputer -Identity {sys1,sys2,sys3} -Properties Name,Description,LastLogonDate | Select-Object Name,Description,LastLogonDate} }

Else{"Exiting Program do come again"}

Calling script with &

$
0
0

I have this code that works fine. 

$call1 = "\\server\scripts\MyUtility.exe"

&$call1

The issue I have is when the .exe is called a CMD window pops up for a brief moment. It is calling PowerShell.exe based on the CMD window title.  Is there anyway to suppress this window when calling with the & character?

 

What's the difference between remote access and 'remoting'

$
0
0

Hi - I am new to Powershell (I am using v3.0 ISE, running as Administrator, in W7 environment), but not to scripting in general.  I have also been a c# programmer in a past life, so am reasonably comfortable with Object-Oriented principles.

I am initially just trying to access each PC in our office (all on a common domain, and most are on the same subnet).  I have not done anything special on any of the PCs (i.e. I haven't run 'Enable-PSRemoting' on them), and my little script appears to be able to access almost all of them straight away.  Great!!

However, there is at least one PC that my script baulks at, that I know is connected and powered on.  I even went and ran the 'Enable-PSRemoting' cmdlet on it (as local Administrator).  It turns out, this happens to be one of the few PCs on a different subnet - so I suspect that without getting into firewall configuration, there is little I can do about this particular PC.

My main question though is whether there is a subtle difference between accessing a remote computer, and the term 'remoting'...  My script is just doing a simple Test-Path to \\$ComputerName\c$ to check if the computers are reachable, and in most cases, they are.  I can then use 'Set-Location' to navigate around their systems, and even get into their registries and do untold damage ;-)

But, when I have tried the 'Test-WSMan' cmdlet from my PC to these 'accessible' PCs, it returns an error, presumably because the WinRM service is not running at the far end (and the various other things that Enable-PSRemoting turns on for us).  So, even though I can 'access' the computers, what does this lack of 'remoting' mean I can't do.

Given that I can access the computers to some degree, can I emulate running the 'Enable-PSRemoting' on each PC, from my PC, without having to go out and visit each one (which is the whole point of me wanting to learn Powershell in the first place)?

Many thanks

Graham

Trigger when a Folder is opened

$
0
0

Is there a way to trigger an action when a Folder is opened?

Or to find out if a folder is currently opened and trigger an action?

When certain folders are open, I want to launch a companion App that will help me manage the contents of the folder. Maybe offer 3 or 4 actions that I will select from. I want that App to start running when I open that Folder.

Any thoughts?
Paul 

invoke-command on remote computer using New-Object -ComObject Microsoft.Update.Session

$
0
0

Powershell V2.0 on win2003R2 remoting to 2003R2 and 2008R2

I have a script that I wrote that uses the winupdate api to find updates that need to be applied. the script does a search, followed by a download, followed by install.

if I execute the script locally on any computer, all parts of it work fine, but I can't get it to work on a remote system (eventually a set of systems) from a central server.

I would love to know what I am doing wrong, or how I can make it work another way. I have also tried using a pssession with the same result.

I have narrowed the problem down to this section, if executed locally on serverA, it works, but if executed remotely on the same serverA, it returns the error shown

invoke-command -scriptblock {
  $Session = New-Object -ComObject Microsoft.Update.Session
  $Downloader = $Session.CreateUpdateDownloader()
} -credential $cred -cn $sys

Exception calling "CreateUpdateDownloader" with "0" argument(s): "Access is denied. (Exception from HRESULT: 0x800700
05 (E_ACCESSDENIED))"
    + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
    + FullyQualifiedErrorId : ComMethodTargetInvocation

thanks for your assistance. Ole Jensen.


AD search with user input script???

$
0
0

Hi all,

I am new to powershell and was hoping someone could help me out.  I am trying to create a script that will search for user name and phone number in AD.  I was able to get this to work when I specify the user name:

function findNumber
{
 Get-ADUser -filter {name -like 'john*'} -properties ipphone | ft Name, ipphone
}

But when I try to allow for user input it does not return anything, goes back to prompt.

function findNumber ([string]$who)
{
 Get-ADUser -filter {name -like '$who*'} -properties ipphone | ft Name, ipphone
}

also tried this...

function findNumber
{
 $name = Read-Host 'Enter the First Name you would like to search'
 Get-ADUser -filter "name -like '$name'" -properties name, ipphone | ft Name, ipphone
}

Could anyone let me know what I am doing wrong?

PowerShell Problem Solver: Where is that IP?

$
0
0

In a previous PowerShell Problem Solver article, I used PowerShell to convert a ctime value to a proper datetime format. I had a list of IP addresses as part of the same troubleshooting process, and this is something you also might come across in a log file.

Read More

Linux data recovery

$
0
0


Linux is the backbone  of a family of operating systems. In a similar sense, Windows is a family of operating systems (2000, XP, Vista, etc). Some of the most popular operating systems in the Linux family are Ubuntu, Fedora, and Knoppix. In this tutorial we will be using Knoppix to preform the data recovery, but any Linux distribution should work fine. The first step is to download a Linux Live CD. When you turn your computer on your operating system (lets say Windows Vista) is loaded from the harddisk into the ram. When you use a live CD, the operating system is loaded from a CD disk to the ram. The benefit of this is that you do not need to make any changes to the harddisk to run this operating system, every thing is done from the CD. In fact, one can use a live operating system off of a CD even if there isn't a harddisk in the computer! Linux subscribes to the philosophy of open source software, in other words, Linux is completely free. Linux Data Recovery Software easily repairs the corrupt data from Linux (EXT2, EXT3), ReiserFS and JFS partitions. User must attach the corrupt hard disk as the secondary drive and use Linux Data Recovery software. The software then analyzes aforementioned crashed hard drive and searches for required data. After preview, you can save the recovered data to the hard disk and later transfer to the location you wish to keep it in.

User Can Read More:- http://www.pcrecoverytools.com/linux-data-recovery.html

Handling newly presented LUNs and mapping them to all cluster nodes

$
0
0

Hi all.

I have an app that would help me take a snapshot of the production SQL Database and present it to the cluster I choose. What I want to do is to enumerate these disks, and map them to all cluster nodes or make it a cluster resource.

Once that is done, make SQL Server aware of this resource and start using it for attach of presented files on the LUNs.

Not even sure where to begin.

Any help is welcome.

P.S. I am not a power-shell guy. 

Deploy Powershell 3.0 on Windows 7 Computers using Configuration Manager 2012 R2

$
0
0

In order to deploy powershell 3.0 to Windows 7 workstations, the computer that do not have powershell 3.0 need to be identified. 

Read More

Viewing all 6937 articles
Browse latest View live


Latest Images