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

Deny this user permissions to logon to Remote Desktop Session Host Server

$
0
0

ow can we enable or disable 'Deny this user permissions to logon to Remote Desktop Session Host Server' for bulk users from Remote Desktop Services Profile tab in Active Directory. Also, how do we generate report of users who has this option enabled or disabled? This is urgent!!

Is there any PS1 command which can be used to generate a report of users who has this option enabled in their properties and then using another command disabled those users? DCs are with 2008R2,2012 and 2012R2..


Populate IP Phone field in AD based on entries in a csv file

$
0
0

Hi,

Is there a way to populate the IP Phone field in AD based on a csv?

I tried the following link but no luck: http://en.community.dell.com/techcenter/powergui/f/4834/t/19569423

Thanks in advance,

Johnross

Scheduled Task only fails to print when user not logged in

$
0
0
   

Setting the stage:
I am trying to print pdf reports to a networked printer from a scheduled task at 6am daily.  I have a Powershell 2.0 script on WIndows 2008 R2 that checks for a trigger file with a path to the folder the pdf reports are in and then iterates over the files looking for 3 specific files to print and then prints them to the default printer which is an installed network printer.  This task is set to run "whether the user is logged in or not" and is set "to run with the highest privileges".  It is set to run under a service account with admin access that was also the user that installed the printer.  The code used to print to the default printer is:

Start-Process -FilePath "$archivePath\$($pdf.Name)" -Verb Print  

The Problem:
The issue I am having is that the process only actually prints if the user is logged into the server.  Everything else works, the logging the opening of the pdf in adobe reader, everything.  It just will not send the report to the printer.  If I log in at 5:55am and watch the process and the print spooler I can see everything work, however if I log in at 6:01am I can see the processes running in task manager and track the log but the reports never get sent to the printer.
What I have tried:
I have tried to run this from a bat script that self elevated the powershell in the hopes it was a permission issue using:

SET PowerShellScriptPath=D:\Scripts\Print_HFM_Reports.ps1START /WAIT PowerShell -NoProfile -ExecutionPolicy Bypass -Command "& {Start-Process PowerShell -ArgumentList '-NoProfile -ExecutionPolicy Bypass -File "%PowerShellScriptPath%"' -Verb RunAs}";

I am not sure what else to check or change.  I am not getting any errors in the event viewer or anywhere else.  The Print just doesn't work and right now my only option is to get up at 5:45 and log in.

Acces Denied when running set-aduser and delegated rights

$
0
0

Hi,

when a user with delegated rights run a script to change an specific field he gets the message access denied.

If he changes the value over the ADUC snapin, he can change the field where he has the rights.  

if ($objext2txtbox.text -ne "") {set-aduser -Identity $user.DistinguishedName[0] -Replace @{employeeNumber=@($objext2txtbox.text)}} else {$user.employeeNumber.clear()}

Above the codesnip where the change will be set. If the complete code is required i can post that one too.

Best regards

Malte

How to read file attributes while looping thru list of files ?

Active Directory Module for Windows PowerShell question

$
0
0

Hi PowerShell Community,

I'm playing with the Active Directory cmdlets and, so far, I can't find a way to get a collection of users or add to a collection of users with get-aduser. For example, is there a way to get a group of users in a variable and the use add-adgroupmember and use that collection as an argument to the -members parameter?

I'm probably going about it wrong, but I just thought I'd ask...

Thanks!

Show Objects from Get-Contect in output.

$
0
0

This is my current script

Get-Content c:\vendorgroups.txt | Foreach-Object {Get-ADGroup $_ | Get-ADGroupMember | Where-Object {$_.objectClass -eq "user"} | Get-ADUser -Properties SN,GivenName,Mail,AccountExpirationDate,Description | Select-Object SN,GivenName,Mail,AccountExpirationDate,Description | Export-Csv -Append c:\1.csv}

Is there a way that the vendorgroups can be shown in the exported csv file with the corresponding users under each?

