Quantcast
Channel: Windows PowerShell Forum
Viewing all 2562 articles
Browse latest View live

Powershell script to enable "Connect client printers at logon" and "Default to main client printer" in AD.

$
0
0

I've been searching around and haven't found a solution yet.

Is there a Powershell script that can manipulate the "Client devices" under the Environment tab for all AD users?

I'd like to enable "Connect client printers at logon" and "default to main client printer", and make sure "Connet client drives at logon" is disabled.


Incremental Reading

$
0
0

Hi All,

Suppose i want to create a script so that it reads the email addresses from a from.txt file that contains senders email addresses also it reads email addresses from a to.txt file that contains recipients email addresses and then sends a mail. How do i go about the looping part.

Example.

a@xyz.com , b@xyz.com are the addresses in the from.txt and p@xyz.com , q@xyz.com are the names in the to.txt file . 

The logic is that it should read a@xyz.com from from.txt and p@xyz.com from to.txt file and then send a mail . after that it should read b@xyz.com from from.txt and q@xyz.com and then send a mail so on. 

Renaming Accounts - adding the same letter to every account

$
0
0

Every account that I get from a get-qaduser query, I'd like to rename by adding a z_ to the account name. Can anyone tell me how to do this? Thanks.

How to view running Powershell scripts?

$
0
0

Im troubleshooting a server which is maxed out at 100% CPU. 

I can see there are 20+ Powershll scripts in memory, each consuming about 180 MB all at the top of the CPU utilization list.  All 8 CPU's are maxed at 100 CPU.

I'd like to detremine what scripts are being run\ spawned but have had limited success in determining how to gain visibility of these, other than the genric information provided by Task Manager.  Ive created a Dump File of one of the processes and reviewed it in Visual Studio, but this does not provide any further info about what script is being spawned.

Any thoughts \ suggestions appreciated.

Unix SED command replacement and for loop in Powershell

$
0
0

Hi,

Platform: Win Server 08

Requirement is
InputFile:
File1 Contents:

Row1: Col1_VALUE, Col2_Value, Col3_Value
Row2: Col1_VALUE, Col2_Value, Col3_Value
Row3: Col1_VALUE, Col2_Value, Col3_Value
Row4: Col1_VALUE, Col2_Value, Col3_Value

OutputFile: Loop No of rows in File1 (4)
(
Param1=<Col1_Value in Row1..4>
Param2=<Col2_Value in Row1..4>
Param3=<Col3_Value in Row1..4>
)

Script is to execute an exe file 4 times once for a row in Input file.

 Please let me how i can achieve this. I know how i can do this in Unix. using sed functionality. But dont know how to achieve this in windows. Please help.

Regards
Suresh

Easy one - passing values to a function

$
0
0

I'm trying to write a function that executes a series of commands on a machine. I want the function to accept a list of server names so that it can execute against each server. I'm having issues..

I have a text file C:\serverlist.txt which contains entries as follows

SERVERXXX

SERVERYYY

(and so on...)


The script starts off by reading this text file and storing it in a variable

$servers = (Get-Content -path "C:\serverlist.txt)

Next the function is as follows:

function BLAH ([string[]]$arg)

{

out-file "C:\$arg"

}

I then call the function to execute passing it the server list

BLAH($servers)

My output is one text file called:

SERVERXXX SERVERYYY.txt

This isn't what I want, I want it to create a unique text file for every server defined in the serverlist.txt file

I'm sure its related to how I am passing the data...help!!



Q on remoting

$
0
0

Hi,

This is my set up

  1. All scripts used by system personnel or run by task scheduler are located in one network share.
  2. This share is mapped as drive K: on all my servers and mng stations
  3. winrm is enabled all all servers
  4. I preload a common shell any time ps is opened via profile.ps1; this preloads necessary modulesand  has MANY functions and aliases that are often reused in my scripts.
  5. All my housekeeping scripts, that run by task scheduler, are run from my "management" server.
  6. I am now trying to run (on mng server) a script that uses get-clusteredsharedvolume on a (remote - same domain) HV server (as domain admin). I am usinginvoke-command -filepath k:\monitor.ps1 -computername hvserver and it works fine
  7. BUT the script (like all my scripts relys on a the common shell -see item (2) above) fails because the script does not "see" this common shell.
  8. So i have two questions:
  9. Q1) can i, using invoke-command have the profile.ps1 run before monitor.ps1 so that all functions are available to the script

