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

Function Parameter Selectlist

$
0
0

When I use the function I would like it to get a dropdown list of "ValidationSet" after I typed in

"My-Function -Selected "

Function My-Function (
	[CmdletBinding()]
	[Parameter(Position=0, Mandatory=$true)]
    [ValidateSet("Default", "SomethingElse", "Custom")]
    $Selected = "Default"

	) {
	begin {
		switch ($Selected) {
			"Custom" { "code A" }"Default" {"Code B" }
		}
	}
}

My-Function -Selected "Custom"





Report of ad user based on group member ship

$
0
0

Team, 

can we get report from AD based on the  group member ship, we need to find user's which are not log in ad from 120 days . these users are part of any specific security group. 


Regards, Triyambak

Multiple select-object in one powershell

$
0
0

I am piping the output of one PS command into another command, and then displaying the resultant set via the select-object command. However I am not able to display any field/column from the original powershell command. How can I make that happen? Any ideas/leads. Here is a sample of what I am trying to do. 

Get-Mailbox -OrganizationalUnit "mydomain/french" | select-object Alias | foreach { Get-ActiveSyncDeviceStatistics -Mailbox $_.alias} | select-object Identity, DeviceOS

I was hoping for a output like Alias, Identity, DeviceOS. However it is only displaying Identity, DeviceOS (which are the fields in the second select-object). 

Am I  missing something here? Is there some other way to do it? 


Project Manager FTC

Error when running Get-ADAccountAuthorizationGroup cmdlet

$
0
0

I am trying to retrieve a list of all the groups a user is a member of. I ran the command:

Get-ADAccountAuthorizationGroup username

and received this error:

The server has returned a no matching security principal error.

I tested the same command on another user and received results.  I tested it a 3rd time on my own account, and received the error.  Double/triple checked the syntax in case of typos, no errors.

Not sure what to look for, or how to fix this error.

Need to recursivley get folder name and append to files

$
0
0

 As I process folders I want to capture the folder name and append to each file I process in that perticular folder.

 THis is a script I have that appends a file name to the end. I want the folder that it's currently processing added to the end of
each file.

 The folder structure example I'm using is

C:\sistemi  -- Need to recursivley get next to folders and pull Folder name in example.

$path='C:\Sistemi\'
get-childitem -path $path *.spx | % {" Starting File Process....."  >> $path\sistem.log
	   $PDate = get-date
       $date = get-date -uformat "_%d_%m_%Y_%H%M%S.bak"
       #"Set backup date to $date" >> $path\sistem.log
       $newname=($_.fullname -replace ".spx",$date)
	$file = [System.IO.Path]::GetFileNameWithoutExtension($_.fullname)"File backup name is $newname" >> $path\sistem.log 
       Rename-Item $_.fullname $newname"Renamed file to $newname" >> $path\sistem.log
	   $lines = get-content $newname
	   foreach ($line in $lines) 
	    {
			$line + " " + [System.IO.Path]::GetFileNameWithoutExtension($_.fullname) | Out-File "$path\sistem.csv"   -append
	    }		
       Write-Host $_.fullname "Files Processed on $PDate are $newname " >> $path\sistem.log
}


C:\Sistemi\REW1___1
C:\Sistemi\REW2___1 

I need to pull up to the underscore as the folder name (REW1,REW2 examples) and append that to the end of each processed file in my script.

 


 

Write-Error in script method writes nothing

$
0
0

Powershell newb here. Could someone enlighten me as to why "error 2" below is not getting displayed?

-------------------
function New-Log() {
    New-Object Object |
        Add-Member ScriptMethod Error { param($m); Write-Error $m } -PassThru |
        Add-Member ScriptMethod Warning { param($m); Write-Warning $m } -PassThru
}

$log = New-Log

Write-Error "error 1"
Write-Warning "warning 1"

$log.Error("error 2")
$log.Warning("warning 2")
----------------
produces output:
----------------

C:\temp\testps.ps1 : error 1
At line:1 char:1
+ .\testps.ps1
+ ~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [Write-Error], WriteErrorException
    + FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,testps.ps1
 
WARNING: warning 1
WARNING: warning 2

----------------

As an aside, I don't understand the line/char information of "error 1". I'm running on x64 Win 8.1

> $PSVersionTable

Name                                  Value
----                                     -----                                                                                                                                      
PSVersion                            4.0
WSManStackVersion             3.0
SerializationVersion              1.1.0.1
CLRVersion                          4.0.30319.34011
BuildVersion                         6.3.9600.16394
PSCompatibleVersions           {1.0, 2.0, 3.0, 4.0}
PSRemotingProtocolVersion    2.2