Currently it only shows the users.

Any help is appreciated.

-Justin

Script taking a LONG time to run

$
0
0

I wrote a script that find all the user accounts that have an email address and adds the samaccountname of that account to a variable.  I then use a foreach to run a get-mailbox, get-recipient, get-mailboxstatistics, and get-mailboxdatabase for each samaccount generated in the previous step.  Using an open ended array and new-object psobject, I generate a spreadsheet with all the data  I am looking for.  

My question is why does this script take so long to run?  I expected it to take a while, but its been about 30 minutes and it is only to the c's.  

here is the script.  i am wondering if there is a better or faster way to accomplish what I am doing here:

<#

.SYNOPSIS
    Lists all users with email and thier size restrictions

.DESCRIPTION
    Creates an Excel report of all users with email and thier size restrictions

.NOTES
    Requires Active Directory Rights
    Requires Exchange Console Installed

    File Name  : EmailSizeRestrictions.ps1
    Author     : Matt Dillon
    Date       : 4/9/2015
    Module     : activedirectory, exchange

#>

# import Exchange 2010 modules
Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010

# import activedirectory module
import-module activedirectory

# get list of ALL user accounts with email
$CSVReport = "network location\MailQuotas2.csv"
# remove -and mdillon@williamblair.com
$Mailboxes = (Get-ADUser -Properties * -Filter * | Where-Object {$_.EmailAddress -ne $null} | Sort-Object Name | Select-Object -ExpandProperty samaccountname)
$MailboxObject =@()

foreach($mailbox in $Mailboxes)
        {
        $mbx = Get-Mailbox $Mailbox
        $recipient = Get-Recipient $mailbox
        $mbxstats = Get-MailboxStatistics $mailbox
        $database = Get-MailboxDatabase $mbx.Database

        if ($($mbx.UseDatabaseQuotaDefaults) -eq $true)
            {
            Write-Host $mbx.name
            $MailboxObject+= New-Object PSObject -Property @{'Name'=$mbx.Name;'Department'=$recipient.Department;`
                                                            'StorageLimitStatus'=$mbxstats.StorageLimitStatus;`
                                                                'Database'=$mbx.Database;'UsesDatabaseQuotaDefaults'=$mbx.UseDatabaseQuotaDefaults;`
                                                                    'WarningQuota'=$database.IssueWarningQuota;'SendQuota'=$database.ProhibitSendQuota;`
                                                                        'SendReceiveQuota'= $database.ProhibitSendReceiveQuota}

            $MailboxObject | Select-Object Name,Department,StorageLimitStatus,Database,UsesDatabaseQuotaDefaults,WarningQuota,SendQuota,SendReceiveQuota | Export-Csv $CSVReport -NoTypeInformation
            }

        else

            {
            Write-Host $mbx.name
            $MailboxObject+= New-Object PSObject -Property @{'Name'=$mbx.Name;'Department'=$recipient.Department;`
                                                            'StorageLimitStatus'=$mbxstats.StorageLimitStatus;`
                                                                'Database'=$mbx.Database;'UsesDatabaseQuotaDefaults'=$mbx.UseDatabaseQuotaDefaults;`
                                                                    'WarningQuota'=$database.IssueWarningQuota;'SendQuota'=$database.ProhibitSendQuota;`
                                                                        'SendReceiveQuota'= $database.ProhibitSendReceiveQuota}

            $MailboxObject | Select-Object Name,Department,StorageLimitStatus,Database,UsesDatabaseQuotaDefaults,WarningQuota,SendQuota,SendReceiveQuota | Export-Csv $CSVReport -NoTypeInformation
            }

        }

Thanks in advance.  


Matt Dillon


Using "Schedule.Service API" with RegisterTaskDefinition

$
0
0