10. Q2) Can this alternately be done via a remote session and if si can u say how?

Thank u for reading all the way down here :-)

Roy


roys99

Four in a row game in Powershell

$
0
0

Alright, right now I am trying to create a basic four in a row game with a 10x10 board. (Ranging from A to J and 1 to 10.) Now, the goal of the game is to prohibit the player from entering a 'coordinate' that has already been used, and the coordinate can't 'float'.

For example: When the player chooses A9, but A1 to A8 are still empty, the choice can't be there. (As if you drop a coin down the collumn)


What I wanted to ask is, how do I validate that the previous value isn't in use? I was thinking about arrays, but I don't know how to make that work.

This is the code I wrote to validat the coordinate:

Function Validate-Move{

do{
    do {        
        $script:coordinateLetter = Read-host "Please enter a letter from A to J" 
        if($script:coordinateLetter.Length -gt 1){}
       } 
    while ($script:coordinateLetter.Length -gt 1)
  }
until($script:coordinateLetter -cmatch "[A-J]")

do{
  $script:coordinateNumber = Read-host "Please enter a number from 1 to 10!"

  }
until($script:coordinateNumber -match "^([1-9]|[1][0])$")


}
$playerMove = $coordinateLetter + $coordinateNumber
Write-host "You have chosen " -NoNewline; Write-host "$fullCoordinate" -for green

After this block of code I would like to perform a check that the value is possible for use. Jerry Lee Ford's book uses the following method in the Three in a Row game:

if (($move -eq "A1") -and ($A1 -ne " ")) {$result = "Invalid"}
if (($move -eq "A2") -and ($A2 -ne " ")) {$result = "Invalid"}
if (($move -eq "A3") -and ($A3 -ne " ")) {$result = "Invalid"}
if (($move -eq "B1") -and ($B1 -ne " ")) {$result = "Invalid"}

and so forth. But that would mean that I would have to make 100 variables (!) and write a check for all of them ?

Can anyone point me in the right direction?


Reboot check script using WMI

$
0
0

Hi All,

Sorry if this is something I should know but I am new to Powershell, below is what I run to check reboot times on 200 Xenapp servers. The script works fine but if a server has not come back online Powershell just ignores it and moves on it seems, is there a way I can add servers that have not booted to the email that gets sent? Any help would be great :)

Send-MailMessage -From "a.user@abc.com" -To "b.user@abc.com" -Subject "XA Reboot Check" -Body (Get-WmiObject Win32_OperatingSystem -computer (Get-Content .\Servers.txt) |
    Select CSNAME,
           @{N='LastBoot';E={[System.Management.ManagementDateTimeCOnverter]::ToDateTime($_.LastBootUpTime)}} | Out-String)

Run PowerShell script from C# writing to input pipe

$
0
0

Hello,

I am trying to run a PowerShell script from C# (I have no control over what's in the script). The script may have a prompt like "Press enter to continue". So my goal is:

1. Get text output from the script (easy, many examples available)

3. If output contains "Press enter to continue", write a blank line to the running script's pipe to make it finish its job and quit

4. If output does contain that prompt, just let it exit by itself without sending any input

Note that commands in this PS script also try to get at script's file path, so I can't read script from file and pass it as text. It has to be executed as a script so it knows where it's located.

I have done this with .exes and batch files before. All you do in that case is process.StandardInput.WriteLine() which "types" enter into the input stream of script you are trying to control. But this does not work with Power Shell. How do I do this?

I have tried using PS object model like so:

using (Pipeline pipeline = runspace.CreatePipeline()) { Command command = new Command(scriptPS, true, true);   pipeline.Commands.Add(command);   pipeline.Commands[0].MergeMyResults(PipelineResultTypes.Error, PipelineResultTypes.Output);   pipeline.Input.Write("\n");   Collection<PSObject> psresults = pipeline.Invoke();

   //...

But I get an error because the script prompts:

"A command that prompts the user failed because the host program or the command type does not support user interaction. Try a host program that supports user interaction, such as the Windows PowerShell Console or Windows PowerShell ISE, and remove prompt-related commands from command types that do not support user interaction, such as Windows PowerShell workflows."

I also tried using Process, and running PowerShell with -File switch to execute the script, then write to StandardInput with C#. I get no errors then, but the input is ignored and doesn't make it to PowerShell.

Please help!


Powershell log user account in on remote server

$
0
0
I have a application that we install that I have to log out of user account and then log back in manually. I have firgured out how to log the user out, but cannot find how to log the user back in with a powershell. It is using sessionID 1 so I need to to log back in as that one aswell. Any ideas.

activating windows using creds gathered from get-credential?

$
0
0

so, after a couple hours not being able to put my finger on this... i am looking here for a poke in the right direction since i am still feeling my way around PowerShell 3 :)