How to unlock nokia lumia 520

$
0
0
http://www.andengine.org/forums/tutorials/getn-watch-endless-love-online-free-movie-qhd-full-t15029.html
http://www.andengine.org/forums/tutorials/season-watch-winter-s-tale-online-free-full-putlocker-t15030.html
http://www.andengine.org/forums/tutorials/i-watch-robocop-online-2014-full-movie-free-qhd-t15033.html
http://www.andengine.org/forums/tutorials/eni-watch-about-last-night-online-full-movie-dir-pink-t15034.html
http://www.andengine.org/forums/tutorials/watch-the-lego-movie-online-free-full-movie-streaming-enjoy-t15035.html
http://www.andengine.org/forums/tutorials/o-watch-the-monuments-men-online-full-free-on-net-2014-t15038.html
http://www.andengine.org/forums/tutorials/watch-ride-along-online-2014-tim-best-story-free-full-t15041.html
http://www.andengine.org/forums/tutorials/watch-the-nut-job-online-2014-free-full-movie-t15042.html
http://www.andengine.org/forums/tutorials/watch-that-awkward-moment-online-t15043.html
http://www.andengine.org/forums/tutorials/etc-watch-pretty-little-liars-season-4-episode-20-online-t15045.html
http://www.andengine.org/forums/tutorials/watch-dance-moms-season-4-episode-9-online-t15046.html
http://www.andengine.org/forums/tutorials/watch-twisted-season-1-episode-13-online-t15047.html
http://www.andengine.org/forums/tutorials/watch-cougar-town-season-5-episode-7-online-t15048.html

While loop hangs in my script

$
0
0

Hi guys,

I want to check if SCCM (install windows image) is ready.

If it's not, than it has to sleep. I want this in a while loop because when it takes longer, it must loop another

5 minutes.

When the image is ready it must go back to the rest of this script.

My loop hangs and the script never finishes. What am i doing wrong?

Kind regards,

André

$compObject = get-wmiobject -query "select * from SMS_R_SYSTEM WHERE Name='$hostName'" -computername "dhgms401" -namespace "ROOT\SMS\site_S01"
  $compObjectstatus = $compObject.client
  do {
    Start-Sleep -Seconds 300
  }
  while ($compObjectstatus -eq 0)
  write "Sccm is klaar "
  Write "$hostName has been started"
  $newHostName = Get-ADComputer -filter {(name -eq $hostName)}	


Windows Powershell has stopped working

$
0
0

Hi,

I am getting an error during Windows logon, which says "Windows Powershell has stopped working". When I looked at the event logs, I found the below event in App logs. Can you pls help what is going wrong here?

Log Name:      Application
Source:        Application Error
Date:          2/18/2014 7:55:16 PM
Event ID:      1000
Task Category: Application Crashing Events
Level:         Error
Keywords:      Classic
User:          N/A
Computer:      MININT-BNG69NS
Description:
Faulting application name: powershell.exe, version: 6.3.9600.16406, time stamp: 0x5244e9dc
Faulting module name: KERNELBASE.dll, version: 6.1.7601.18229, time stamp: 0x51fb1677
Exception code: 0xe0434352
Fault offset: 0x000000000000940d
Faulting process id: 0xb3c
Faulting application start time: 0x01cf2cb52a860b9f
Faulting application path: C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe
Faulting module path: C:\WINDOWS\system32\KERNELBASE.dll
Report Id: 7c4832cf-98a8-11e3-b82f-a088b40d3a94
Event Xml:
<Event xmlns="http://schemas.microsoft.com/win/2004/08/events/event">
  <System>
    <Provider Name="Application Error" />
    <EventID Qualifiers="0">1000</EventID>
    <Level>2</Level>
    <Task>100</Task>
    <Keywords>0x80000000000000</Keywords>
    <TimeCreated SystemTime="2014-02-18T14:25:16.000000000Z" />
    <EventRecordID>2449</EventRecordID>
    <Channel>Application</Channel>
    <Computer>MININT-BNG69NS</Computer>
    <Security />
  </System>
  <EventData>
    <Data>powershell.exe</Data>
    <Data>6.3.9600.16406</Data>
    <Data>5244e9dc</Data>
    <Data>KERNELBASE.dll</Data>
    <Data>6.1.7601.18229</Data>
    <Data>51fb1677</Data>
    <Data>e0434352</Data>
    <Data>000000000000940d</Data>
    <Data>b3c</Data>
    <Data>01cf2cb52a860b9f</Data>
    <Data>C:\WINDOWS\System32\WindowsPowerShell\v1.0\powershell.exe</Data>
    <Data>C:\WINDOWS\system32\KERNELBASE.dll</Data>
    <Data>7c4832cf-98a8-11e3-b82f-a088b40d3a94</Data>
  </EventData>