I'm needing to automate numerous tasks, one of which is a scheduled task that runs indefinitely.  I want to be able to stop and start the scheduled task via powershell.  To do so it is my understanding the job must be registered via powershell. There are parameters that I need to set where I need to use the "Schedule.Service API".  I'm close to having a working solution but need some help in setting the "RegisterTaskDefinition" which is the last line in the script below. 

Can anyone give me some counsel on setting this correctly?


# http://www.verboon.info/2013/12/powershell-creating-scheduled-tasks-with-powershell-version-3/
# https://msdn.microsoft.com/en-us/library/windows/desktop/aa382577(v=vs.85).aspx

$UserAcct = "Domain\acctname"
$UserPass = ConvertTo-SecureString "somepass" -AsPlainText -Force
$UserCred = New-Object System.Management.Automation.PSCredential($UserAcct, $UserPass)

# The name of the scheduled task
$TaskName = "MyScheduledTask"
# The description of the task
$TaskDescr = "Run a powershell script through a scheduled task"
# The Task Action command
$TaskCommand = "c:\windows\system32\WindowsPowerShell\v1.0\powershell.exe"
# The script to be executed
$TaskScript = "D:\MySQLAdmin\Scripts\MySQLFailoverService.cmd"
# The Task Action command argument
$TaskArg = "-NonInteractive -Executionpolicy unrestricted -file $TaskScript"

# The time when the task starts, for demonstration purposes we run it 1 minute after we created the task
$TaskStartTime = [datetime]::Now.AddMinutes(5) 

