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

Filter results by values from array

$
0
0

Hey Guys,

I'm writing a script to list the properties of SharePoint groups.

This piece of code works fine but returns all Sharepoint groups in $site, meaning hundreds of records.

$site = Get-SPSite https://MyWeb/MySiteCollection
$groups = $site.RootWeb.sitegroups
foreach ($grp in $groups) { do something }

So I was looking to filter the list of groups; and I came up with this other piece of code, which also works.

$site = Get-SPSite https://MyWeb/MySiteCollection
$groups = $site.RootWeb.sitegroups | ? {$_.Name -like "Training*"}
foreach ($grp in $groups) { do something }

Then I thought, why not storing the names of the groups I'm interesting in an array and select from $groups only the ones where the group name matches one of the names in my array.

So I created a file named 'Groups.ini' and typed the names of the groups I'm interested in. I wrote this script, but it doesn't work

$site = Get-SPSite https://MyWeb/MySiteCollection
$mygroups = Get-Content D:\Tools\Groups.ini
$groups = $site.RootWeb.sitegroups | ? {$_.Name -like $mygroups}
foreach ($grp in $groups) { do something }

The line I'm interested in is 

$groups = $site.RootWeb.sitegroups | ? {$_.Name -like $mygroups}

How can I select the items from $groups where the name is one of the value of my array $mygroups ?

Thanks in advance and have a nice day




Copy files to remote machine

$
0
0

hi all, please help me with this... in WINDOWS POWERSHELL

     I need to copy files to multiple computers from my computer with following specifications..

     1)I need to provide username

     2)I need to provide password also

     3)while running it should not prompt again for password /*important*/

I USED THE FOLLOWING CODE BUT IT IS PROMPTING FOR PASSWORD AGAIN

###############################################################################################

     read-host -assecurestring | convertfrom-securestring | out-file e:\SSS\pass.txt

     $password=get-content e:\SSS\pass.txt | convertto-securestring 

     $credential=new-object -typename System.Management.Automation.PSCredential -argumentlist KS\KS012\Administrator, $password

Make one command out of if/else statements - Cannot convert the value of type"System.String"

$
0
0

Hello,

I'm trying to make one command out of multiple if/else statements.
For example I'm looking up a cloud in VMM, when it does exists add "-cloud $cloud" to $command, when it does not exists  lookup the default cloud and add -cloud $cloud" to the command.
Maybe a cloud is a bad example but it could also be an IP address (if $IP -ne $null) then add "-ip $IP" to $command.

# Get cloud, if exists
$cloud = get-sccloud -name "Cloudname"

[string]$command = "New-SCVirtualMachine -Name $VMname -VMConfiguration $virtualMachineConfiguration -ReturnImmediately -DelayStartSeconds '0' -RunAsynchronously"


if ($cloud -ne $null){
$command  += " -cloud $cloud"
}
else {
$cloud = get-sccloud -name "Default cloud"
$command += " -cloud $cloud"
}

When I try the above I will recieve this error:

New-SCVirtualMachine : Cannot bind parameter 'VMConfiguration'. Cannot convert the "Test VM" value of type"System.String" to type "Microsoft.SystemCenter.VirtualMachineManager.BaseVMConfiguration".

And I think the I get this error because the variables are emtpy when converting it to string.
What other type could I use? or other method?


Thanks for any help! :-)


how to retrieve the "Partner agents with full access" and "Partner agents with limited access" users in office365 using powershell?

$
0
0

how to retrieve the "Partner agents with full access" and "Partner agents with limited access" users in office365 using powershell?

thanks

venkat

start 2 processes in script with if / else command

$
0
0

Hy Everybody,

I am new to powershell scripting and i am facing the following problem,

For a specific application, that uses security dongles, i want to create a script that looks at the hardware id's of 2 types of usb security dongles.

  • one has limited runs
  • second has unlimited runs

For the dongle with unlimited runs i want to change a specific file in a specific folder before it starts the application for the second one i want to do nothing but just starting the application.

i have made the following script.

$devices = Get-WmiObject Win32_PNPEntity
$found = 0
foreach ($device in $devices) {
    if ($device.deviceid -eq 'USB Dongle with limited runs')
    { $found = 1 }
}

if ($found -eq 1)
{start-process "D:\Rename.cmd"} & {"C:\Program Files (x86)\App name\x.exe"}
else
{start-process "C:\Program Files (x86)\App name\x.EXE"}