</Event>


Arun

PowerShell - Rename Contents of File Using names From CSV

$
0
0

I have the following script where the user is asked for the file server IP address, the IP is entered and the gpreport.xml file modified as needed.

$file_server = Read-Host "Enter the file server IP address"

$rootFolder = 'C:\TEMP\GPO\source\5'

Get-ChildItem -LiteralPath $rootFolder -Directory |
Where-Object { $_.Name -as [System.Guid] } |
ForEach-Object {
    $directory = $_.FullName

    (Get-Content "$directory\gpreport.xml") |
    ForEach-Object { $_ -replace "99.999.999.999", $file_server } |
    Set-Content "$directory\gpreport.xml"

    # ... etc
}

This works well, but I would like to automate it using a reference CVS file. I have 3 columns in my file - FQDN, Server Name and Server IP. I need PowerShell to identify current logged on users domain name ($env:userdnsdomain) and match the result to the CSV file below. Once matched, take the server IP column and insert it into gpreport.xml . This way the user insnt being asked for the Ip address of the $file_server and it's being done automatically.

Thank you.


Get-process mainwindowtitle for all users

$
0
0

I have an application on a server that must be run in a user's session, and multiple instances are open which connect to different databases. In the account they run under, the window title will be "App - client A", "App - client B", etc.

The problem is that if another admin needs to restart one of them, when he looks in task manager in Server 2008R2, it only shows as programname.exe with 5 listings of it. I've tried process explorer and such, and it won't list the window name across sessions.

I found this string: get-process | where {$_.mainwindowtitle -match "Windowname"} | format-table id, name, mainwindowtitle -autosize

Now, while that will show the correct info for the user running that app, if another admin runs that, the mainwindowtitle is blank. How can I make it show the mainwindowtitle for another user?

My end goal is to have it display the mainwindowtitle and the PID, so we know which to kill.

Any help would be greatly appreciated!

Automate PowerShell Install

$
0
0

Hello,

I am really new at this. But I am trying to deploy PowerShell 2.0 to our environment. Is there a way to automate this? I know we will have to remove PowerShell 1 first.

I hope I am asking the right question. What I need Is a script or a how-to create a script that will install PowerShell 2.0 to a bunch of test servers  I have. If I am not in the right forum please let me know also. thanks in advance for your help.

Using select with get-adgroupmember

$
0
0

Hello all. What I would like to do may be a bit tricky, but maybe not. This simple bit of code will get the members from a group and list the group name along with each member. Easy right?

$group = "Group1"

get-adgroupmember $group | select name, @{n="group name";e={$group}}

The output from the above script looks like:

What I would like is to eliminate the repetitive "Group1" output, and have the output look like this instead:

Is this possible with the get-adgroupmember command? Or is there another series of commands that would accomplish this?

Windows 2008, PowerShell 2.0 isn't able to load FailoverClusters module, says no valid module file was found

$
0
0

Hi all.

On our Windows 2008 SP1 Server running a Windows Cluster (not R2) I've installed PowerShell 2 (KB968930) but when I attempt to run this:

Import-Module FailoverClusters