i am prompting the users for domain credentials in the script and and trying to run the windows activation command as the user that just 'authenticated' (trouble is the proxy is not liking the normal "join domain" account and blocking access)

$Global:c = Get-Credential -Message "Please Enter Your Credentials:"

Invoke-command -Credential $global:c -ScriptBlock {& C:\Windows\System32\slmgr.vbs /ato}

I keep getting a "parameter cannot be resolved using specified parameters... if it remove the "-Credential" parameter it works... but doesn't run under the right user context...

same if i try calling the .vbs via "&" or anything else I have tried for that matter... it will run but not with the right credentials i have a feeling it is something silly... but maybe not.... it might be my logic; but this works if i use the variable $global:c in other calls like

$name = $env:COMPUTERNAME $Global:c = Get-Credential -Message "Please Enter Your Credentials:" New-ADGroup -Credentials $global:c -Name "$name Administrators" -GroupScope DomainLocal -GroupCategory Security -Path

"OU=LocalAdmins,OU=Groups,DC=test,DC=com" -Description "Grants local administrator access for $name"

-DisplayName "$name Administrators"

any insight would be greatly appreciated but it feels like i am close! :)


~Shadster

path seems to be invalid when powershell started

$
0
0

Hi, I have novice question, I defined a specific path in a system properties to be able to execute a file without typing full path.

Once I start the command line I can start executable fine. Now I start powershell from cmline so that PS prompt becomes PS C:\<path>. Now I execute the same file it is not longer recognized. if I exit from PS to command line again I can execute again.

Does that mean, path defined in system properties are invalid in PS session? Or do I have to do an extra steps? Thanks,

convert .eml to .msg

$
0
0

I have 500000 .eml files that needs to be converted to .msg file and save in local folder.

I want to know if we have any powershell command to do so?