# attach the Task Scheduler com object
$ScheduleObject = new-object -ComObject("Schedule.Service")
# connect to the local machine. 
$ScheduleObject.Connect()
$rootFolder = $ScheduleObject.GetFolder("\")

$TaskDefinition = $ScheduleObject.NewTask(0) 
$TaskDefinition.RegistrationInfo.Description = "$TaskDescr"
$TaskDefinition.RegistrationInfo.Author = "My Name"
#$TaskDefinition.Principle.RunLevel = $true
$TaskDefinition.Settings.Enabled = $true
$TaskDefinition.Settings.AllowDemandStart = $true
$TaskDefinition.Settings.DisallowStartIfOnBatteries = $false
$TaskDefinition.Settings.ExecutionTimeLimit = "PT0S"  # See Note Below

$triggers = $TaskDefinition.Triggers
$trigger = $triggers.Create(8) # Creates a "At System Startup" trigger
$trigger.StartBoundary = $TaskStartTime.ToString("yyyy-MM-dd'T'HH:mm:ss")
$trigger.Enabled = $true

$Action = $TaskDefinition.Actions.Create(0)
$action.Path = "$TaskCommand"
$action.Arguments = "$TaskArg"

$rootFolder.RegisterTaskDefinition($TaskName,$TaskDefinition,6,$UserAcct,$UserPass,1)

     

Search *.config files for token

$
0
0

I would like to run a powershell script that will search all *.config files in a specified directory for a specified token. The script will then list the files/hits and write an error to console if any hits were found.

I have this so far but not sure how to test for hit existence.

get-childitem $dir -include *.config -rec | select-string -pattern "#{"

How do you capture the file names / hits and list them?

Please tell me everything wrong with this simple script

$
0
0

So no matter what i try this fails on me:

$computer = Get-Content -path "c:\scripts\machines.txt";
Get-EventLog -Newest 4 -LogName System -ComputerName $computer -source EventLog  | where {$_.eventID -eq 6013
} | Export-Csv -path c:\scripts\uptime.csv

it tells me 

Get-EventLog : Cannot validate argument on parameter 'ComputerName'. The argument is null or empty. Supply 
an argument that is not null or empty and then try the command again.
At line:2 char:54
+ Get-EventLog -Newest 4 -LogName System -ComputerName $computer -source EventLog  ...
+                                                      ~~~~~~~~~
    + CategoryInfo          : InvalidData: (:) [Get-EventLog], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.PowerShell.Commands.GetEventLogComm 
   and

If I execute Get-Content on $computer by itself i get a list of machines.  Also I'm guessing I will run into problems with this when a machines is offline, how can i get around that problem?

Thanks,

Scott


How to sent a message or notification to PCs on LAN using Powershell

$
0
0
i want to sent a message to list of PCs on LAN, how to do that, thanhk u

verifying that user specified output file is in a valid folder path

$
0
0

I'm trying to write a validation script to ensure that the output file specified by the user is in a folder path that actually exists. This is the approach I have been working on and the error message:

PowerCLI g:\> Split-Path "c:\output.log" -Parent | Test-Path  -Path $_ -PathType 'Container'
Test-Path : Cannot bind argument to parameter 'Path' because it is null.
At line:1 char:49
+ Split-Path "c:\output.log" -Parent | Test-Path  $_ -PathType 'Container'
+                                                 ~~
    + CategoryInfo          : InvalidData: (:) [Test-Path], ParameterBindingValidationException
    + FullyQualifiedErrorId : ParameterArgumentValidationErrorNullNotAllowed,Microsoft.PowerShell.Commands.TestPathCommand

remote Command prompt

$
0
0

Hi All,

Is it possible to get remote servers command prompt using power shell 

Verify if a Registry Key exists on Remote Machines

$
0
0
I am looking for a simple script to check if a registry key exists on remote machines. I have the code to perform an action based on a list of machines (Which has been done and published hundreds of times). What I am looking for now is a way to check the existance of a key on a remote machine.
http://www.virtualrealm.com.au - XNA Game Programming News and Resources from Downunder.

Help to change registry "REG_DWORD" value

$
0
0

Hello,

I'm wanting to turn off (un-tick) the "Send Authentication trap" setting on the "Security" tab of the SNMP Services using PowerShell on a remote server. The registry "REG_DWORD" is called "EnbledAuthenticationTraps" and resides directly under the $SubKey and needs to be set to "0" instead of "1"

$server = "SRV01"

$BaseKey = [Microsoft.Win32.RegistryKey]::OpenRemoteBaseKey(‘LocalMachine’, $server)
$SubKey= $BaseKey.OpenSubKey("SYSTEM\\CurrentControlSet\\Services\\SNMP\Parameters",$true)

Can someone assist?

Thank you

 

SOLVED: powershell script working on its own, access denied when called from a service

$
0
0

Hi powershell experts,

I'm using a powershell script, called by a service with serviceaccount PWSService, which gives an exception denied. This powershell script sets up a remote powershell connection(with a specific account), and runs some powershell scripts remotely on that server. 

When I launch the powershell script manually, by opening the powershell console myself(with "run as" PWSService), the remote session starts and I'm able to succesfully run commands through it.

The PWSService is local admin on the server.

Is there any diffrence in behaviour when powershell scripts are started by a service or started as a "user"? Can someone shed a light on this?

Thanks in advance,

Robin


MCTS, MCPD


String formatting with Write-Output

$
0
0

I have a FileInfo object that I want to print the full file name member value.

I tried this:

Write-Output "Scanning $file.FullName..."   

However that just prints out:

"Scanning c:\foo.txt.FullName..."

What is the proper way to format the FileInfo.FullName using Write-Output (In C#, I would use String.Format)?

thanks

Changing a screenshot to JPG instead of PNG

$
0
0

I've got a script that works that runs on a scheduled task to snapshot the screen of a computer.  Basically the computer runs a query at a regular interval that is pretty resource intensive on the server but has information that anyone might want to see at a given time.  So rather than having them generate the data on the fly, they get a html page that displays the screenshot of the last result set. The script is based on another one that I found online.  Right now it saves in PNG format and is about 1.8MB.  I'm trying to get it to save in .JPG format so it is smaller.  

This works:

$ScreenshotObject.Save($FilePath)

However this does not:

$ScreenshotObject.Save($JpgOut, Drawing.Imaging.ImageFormat.Jpeg))

I'm about 90% sure my problem lies in the Drawing.Imaging.ImageFormat.Jpeg part.  I guess I'm not sure what the correct parameter is since there seem to be many things that can end in .ImageFormat.Jpeg.  I've tried Drawing.Bitmap.ImageFormat.Jpeg. I've tried with System at the beginning. I've also tried Drawing.Grapics.ImageFormat.Jpeg

I've also tried several variations on New-Object and various ways of trying to save it.

I guess I just can't figure out which is the right way.

The errors vary from Cannot find Type, or complaining that I passed a null value.

$ImageFormat = New-Object [Drawing.Imaging.ImageFormat]::Jpeg
$ImageFormat = New-Object [Drawing.Imaging]::ImageFormat.Jpeg
$ImageFormat = New-Object [Drawing.Imaging]::ImageFormat

$ScreenshotObject.Save("C:\Screenshot\Current.Jpg",$ImageFormat.Jpeg)

$ScreenshotObject.Save("C:\Screenshot\Current.Jpg",$ImageFormat)
And I've tried with and without:
Add-Type -Assembly System.Drawing.Imaging

Here's the full script.  I've alternated between commenting out the first save and uncommenting the second.

Again, just saving it with a default path outputs it in PNG format and works.  It's just 1.8MB is a lot to put in a web page the that keeps refreshing.

$Path = "c:\Screenshot"
$Current = "Current.Png"
$CurrentJpg = "Current.Jpg"
$JpgOut = (Join-Path $Path $CurrentJpg)

Function GenScreenshot
	{
		$ScreenBounds = [Windows.Forms.SystemInformation]::VirtualScreen
		$ScreenshotObject = New-Object Drawing.Bitmap $ScreenBounds.Width, $ScreenBounds.Height
		$DrawingGraphics = [Drawing.Graphics]::FromImage($ScreenshotObject)
		$DrawingGraphics.CopyFromScreen( $ScreenBounds.Location, [Drawing.Point]::Empty, $ScreenBounds.Size)
		$DrawingGraphics.Dispose()
		$ScreenshotObject.Save($FilePath)
		#$ScreenshotObject.Save("C:\Screenshot\Current.Jpg", Drawing.Imaging.ImageFormat.Jpeg))
		$ScreenshotObject.Dispose()
	}
	Add-Type -Assembly System.Windows.Forms
	$Time = (Get-Date)

	[string] $FileName = "$($Env:ComputerName)"
	$FileName += '-'
	$FileName += "$($Time.Hour)"
	$FileName += '-'
	$FileName += "$($Time.Minute)"
	$FileName += '.png'

	[string] $FilePath = (Join-Path $Path $FileName)
	{
		Remove-Item $FilePath
	}
	GenScreenshot
	Copy-Item $FilePath -destination (Join-Path $Path $Current)	


Issue using Get-Child-Item

$
0
0

Have a function that will scan (grep) files in a folder with a certain extension.  For some reason, Get-Child-Item always returns empty / 0 files on my folder even though you can look at the folder and see files of the specified extension (*.config). Suspect either I am doing something wrong or permissions are somehow getting in the way.  How do you properly use Get-ChildItem in this context?

function scan-Files { param( [parameter(mandatory=$True)] [string]$folder, [parameter(mandatory=$True)] [string]$filePattern, [parameter(mandatory=$False)] [bool]$recurse = $False ) Write-Host "Folder = $folder" Write-Host "FilePattern = $filePattern" $files = Get-ChildItem -Include $filePattern -Path $folder

#always empty for some reason if ($files) { Write-Host "File count = $($files.Length)" }

.

.

.

#Invoke our function

$folder = "C:\Program Files\Microsoft SQL Server\MSRS12.MSSQLSERVER\Reporting Services\ReportServer\"
$filePattern = "*.config"         

#scan-Files -folder $folder -filePattern $filePattern -recurse:$true
scan-Files -folder $folder -filePattern $filePattern



Viewing all 21975 articles
Browse latest View live


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