It says the module couldn't be loaded because no valid module file was found in any module directory. I've ran this as both myself (I'm in Admin group) and as the local administrator with the same results.  When I run Get-Module -listavailable it only lists BitsTransfer and PSDiagnostics.  

This server is one of the nodes on the Windows Cluster and the Windows Cluster service is running with the cluster being up and working without issue.  So how can I get the FailoverClusters module available in PowerShell?

Thanks.

Auto delete everything but specified folder contents from txt file

$
0
0

Hey Guys,

I am brand new to using Powershell (like 48 hours into using it for work) and I've run into a bit of an issue.  I've only taken a programming concept classes so some of the stuff makes sense to me but a lot of it is new.  Basically I've made a script that automatically deletes any files over X amount of days.  My next step is to have an exceptions text that will have a list of folders that should not have its contents deleted.  This is what I have so far.


$Date= Get-Date 
$Days = "7"
$Folder = "C:\publicftp\users"
$LastWrite = $Now.AddDays(-$Days)
#----- getting DO NOT DELETE listing from TXT ----#
$Exceptions = Get-Content "c:\exclude.txt"
$Files = Get-Childitem $Folder -Recurse -Exclude "c:\exclude.txt" | Where {$_.LastWriteTime -le "$LastWrite"}


foreach ($File in $Files)
    {
    if ($File -ne $NULL)
        {
        Remove-Item $File.FullName -Exclude $Exceptions | out-null
        }
    }

I've seen a lot of threads that show how to auto delete contents or how to exclude specific file types but I haven't seen an answer to my particular problem.  Any help would be greatly appreciated!  Thanks!




how restore damage environment variables

$
0
0

hi all, i damage in some way my environment variables and now im unable to run anything with elevation.

The only command that i use was:

[environment]::setenvironmentvariable("Path", thepathvariablethaticompute, "Machine")

before i make any change i save the content of the path variable because that was the variable that i want to modify. So after the things goes wrong i reestablish the order setting the Path to the old value. To my surprise that doesn't was enough and now every time i try to run something with elevation the system doesnt found the excutable.

Perhaps that some things still works, if i go to the execute (win+R) and write notepad, cmd, etc, they are executed normally. But if i want to explore the advances system options c:\windows\system32\systemPropertiesadvanced.exe then this message appear:

The System could not find the environment option that was entered.

To diagnose the problem in cmd i ask for the environment variables, this is the output:

ALLUSERSPROFILE=C:\ProgramData
APPDATA=C:\Users\voodoomsr\AppData\Roaming
CLASSPATH=.;C:\Program Files (x86)\Java\jre6\lib\ext\QTJava.zip
CommonProgramFiles=C:\Program Files\Common Files
CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
CommonProgramW6432=C:\Program Files\Common Files
COMPUTERNAME=VOODOOMSRLAPTOP
ComSpec=C:\Windows\system32\cmd.exe
FP_NO_HOST_CHECK=NO
FTP_PASSIVE=1
HOMEDRIVE=C:
HOMEPATH=\Users\voodoomsr
LOCALAPPDATA=C:\Users\voodoomsr\AppData\Local
LOGONSERVER=\\VOODOOMSRLAPTOP
MOZ_PLUGIN_PATH=C:\Program Files\Tracker Software\PDF Viewer\Win32
NUMBER_OF_PROCESSORS=2
OS=Windows_NT
PATHEXT=.COM;.EXE;.BAT;.CMD;.VBS;.JS;.WS;.MSC
ProgramData=C:\ProgramData
ProgramFiles=C:\Program Files
ProgramFiles(x86)=C:\Program Files (x86)
ProgramW6432=C:\Program Files
PROMPT=$P$G
PUBLIC=C:\Users\Public
SESSIONNAME=Console
SystemDrive=C:
SystemRoot=C:\Windows
USERDOMAIN=voodoomsrlaptop
USERNAME=voodoomsr
USERPROFILE=C:\Users\voodoomsr

In the powershell i get different results when i ask for the path variable

if i do:

$env:path

the result is : %SystemRoot%\system32\WindowsPowerShell\v1.0\

if i do: [environment]::GetEnvironmentVariable("Path","User")

then i get all the correct path:

C:\Windows\system32\WindowsPowerShell\v1.0\;C:\Program Files\Common Files\Microsoft Sh
ared\Windows Live;C:\Program Files (x86)\Common Files\Microsoft Shared\Windows Live;C:
\Program Files (x86)\CodeBlocks\MinGW\bin;C:\Program Files (x86)\HTML Help Workshop;C:
\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\bin;C:\Program Files (x86)\Microsoft
 SDKs\Windows\v7.0A\bin\NETFX 4.0 Tools\x64;C:\Program Files (x86)\Microsoft SDKs\Wind
ows\v7.0A\bin\x64;C:\Program Files (x86)\Microsoft SQL Server\100\DTS\Binn\;C:\Program
 Files (x86)\Microsoft SQL Server\100\Tools\Binn\;C:\Program Files (x86)\Microsoft SQL
 Server\100\Tools\Binn\VSShell\Common7\IDE\;C:\Program Files (x86)\Microsoft Visual St
udio 10.0\Common7\IDE;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\Tool
s;C:\Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Performance Tools;C:\
Program Files (x86)\Microsoft Visual Studio 10.0\Team Tools\Performance Tools\x64;C:\P
rogram Files (x86)\Microsoft Visual Studio 10.0\VC\BIN\amd64;C:\Program Files (x86)\Mi
crosoft Visual Studio 10.0\VC\VCPackages;C:\Program Files (x86)\Microsoft Visual Studi
o 2008 SDK\VisualStudioIntegration\Tools\Sandcastle\ProductionTools\;C:\Program Files
(x86)\Microsoft Visual Studio 9.0\Common7\IDE\PrivateAssemblies\;C:\Program Files (x86
)\MiKTeX 2.8\miktex\bin;C:\Program Files (x86)\PHP\;C:\Program Files\7-Zip;C:\Program
Files\Intel\WiFi\bin\;C:\Program Files\Microsoft Windows Performance Toolkit\;C:\Users
\voodoomsr\Valhala\GPS1C;C:\Users\voodoomsr\Valhala\ShortCuts;C:\Users\voodoomsr\Valha
la\Utilitarios\bin;C:\Users\voodoomsr\Valhala\Utilitarios\SysinternalsSuite;C:\Windows
;C:\Windows\Microsoft.NET\Framework64\v3.5;C:\Windows\Microsoft.NET\Framework64\v4.0.3
0319;C:\Windows\system32;C:\Windows\System32\Wbem;C:\Windows\system32\WindowsPowerShel
l\v1.0\;C:\Program Files (x86)\Windows Live\Shared;C:\Program Files (x86)\PostgreSQL\8
.4\bin;C:\Program Files (x86)\QuickTime\QTSystem\;C:\Program Files\TortoiseSVN\bin;C:\
strawberry\c\bin;C:\strawberry\perl\site\bin;C:\strawberry\perl\bin;C:\Users\voodoomsr
\Valhala\GAHKC;;C:\Program Files (x86)\Microsoft ASP.NET\ASP.NET Web Pages\v1.0;C:\Use
rs\voodoomsr\Valhala\Utilitarios\Q10

I get the same result using   [environment]::GetEnvironmentVariable("Path","Machine")

so i really don't understand what is happening, with the inspection everything appears to be normal except the path variable.Using .net appears fine but directly $env:path is incomplete. If i ask in cmd for path then it tellsme that is null.

Any helps is apreciated.

 

 

 

Powershell - Parse Data Returned from Web Request

$
0
0

$result = Invoke-WebRequest http://partsurfer.hp.com/Search.aspx?SearchText=614988-B21

Now, I want to grab two lines in the output that looks like:

Product Number : 614988-B21
Description : HP SCO8E 6 GB SAS HOST BUS ADAPTER (HBA)

How can I grab the text that appears after "Description :" up to the end of line?

I've tried things like:

$result.allelements | where {$_.innertext -like "Description : "} | select innertext

But that doesn't give me the whole line. Just echoes "Description :"

Obviously, the exact part number and description will vary. This is just one example.

Active Directory/Powershell Name Formatting - Proper Title Case & processing

$
0
0

I'm getting a nightly feed from our HR system with user information.  I'm trying to use this feed to create and maintain Active Directory.  The folks that enter the data are a little less than consistent.  I've seen ALL CAPS, all lowercase, and occasionally AmiXed BaG.

I can't fix the database because I don't own the data.  I'm a lowly windows/linux guy trying to make the best of a bad situation.  

I'm loading everything in from a CSV file, and removing parenthesis and escaping the apostrophes for the O'Malley twins.

$LAST = "'" + ($entry.last_name -replace "'","''" -replace "\(","" -replace "\)","") + "'"

I'm actually doing that replace command for everything I read in since some departments and titles have apostrophes in the names...but that's another thread.

I'm using (Get-Culture).TextInfo.ToTitleCase to fix the easy stuff and capitalize the first letter of each name:

$FIRST = (Get-Culture).TextInfo.ToTitleCase($FIRST)
$LAST = (Get-Culture).TextInfo.ToTitleCase($LAST)
$MIDDLE = (Get-Culture).TextInfo.ToTitleCase($MIDDLE)

I've written the code to fix names like MacGruber and McClung, but I'm having trouble finding where I've done it and how I've done it (I'm assuming I used regex).  I'm curious if there are other problem names that (Get-Culture).TextInfo.ToTitleCase won't totally fix. 

I have another concern.  My script is going to run from the HR data....meaning, it could be triggered any time they make any change to the record.  Once they make a change, they'll show up in the feed and my script will repush all fields from HR... I may try to build in a *manual override* flag somewhere, but don't know what attribute in AD I can use to store it or if it's worth spending time on coding it...

I'd like to see what other people do that are faced with this problem.

Thanks.

Remove characters except numbers from variable string

$
0
0

Hi, my script queries some linux servers for ram memory, but it returns the value as:

$ram = MemTotal:        3521384 kB

Is there a way that i can remove all characters except numbers from the variable?

Thanks

Power Shell vs AutoIT

$
0
0

How does Power Shell compare to AutoIT in terms of:

1. functionality

2. complexity

3. learning curve

Currently my interest is for non-GUI functionality, especially for disk/folder/file management, PC maintenance, registry work, date/time, string maniputation, file I/O, interfacing with MS Office, interaction with external programs such as robocopy, access to and work on networked PCs and storage.

Viewing all 21975 articles
Browse latest View live


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