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

Jobtrigger at startup

$
0
0

Hello,

Since I migrated from Win 8.1 to 10, job scheduling seems to have changed.

I want to launch a script to read out the data from a 'smart' electricity meter whenever I turn on my pc.

I registered the job as follows:

  • $trigger = New-JobTrigger -AtStartup -RandomDelay 00:00:30
  • Register-ScheduledJob -Trigger $trigger -FilePath C:\leo\Read_SlimmeMeter.ps1 -Name GetSlimmeMeterData

As opposed to Windows 8.1,  Windows 10 no longer executes my script whenever I start my pc from power down.

I need to do a restart to get my script activated.

How can I ensure that the job gets activated after starting the pc from power off?

Thank you!

Leo


Trouble with DDG Filter in O365

$
0
0

Hi,

I have set up a DDG in my org's Office 365 E2 plan, which was intended to include all accounts in the domain (an allstaff mailing address, basically). There is a need to filter a single person off of this list. For the sake of granularity I decided to filter based on "Title". Here's the filter copied from the membership section of the DDg in exchange admin-

((-not(Title -eq 'Trustee')) -and (-not(Name -like 'SystemMailbox{*')) -and (-not(Name -like 'CAS_{*')) -and (-not(RecipientTypeDetailsValue -eq 'MailboxPlan')) -and (-not(RecipientTypeDetailsValue -eq 'DiscoveryMailbox')) -and (-not(RecipientTypeDetailsValue -eq 'PublicFolderMailbox')) -and (-not(RecipientTypeDetailsValue -eq 'ArbitrationMailbox')) -and (-not(RecipientTypeDetailsValue -eq 'AuditLogMailbox')) -and (-not(RecipientTypeDetailsValue -eq 'AuxAuditLogMailbox')))

I set this up with powershell and from what I can tell, the filter is set up correctly.

However, when sending emails to this list, users with Title = Trustee still receive the email.

I have tried this with various other properties like Custom attributes, setting up a security group and adding members to that, and omitting it with a filter in the same manner as above, but none have worked. I must surely be overlooking something simple. Can anyone please help me?

thanks in advance

Importing certificate into Root Store using powershell v 1.0

$
0
0

Hello Experts,

I have a requirement to import one .pfx certificate into personal store & .p7b certificate into root store. 

I have accomplished this using import-pfxcertificate & import-certificate in higher version of PS than 1.0

For achieving the same in v 1.0 i have written the below code.

For .pfx into personal store :

$pfx = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2
$pfx.Import("c:\temp\test.pfx","password", "Exportable,PersistKeySet")
$store = New-Object System.Security.Cryptography.X509Certificates.X509Store("My", "LocalMachine")
$store.open("MaxAllowed")
$store.add($pfx)
$store.close()

This works fine.

For .p7b into root store :

$certs = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2Collection
$certs.Import("c:\temp\test1.p7b")
$store1 = New-Object System.Security.Cryptography.X509Certificates.X509Store("root", "LocalMachine")
$store1.open("MaxAllowed")
$store1.add($certs)
$store1.close()

This doesnt :( 
Getting an error in line "$store1.add($certs)" as below

Cannot convert argument "certificate", with value: "[Subject]
  CN=XXX, DC=YYY, DC=local
[Issuer]
  CN=XXX, DC=YYY, DC=local
[Serial Number]
  XXXX
[Not Before]
  8/14/2015 5:09:43 PM
[Not After]
  8/14/2025 5:19:43 PM
[Thumbprint]
  XXXXXX
", for "Add" to type "System.Security.Cryptography.X509Certificates.X509Certificate2": "Cannot convert the
"System.Security.Cryptography.X509Certificates.X509Certificate2Collection" value of type
"System.Security.Cryptography.X509Certificates.X509Certificate2Collection" to type
"System.Security.Cryptography.X509Certificates.X509Certificate2"."
At line:1 char:1
+ $store1.add($certs)
+ ~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], MethodException
    + FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument

Please help.

Regards,

Prajul Nambiar

PowerShell ISE Freezes after executing WinForms

$
0
0
Hello, I've been having an issue with my PowerShell ISE. I am currently developing a PowerShell script that generates Windows Forms for gathering and displaying data. From what I can tell, the application runs and works great. However, after I execute the code once in the ISE (and close the app/stop execution gracefully); if I leave the ISE idle, for about 10 minutes, the ISE will freeze and I have to crash it with Task Manager. If winform code has not been executed, ISE works fine indefinitely. Thoughts on why my ISE constantly crashes when working on winform based scripts? Thanks.

win32_shadowcopy Unsupported shadow copy context

$
0
0

The result of entering a (Get-WmiObject -list win32_shadowcopy).create("C:\","Backup") command into powershell is 

ReturnValue      : 5
ShadowID         : {00000000-0000-0000-0000-000000000000}

However the ClientAccessible type of win32_shadowcopy is available for creation and accessible in file system after mklink /dWhich makes me feel confused. And i need the non-persistent, auto-release type of shadow copy with full read/write capabilities to be created during this operation... The Backup type satisfyingly meets these requirements. What is the reason for the .create job to end up with such an error?

http://stackoverflow.com/questions/17601354/creating-a-shadow-copy-using-the-backup-context-in-a-powershell was not really helpful while trying to figure out the roots of the issue.

Please, respond. I desperately need your help. Thanks in advance

an script to get list of AD computers & run gpupdate on them

$
0
0

Hello Guys

i need an script that gets the list of all current computers which exists in active directory and stores them in a variable or in a file, so that then we run gpupdate on them using invoke-command cmdlet.

but i am unable to store that list correctly in the $computers variable so that the next command be executed on them without error.

also i couldn't find a correct method to store them in a text file & using get-content

$Computers = Get-ADComputer -filter * | select name


<#
 # i don't know how to create above variable correctly so that be able to use it in following invoke-command
#>

Invoke-Command -ComputerName $computers { gpupdate /force }

  perhaps it is because of the result of the $computers variable which contains the following result:


PS C:\> $Computers = Get-ADComputer -Filter * | select name

PS C:\> $Computers

name                                                                                                                                                
----                                                                                                                                                
2012-TEST                                                                                                                                           
pc1                                                                                                                                                 
pc2                                                                                                                                                 
pc3                                                                                                                                                 

any help please




LDAP query error: the following exception occurred while retrieving member "distinguishedname": "unknown error (0x80005000)"

$
0
0

Hi Guys,

I'm using SCCM OSD taks to run a powershell script to set a computer name, the problem is that getting a list of pc names already taken on the domain is giving me this error: "the following exception occurred while retrieving member "distinguishedname":"unknown error (0x80005000)"", for this line:

$root = New-Object System.DirectoryServices.DirectoryEntry($ldapconn,"username","pass")  -ErrorAction Stop

If a run the script on any computer it will work, even if the machine is not joined to the domain and also firewall is turned on. What could be the reason of this error?

here is the full script:

$destDir = "C:\Temp"
If (!(Test-Path $destDir)) { New-Item -Path $destDir -ItemType Directory -Force |Out-Null}
New-Item C:\Temp\log.txt -type file -force | out-null
#create an array that contains all domain controllers
$dcips = @("10.10.10.10","10.10.10.10","10.10.10.10","10.10.10.10")
#create a variable with the first element of the array
$dc = $dcips[0]
#create a variable that will be used onthe "while" loop
$i = 0
#test if domain controller have connection, if not search for any available from the array
if ((Test-Connection $dc -Quiet) -eq $false){while ( (Test-Connection $dcips[$i] -Quiet)-eq $false ){ $i++;$dc = $dcips[$i]}}"- Domain Controller IP"|out-file C:\Temp\log.txt -append
$dc|out-file C:\Temp\log.txt -append"- Check Connectivity to DC"|out-file C:\Temp\log.txt -append
Test-Connection $dc -Quiet|out-file C:\Temp\log.txt -append
#create connection string
$ldapconn = "LDAP://$dc/DC=subdomain,DC=domain,DC=com""- Review LDAP String"|out-file C:\Temp\log.txt -append
$ldapconn|out-file C:\Temp\log.txt -append
#Create an instance of the DirectoryEntry Class and set the connection values
Try{
$root = New-Object System.DirectoryServices.DirectoryEntry($ldapconn,"username","pass")  -ErrorAction Stop"- Root Variable"|out-file C:\Temp\log.txt -append
$root|out-file C:\Temp\log.txt -append
}
Catch{
 $ErrorMessage = $_.Exception.Message|out-file C:\Temp\log.txt -append
 $FailedItem = $_.Exception.ItemName|out-file C:\Temp\log.txt -append
}

#create an instance of the DirectorySearcher Class
$searcher = New-Object System.DirectoryServices.DirectorySearcher($root)
#set the filter property yo the searcher instance, on this case to search for all computer objects with name pc*cr
$searcher.Filter = "(&(objectClass=computer)(name=pc*cr))"
#set the pagesize property, this is the amount of objetcs returned by the searcher
$searcher.PageSize = 10000"- Searcher Variable"|out-file C:\Temp\log.txt -append
$searcher|out-file C:\Temp\log.txt -append
#create an instance of the ResultCollection Class and run the search of objects in AD
[System.DirectoryServices.SearchResultcollection]$results = $searcher.FindAll()"- Total results received"|out-file C:\Temp\log.txt -append
$results.count|out-file C:\Temp\log.txt -append
#pass only the pc names into a new variable
foreach ($result in $results){$pcnames += $result.properties.name}
#create a regular expression the contains all letters
$pattern = '[a-zA-Z]'
#remove letters from all the results in order to keep only the numbers and make a sort
$n = ($pcnames) -replace $pattern, ''|Sort-Object @{e={$_ -as [int]}}
#create a variable that will be used for the while loop
$y = 1
#while loop to search the next available number from the results
while ($n -contains $y){$y++}
#create the new machine nambe based on the while's result
$OSDComputerName = "PC"+ $y + "CR""- Name Assigned"|out-file C:\Temp\log.txt -append
$OSDComputerName|out-file C:\Temp\log.txt -append
#create a variable of type "Task Sequence"
$TSEnv = New-Object -COMObject Microsoft.SMS.TSEnvironment
#assing the new pc name to this variable
$TSEnv.Value("OSDComputerName") = "$OSDComputerName"

netdom join

$
0
0
How do you use netdom join?! i have google as much as i can. plz help Thx 

LastBootUp Time Script

$
0
0

I have a working script that that produces the results of all the computers with the last Time the machine was rebooted however I want to add a WHERE statement filtering out machines that have not been rebooted in 30 days.  I haven't been able to figure out how to get it to work if it is even possible

Where { $_.LastBootUpTime -lt (Get-Date).AddDays(-30) }

working code below

$computer = Get-ADComputer -Filter * -SearchBase "OU=Desktops,OU=Devices,DC=XX=com" | Select-Object -Expand Name
Get-WmiObject -class Win32_OperatingSystem -computer $computer | Select-Object __SERVER,@{label=’LastBootUpTime’;expression={$_.ConvertToDateTime($_.LastBootUpTime)}
}

Activate Office (2013)

$
0
0

I want to activate office 2013 on remote computers. (KMS & GP are not possible)

Ideally I want to send someone the powershell script to run which would activate locally.

The thing is I don't want the key that's in the script to be visible in plain text. IE I don't want them to open up the script & see the key & use it somewhere else.

All I've found at the moment is this: (which would be fine if I could mask the key somehow)

Activate Office:

cd "<C:\Program Files (x86)\Microsoft Office\Office15>"
 
cscript ospp.vbs /inpkey:"XXXX-XXXX-XXXX-XXXX-XXXX"
cscript ospp.vbs /act
cscript ospp.vbs /dstatus   

Powershell Function Help

$
0
0

Hey guys,

Just coming back to powershell after a bit of a hiatus and can't get my head around what I'm missing here.

I picked up a working function from  https://technet.microsoft.com/en-us/magazine/2009.04.heyscriptingguy.aspx in respect to extracting .cab files.

I'd like to turn this function into something that can accept pipeline input so I can have it run through a list of files but I am unable to get the function to work once I have done this.

Would anyone be able to point me in the right direction?

Thanks.

# script to copy Office 2010 32 Bit Updates to SCCM OSD Package


$cabPath="C:\temp\Office_2010_32bit"
$destination="C:\Temp\Office_2010_32bit_Extracted_MSP"


#Create expand-cab function

Function ConvertFrom-Cab {
    [cmdletbinding()]
    Param(
            [Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelinebyPropertyName=$True)]
            [string[]]$cab,
            [string[]]$destination


        )
{
 $comObject = "Shell.Application"
 Write-Debug "Creating $comObject"
 $shell = New-Object -Comobject $comObject
 if(!$?) { $(Throw "unable to create $comObject object")}
 Write-Debug "Creating source cab object for $cab"
 $sourceCab = $shell.Namespace($cab).items()
 Write-Debug "Creating destination folder object for $destination"
 $DestinationFolder = $shell.Namespace($destination)
 Write-Debug "Expanding $cab to $destination"
 $DestinationFolder.CopyHere($sourceCab)
}

}