Or any other efficient method to achieve this??(C#)

PS: Dont want to use third party converters.

Checking directory structure compliance

$
0
0

Hi all,

I have a need to check for compliance of NTFS permissions on several file servers. My initial thought was write a script that takes a set of ACLs and recurses the directory tree checking for compliance and outputting directory names that are out of compliance with our standards.

This proved to be way above my level. 

What I came up with is a script checks for broken inheritance and outputs the ACLS. I then manually compare them using Notepad++. This is very tedious, but it works.

My script is here:

Get-ChildItem "e:\pathHere" -recurse | ? {$_.PSIsContainer} | ? {Get-Acl $_.FullName | % {$_.GetAccessRules($true, $true, 'System.Security.Principal.NTAccount') | ? {!$_.IsInherited}}} | get-acl | Format-List >> c:\OutputPathHere.txt

My question is, anyone have any ideas for a less time consuming way to accomplish this? A fully automated solution would be ideal but I am not sure that is even possible.

I appreciate any input.

Thanks.


Converting vbscript to powershell -- ACE question

$
0
0

hello, 

I have a script to disable a user written in vbscript that I am converting to powershell.  One line has me stumped

objACE = CreateObject("AccessControlEntry")

what would be the PowerShell equivalent?   If it makes it more clear here are the few lines for this section, I have attempted to make this into powershell code.

I geatly appreciate any help, tips and links you can offer.

$objUser = New-Object System.DirectoryServices.DirectoryEntry ("LDAP://" + $strDN)

#------------------------------------------------------------------------------------
#----------------------- START OF ADDING SELF to EXCHANGE PERMISSION FOR THE USER
#------------------------------------------------------------------------------------

Set $objACE = CreateObject("AccessControlEntry")
Set $objMailbox = $objUser
Set $objMailboxSD = $objUser.MailboxRights
Set $objDACL = $objMailboxSD.DiscretionaryAcl 

# Fill in the new ACE
$objACE.Trustee = "SELF"
$objACE.AccessMask = $ACE_MB_FULL_ACCESS -bOr $ACE_MB_DELETE_STORAGE -bOr $ACE_MB_ASSOC_EXT_ACCT
$objACE.AceType = $ADS_ACETYPE_ACCESS_ALLOWED
$objACE.AceFlags = 2 # object and subcontainers
$objDACL.AddAce = $objACE
$objMailboxSD.DiscretionaryAcl = $objDACL
$objMailbox.MailboxRights = $objMailboxSD
$objUser.SetInfo
#--------------------------------------------------------------------------------
#-----------------------END OF ADDING SELF to EXCHANGE PERMISSION FOR THE USER
#--------------------------------------------------------------------------------

how to pull the latest diff backup from a single folder that contains Multiple diff backups for multiple databases.

$
0
0

Hi,

I have a dilemma...

I have been tasked with automating the restore process for one of our DR sites.

One of the specific things I will be doing is restore all full backups from a  network share then

I need to restore the latest differential for each of the databases I am restoring.

I'm not having any problems getting the correct full back ups restored as I have written another script that purges old full backups...

However, the differencials are a different matter entirely.

I was trying this little bit of code to pull back the latest differencials and then I was simply going to do a -contains to make sure the correct diff was restored to the correct db...

$fil

$filesdif = Get-ChildItem $Directory -filter "*dif*.sqb" -rec | Where-Object {($_.Directory -notlike $Directory+"\master\FULL" )}
$filesSorted = $filesdif | group name | foreach {@($_.group | sort {[datetime]$_.lastwritetime} -desc)[0]} | sort {$_.name}

 

However, this doesn't seem to be working at the filenames contain date/time stamps in them... for example I might have 5 diffs

for acme database and they would like something like follows....

 

DIFF_(local)_acme_20121228_152352.sqb
DIFF_(local)_acme_20121229_152352.sqb
DIFF_(local)_acme_20130102_152352.sqb

etc...

well since they all have different names.. I can't really sort on the name as is...

I was wondering if anyone else has run into something similar. I was wondering if there would be a way to modify the
"group name" section to actually strip off the date time part just for the comparison...

I tried something like...

$filesSorteddif = $filesdif | group $_.fullname.replace("\d{8}\_\d{6}\.\w{3}$","")  | foreach {@($_.group | sort {[datetime]$_.lastwritetime} -desc)[0]} | sort {$_.name}   

But no luck...

Any help would be greatly appreciated.

Thanks!

Jason


esSorted=$files|groupname|foreach{@($_.group|sort{[datetime]$_.lastwritetime}-desc)[0]}|sort{$_.name}



Powershell clicking graphic button on a webpage

$
0
0

I am using Powershell to open a website, enter information and then extract data off the webpage. It works fine for most things. I am using getElementById. However, there is a table and it has buttons below it to move to the next set of records. I can't find an ID to force a click. This is all I see in the page source code, so I don't have an ID to grab.  I don't have access to the websites' code at all.

<TD width=1><IMG style="CURSOR: pointer" onclick="Grid1.NextPage();return false;"

"</td><td width=\"1\"><img style=\"cursor:pointer;\" "+this.GetPagerButtonSource("next.gif")+" onclick=\""+this.Id+".NextPage();return false;\"></td>


Any ideas?

 

Enable-PSremoting or winrm qc received error

$
0
0

Hi

I want to enable remote management on Windows 2003 R2. The WinRM service is running but after running winrm qc i received:



and after running in elevated powershell command enable-psremoting -force:



The firewall is disabled. Can some one give a tip what is wrong?

Thanks



Get-Aduser where Password expiry sanity check.

$
0
0

Hi guys,

I have a script to locate users that:

passwordneverexpires is false

accounts is enabled

and the passwordexpires in less or equal to 8 days.

I think it works fine but it is not showing any data.

The script doesn't error it runs fine but that's it.

I am missing anything? 

Import-Module ActiveDirectory
$days_to_expiry = 8
$date = get-date
[array]$expiring_users=  Get-ADUser -filter {(PasswordNeverExpires -eq $false) -and (enabled -eq $true)} -searchscope subtree -searchbase "OU=Main,DC=Contoso,DC=com" -Properties * | where {($_.passwordexpires -le $date.adddays($days_to_expiry))}

Thanks

Viewing all 2562 articles
Browse latest View live


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