if i run this it gives me the error:

The term 'else' is not recognized as the name of a cmdlet, function, script file, or operable program. Check the spelling of the name, or if a path was included, verify that the path is correct and try again.
At line:1 char:5
+ else <<<<
    + CategoryInfo          : ObjectNotFound: (else:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException
 

Can anyone please provide me the correct solution?

Thank you in advance.

Marc

How to create a new-pssession that runs a administrator

$
0
0

Hello all,

I'm trying to open a remote pssession to a management server that runs as administrator.

When I logon to the server with my account account and start the powershell prompt, then it immediatly starts with elevated rights.

UAC has been turned off and elevate without prompt is enabled via GPO.

I've seen a lot of posts around this by not entering the PSSession, but running the commands through invoke-command.

This doesn't work for me.. When I try to import the SCCM module for example, I get an access denied.

I've also tried creating the session, entering it and then starting a new process: powershell.exe with the switch -verb runas.

This doesn't do the trick neither.

Does anyone have an idea how I can get this working?

Thanks

Filip

PowerShell Script -- A Beginner Needs Some Help

$
0
0

Hi Everyone,

I hope that someone can help me out.  I'm looking for a PowerShell script that will ping all the workstations in my domain and search the discovered pc's for any versions of MS Visio intalled on them.  I'm in the process of learning PowerShell and I could use the help since management needed this done yesterday....

If someone can whip up a ps script for me that would be great -- if it can be set up so I can input any piece of software for later use that would be a big help as well

exporting server volume information to csv file

$
0
0
 

i have a working powershell script which searches active directory for a list of servers, then connects to each server and collects volume statistics and displays the results on-screen.  i would like to export the results into a csv file for trending analysis, this is where my powershell programming knowledge runs out.

i think i understand logically that i need to introduce a blank array (which array type, unsure), then loop through the list of servers 'appending' the individual volume information to the array, then upon completion of the loop, utilize the export-csv cmdlet to export the volume information collected in the array to a csv file.  i've looked online at many examples, i think i need to introduce another variable or powershell object to handle the appending (+=) of the information into the array, but i think i've researched myself into a coma. when i run the script trying to add the export-csv command either inside the loop or after loop completion, i either get an empty csv file or "gobbledy gook".  as a secondary component, collecting the information in an array would then allow me to run the script, export-csv trending data and then i could introduce a where clause at the end allowing me to display/export-csv/export-html any volume that meets a logical threshold (say <10% freespace).

any and all help is appreciated !!

script:

$servers = Get-ADComputer -SearchBase 'OU=Servers,DC=company,DC=com' -Filter { OperatingSystem -Like '*Windows Server*' } | sort name
$results = @()

Foreach ($server in $servers) {
    Get-WmiObject Win32_Volume -computername $server.name | 
        Where {$_.drivetype -eq 3} |
        Where {$_.label -ne "System Reserved"} |
        Select pscomputername, `
            @{"Label"="Volume";"Expression"={$_.name}}, `
            @{"Label"="Label";"Expression"={$_.label}}, `
            @{"Label"="Capacity(GB)";"Expression"={"{0:N2}" -f ($_.capacity/1GB)}}, `
            @{"Label"="FreeSpace(GB)";"Expression"={"{0:N2}" -f ($_.freespace/1GB)}}, `
            @{"Label"="%Free";"Expression"={"{0:P2}" -f ($_.freespace/$_.capacity)}}, `
            @{"Label"="Timestamp";"Expression"={(get-date -format G)}} |
        FT -auto
}
$results

screen output:

PSComputerName  Volume Label        Capacity(GB) FreeSpace(GB) %Free   Timestamp           
--------------  ------ -----        ------------ ------------- -----   ---------           
WindowsServer1  D:\    apps         20.00        19.78         98.91 % 6/7/2013 10:51:06 AM
WindowsServer1  E:\    pagefile     16.00        11.91         74.44 % 6/7/2013 10:51:06 AM
WindowsServer1  C:\    windows      39.90        26.61         66.69 % 6/7/2013 10:51:06 AM

PSComputerName  Volume Label        Capacity(GB) FreeSpace(GB) %Free   Timestamp           
--------------  ------ -----        ------------ ------------- -----   ---------           
WindowsServer2  D:\    apps         20.00        19.91         99.56 % 6/7/2013 10:51:08 AM
WindowsServer2  E:\    pagefile     16.00        11.91         74.44 % 6/7/2013 10:51:08 AM
WindowsServer2  C:\    windows      39.90        21.60         54.14 % 6/7/2013 10:51:08 AM

Powershell sort files by date issue

$
0
0

I have an SSIS package where one of the tasks that I'm running uses powershell to sort files by Modified Date descending and then deletes all the files but the file that had the most recent modification.  When the powershell script runs, it ends up deleting all but the second file from the top of the list; so the second most recently modified file.  I've tried troubleshooting this issue in Powershell ISE to get a better idea of what's going on, but I'm running across strange behavior.  I recently changed the script to sort the files by the LastWriteTime instead, but I get the same result.

I'm new to scripting with PowerShell, so forgive my ignorance.  Here's what I've tried.

The first line below is to view the files that I'm working with and to see what the LastWriteTime is.

The second line is part of the actual script; I add more code to actually remove the files.

Does anyone have any ideas as to why powershell sorts the files in the second result not in descending order when that's what I've specified?

PS D:\Vivid\2008R2_Solution\Vivid-SCP\vividreports> get-childitem -filter "*.xls" | sort LastWriteTime -Descending


    Directory: D:\Vivid\2008R2_Solution\Vivid-SCP\vividreports


Mode                LastWriteTime     Length Name                                                                                
----                -------------     ------ ----                                                                                
-a---        06/01/2013   4:00 AM     115200 managerReport_06_2013.xls                                                           
-a---        04/04/2013  12:00 AM     115200 managerReport_04_2013.xls                                                           
-a---        02/18/2013  11:00 PM     111616 managerReport_02_2013.xls                                                           
-a---        01/28/2013  11:00 PM      81920 managerReport_01_2013.xls                                                           



PS D:\Vivid\2008R2_Solution\Vivid-SCP\vividreports> get-childitem -name -filter "*.xls" | sort LastWriteTime -Descending
managerReport_04_2013.xls
managerReport_06_2013.xls
managerReport_01_2013.xls
managerReport_02_2013.xls


Curious question about -Split (powershell)

$
0
0

$String = @("asdf asdf asdf hijk hijk Database:001 asdf:45545 asdf asdf:4554 Database:101 hijk asdf "
"asdf asdf hijk Database:301 asdf asdf asdf asdf:4545 asdf asdf Database:011 hijk ")
Select-String -InputObject $String -Pattern 'Database:\d+' -AllMatches | %{$_.Matches} | %{$_.Value -split ':'}

I am a using above code as a part of a script..

I have seen in many  forums experts using %{$_.Matches} | %{$_.Value -split ':'} Select-String, however in above code I have noticed%{$_.Matches -split ':'}  also gives me the same result .

$_.Matches contain value as follows. I am not sure how split works on this object.. can someone explain?

Groups   : {Database:001}
Success  : True
Captures : {Database:001}
Index    : 25
Length   : 12
Value    : Database:001

Groups   : {Database:101}
Success  : True
Captures : {Database:101}
Index    : 64
Length   : 12
Value    : Database:101

Groups   : {Database:301}
Success  : True
Captures : {Database:301}
Index    : 103
Length   : 12
Value    : Database:301

Groups   : {Database:011}
Success  : True
Captures : {Database:011}
Index    : 151
Length   : 12
Value    : Database:011

Result

Database
001
Database
101
Database
301
Database
011


-Edatha-


Read file and then replace word from csv file

$
0
0

I want to replace words in config files, an replace the valor with value that are in csv file for example:

User      New User

abc        qwr

wer       123456

I want to search the word  "abc" and replace it for "qwr"

I write this but i do not know how to add

$configFiles=get-childitem . *.config -rec
foreach ($file in $configFiles)
{
$file.PSPath >> log.log
$a= "" + $file.PSPath + ".bkp"
cp $file.PSPath $a
(Get-Content $file.PSPath) |
Foreach-Object {$_ -replace "Decchi", "mono"} |
Set-Content $file.PSPath

}


adecchi

Get-BitsTransfer -AllUsers Remotly?

$
0
0

I am attempting to see if I can retrieve all the bits jobs running on a remote machine.  I have tried this code and it works great if using the local machine but nothing is returned for a remote machine. Any suggestions how to retrieve this information?

$jobwork = {
    #get-all bits downloads
    $jobout = Get-BitsTransfer -AllUsers | ? { $_.jobstate -ne 'transferred'}
    $jobout
}

$jobresults = Start-Job -ScriptBlock $jobwork -Name $job_name -ArgumentList $Compname

Powershell Logon script that can't be killed from Task Manager

$
0
0

Hi,

I am having a power shell script that runs as a logon script.  The script is critical and I want to prevent users from killing/stopping the process from Task Manager.  

I can't give admin/system credentials in the script as per environment's security policy.  Any idea's how I can run this script & prevent users from stopping it?

Thanks

Exchange Message Count

$
0
0

Hi There,

I am using the cmdlet below to extract the number of messages received by a users in Exchange 2010. it works fine and give me the message count however I cannot find a way to output the recipient name.

Any help on this would be appreciated.

get-messagetrackinglog -server svrname-recipients user@domain.com -Start "04/01/2013 00:00:00" -End "04/30/2013 00:00:00" |  measure-object



Find IP Address by MAC Address

$
0
0
I have a list of MAC addresses for remote PCs. How to find IP addresses they currently have?

download webpage content credential

$
0
0

I am trying to download a webpage content after passing on the credentails. Then downloading the content to a text file
and then parsing it to fetch the desried result. I am able to get the desired result while i am doing it from ISE/PS console. But when i am scheduleing it...The output is null.

Please provide your expertise inputs.

===========

$username = "username"
$password = "password"

$ie = New-Object -com InternetExplorer.Application

$ie.visible=$true

$ie.navigate("mywebsite.com")

while($ie.ReadyState -ne 4) {start-sleep -m 100}

$ie.document.getElementById("j_username").value = "$username"

$ie.document.getElementById("j_password").value = "$password"

$ie.document.getElementById("loginform").submit()

start-sleep 20

$mmy = $ie.Document.body
$mmy | Out-File -FilePath "c:\shell\axiom.txt"
$line = Get-Content "c:\shell\axiom.txt" | Select-String "inclue" | Select-String "exclu" -NotMatch
$line

================================

Powershell ISE show-command addon

$
0
0

the show-command addon has stopped working.. it only has the all modules and if say I type in get-process (no intellisense) and if I click on refresh I get the wonderful Windows Powershell ISE - Error  Falure to refresh Manager "Object reference not set to an instance of an object'.

Getting a Null Value, not sure why.

$
0
0

I have the following $FileNameCur2 is giving me a Null value..    I have a directory "E:\AD\Deleted\" where once a day, a CSV file arrives example: UsersDeleted-2013-6-8-6-3-47.csv

The below scripted,   looks at the Current Date of the file  UsersDeleted-2013-6-8* ,  

if it doesn't find UsersDeleted-2013-6-8* , then looks for yesterdays date UsersDeleted-2013-6-7*

Until a match

It worked at one point ,  but now it doesn't.   and now $FileNameCur2 has a null value.


$pathCur = "E:\AD\Deleted\"
$date = (get-date).ToString('yyyyMMdd')

$dateCur = (get-date).ToString('yyyy-M-dd')
$nameCur = "UsersDeleted-"
$Symbol = "*"

$CurDays = 0

Do{
$dateCur = (get-date).AddDays($Curdays).ToString("yyyy-M-dd")
$strFileCur2 = $namecur + $DateCur + $Symbol
$FileNameCur2 = Get-ChildItem -path $PathCur -recurse -include $strFileCur2

$CurDays = $CurDays + -1

}
Until(Test-Path $FileNameCur2)

$FileName = $FileNameCur2.name

thank you

Get-ADUser -Filter { lastLogon -gt $date } compared to Get-ADUser -Filter ' lastLogon -gt $date '

$
0
0

Is there any difference between these two expressions with regard to what they return?

Get-ADUser -Filter { lastLogon -gt $date }
Get-ADUser -Filter ' lastLogon -gt $date '

Variable Values Lost When Executed via group policy shutdown

$
0
0

We're running windows 2008 R2, powershell v2.

I have a script that runs just fine when I execute it manually in powershell.

If I call the same script from the group policy, shutdown powershell scripts the variables within the script lose their values.

If I shutdown the server the scipt is executed but the values of the variables in the script are lost. There is no looping in the script.

Thanks,

Dan

Viewing all 21975 articles
Browse latest View live


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