$cabs=Get-ChildItem -path $cabpath -recurse -include "*.cab" | % { $_.FullName}

ForEach ($cab in $cabs) {

ConvertFrom-Cab -cab $cab -destination $destination

}



Can somebody verify if this is a bug in WMF 5.0

$
0
0

If you do have WMF 5.0 and any Windows 2008 box with built in powershell (PS 2.0), can you verify that code below does in fact fail after first line please. I tried it and it failed for me 100% of the time on multitude of machines I tried on. It works fine on later versions of WinRM and also when launched from lower versions of client but fails 100% of the time going from PS 5.0 to PS 2.0 for me.

PS C:\Windows\system32> Invoke-Command -ComputerName Windows2008box -ScriptBlock {Write-Output 1; Write-Output 2 }

1

PS C:\Windows\system32> 

How do I use invoke command on remote computer with function from local computer and use its parameters.

$
0
0

I have researched enough to know that I can use:

Invoke-Command -ComputerName <remote host> -ScriptBlock ${funcition:Get-Application} and it will use the default settings. 

I have created a function that works like this

-------------------------- EXAMPLE 1 --------------------------                                                                                            
PS C:\>Get-Application                                                                             
Lists all programs the local computer.                       
-------------------------- EXAMPLE 2 --------------------------
Get-Application -ComputerName <remotecomputer> 
Lists all programs the remote computer.                 
-------------------------- EXAMPLE 3 --------------------------               
PS C:\>Get-Application -AppName Silverlight                                  
Searches the local computer for a program that wildcard matches Silverlight  

Since it takes so long to retrieve the information from the remote computer, and then my computer has to parse it, I want to use invoke-command.

This works and retrieves all applications on the remote computer:

Invoke-Command -ComputerName <remote host> -ScriptBlock ${function:Get-Application}

None of these work:

Invoke-Command -ComputerName <remote host> -ScriptBlock ${function:Get-Application -Name 'Silverlight'}

Invoke-Command -ComputerName <remote host> -ScriptBlock ${function:My-Function(param($AppName) -ArgumentList Silverlight}

I am pretty sure I need to supply an ArgumentList, but can't find clear newby-friendly examples online.  The inline help isn't much help either since it doesn't address using function in ScriptBlock.


James Curtis

How do I add objects to variable without interrupting the pipeline?

$
0
0

So I have a block of code that I want to run against a group of computers (get-adcomputer -filter 'name -like "*trn*"'), but they may not all be turned on.  I want to output a list of the computers that aren't online to a variable and output a list at the end.  I have tried $Obj += $ComputerName but it doesn't become an object.  How can I get this done.  Here is a example of the code.

foreach ($Computer in $Computers)

{

if (Test-Connection -ComputerName $Computer -Count 1 -quiet) {<code to execute> } else { Write-Warning "$Computer is offline" }

}

Instead of writing the warning as it encounters the computer that is offline, I would like to save them all up and write them all out after it has completed them all.  I know I could write the output to a .csv file and then import-csv to get the results, I just know there has to be a better way.

Thanks in advance,


james . Curtis

remove disabled / disconnected user accounts from global address list

$
0
0

HI,

is there a way to remove disabled / disconnected user accounts from showing up in outlook's global address list?  I can't delete the mailboxes yet, but I don't want them to show up in outlook address book for end users.

thanks for any help --


Powershell read from file and run set-userphoto

$
0
0

I am trying to read user and photo name from 1 comma delimited text file.

Then I want to pass the set-userphoto command. 

My cmdlet looks like this:

Get-Content users.txt | Foreach-Object{
   $var = $_.Split(',')   
   Set-UserPhoto "$var[0]" -PictureData ([System.IO.File]::ReadAllBytes("$var[1]"))
}

Problem is "$var[0]" give me both fields when if inside double quotes. So its passing incorrect values to the set user command.

I need this to pass

Set-UserPhoto "user1" -PictureData ([System.IO.File]::ReadAllBytes("user1photo.jpg")) but its going in as Set-UserPhoto "user1,user1photo.jpg" -PictureData ([System.IO.File]::ReadAllBytes("user1,user1photo.jpg"))

Sample input from get-content file is like:

user1,user1photo.jpg

user2,user2photo.gif


How to open a Powershell window from a script with admin rigths?

$
0
0

Hiya

I created this script to extract a report, but I converted into .exe with Power GUI, but when I run it, it runs in CMD and it says "Access denied to D drive" and after running the script in CMD it opens a new powershell window as administrator in blank. What I want is, to open the new powershell windows as admin to avoid "access denied to D drive", but I want the script to run the commands as admin in the new window? what do I need to change?

$PSEnv3 = PowerShell {
Start-Process powershell -Verb RunAs
Get-ADUser -Filter * -SearchBase "OU=Disabled Users by Script,OU=Seguridad Informatica,DC=assist-card,DC=com,DC=ar" |
Select Name,SamAccountName,UserPrincipalName,Description,WebPage,ParentContainer,Notes,Office,Mail |
Export-CSV 'D:\Disabled_Users_Report.csv' -NoType
Import-Module ActiveDirectory
}

I'd really appreciate your help.

Thanks!

Powershell script result for Multiple servers.

$
0
0
Hi...I trying to get output for multiple servers & I have got a script and also looked into this post. I would like get disk space for multiple servers and also would like to get output with each server name...An example of the script I am using mentioned below - 
$Output = "C:\Windows\Temp\ServerInformation.txt"

Write-Output "Total RAM installed" | out-file $Output

Get-WMIObject -class Win32_PhysicalMemory -ComputerName $Servers | Measure-Object -Property capacity -Sum | select @{N="Total Ram(GB)"; E={[math]::round(($_.Sum / 1GB),2)}} | Format-List | out-file $Output -Append
I am planning on running this script in multiple servers and wanted to get an output in txt format with different server names...The above mentioned script & one in the script (wants me to login...which I dont want) is working fine in one server...Any assistance, pls let me know...

VT

Help with create variable for list of commands

$
0
0

I apologize, I am not sure how to explain this clearly.

This is for permissions on Microsoft SharePoint for a site.

This is the command I need to run OVER and OVER again, with the "120000820" to be changed.

$web = Get-SPWeb "https://DOMAINNAME/departments/SUBSITE/12000820"
function AddGroupToSite ($web, $groupName, $permLevel)
{
    $account = $web.SiteGroups[$groupName]
    $assignment = New-Object Microsoft.SharePoint.SPRoleAssignment($account)
    $role = $web.RoleDefinitions[$permLevel]
    $assignment.RoleDefinitionBindings.Add($role);
    $web.RoleAssignments.Add($assignment)
}
AddGroupToSite -web $web -groupName "Limited Access - HRBP J3K" -permLevel "HRB34P"

I have all these sites I need to have the PowerShell script to go through.  I then need to put the function (from the script above) below each line to update permissions.

$web = Get-SPWeb "https://DOMAINNAME/departments/SUBSITE/10300820"
$web = Get-SPWeb "https://DOMAINNAME/departments/SUBSITE/10300821"
$web = Get-SPWeb "https://DOMAINNAME/departments/SUBSITE/10300822"
$web = Get-SPWeb "https://DOMAINNAME/departments/SUBSITE/10030824"
$web = Get-SPWeb "https://DOMAINNAME/departments/SUBSITE/10030831"
$web = Get-SPWeb "https://DOMAINNAME/departments/SUBSITE/10300834"
$web = Get-SPWeb "https://DOMAINNAME/departments/SUBSITE/10030843"
$web = Get-SPWeb "https://DOMAINNAME/departments/SUBSITE/10030844"
$web = Get-SPWeb "https://DOMAINNAME/departments/SUBSITE/10030845"
$web = Get-SPWeb "https://DOMAINNAME/departments/SUBSITE/10030847"
$web = Get-SPWeb "https://DOMAINNAME/departments/SUBSITE/10030850"
$web = Get-SPWeb "https://DOMAINNAME/departments/SUBSITE/10030852"

For me, I believe that I can have the number's set as variable in a CSV or XML to pull from possibly or I can keep the above like it; etc.

I have gone into notepad and copied the line

$web = Get-SPWeb "https://DOMAINNAME/departments/SUBSITE/10300822"
and pasted in the function below it. So I'd do that over and OVER again!  100's of times, getting the next /10300822 from the list, going down the list (the number's aren't in succession).
function AddGroupToSite ($web, $groupName, $permLevel)
{
    $account = $web.SiteGroups[$groupName]
    $assignment = New-Object Microsoft.SharePoint.SPRoleAssignment($account)
    $role = $web.RoleDefinitions[$permLevel]
    $assignment.RoleDefinitionBindings.Add($role);
    $web.RoleAssignments.Add($assignment)
}
AddGroupToSite -web $web -groupName "Limited Access - HRBP J3K" -permLevel "HRB34P"

Thank you.  I apologize that I am not clear on this.  PowerShell is not my strongsuit.

Matt

First days of the month

$
0
0

I have a PowerShell script that I need to run three times a month. The catch is, I need it to run in sequence starting with the first Monday > Wednesday > Friday of each month.  

For example, in February I need the script to run on 2/1, 2/3, and 2/5. But in March the first Monday lands on 3/7, so the script needs to run on 3/7, 3/9, and 3/11.

I'll be using the Task Scheduler to run the script, but there is no logic in the schedule trigger that can identify whether or not the Wednesday/Friday executions are occurring after the first Monday.

At the moment I have some logic to identify the first Monday, Wednesday, and Friday of the month, but I'm in the same boat I was with the TS. Any suggestions?

$Date = Get-Date IF ($Date.Day -lt 7 -and $Date.DayOfWeek -eq "Monday") {}

IF ($Date.Day -lt 7 -and $Date.DayOfWeek -eq "Wednesday") {}

IF ($Date.Day -lt 7 -and $Date.DayOfWeek -eq "Friday") {}


Viewing all 21975 articles
Browse latest View live


Latest Images

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