how to create a list and view in sharepoint 2010 using powershell?
Script to copy folders matching the name of folders in another directory, searching using a portion of the folder name e.g. first 4 characters.
Good afternoon guys,
I am totally new to PowerShell (only discovered it a week or so ago), or scripting in general for that matter, and therefore am finding it very difficult to tailor scripts I have found on the internet to fit my requirements.
If anyone could help me with this, I’d be extremely grateful;
I have two directories containing a lot of folders>subfolders>files. The first (search – called TEST A) directory is where the main body of files are kept – these are a mix of Excel and Email files which are put into folders named with a unique 4 digit number followed by some text e.g. “1000 – Folder123”.
The second directory (destination – called TEST B) contains an empty folders for each unique 4 digit number e.g. “1000”, “1001”, “1003”, “1004”, “1005” etc.
What I would like to do is run a script which looks up all of the folders in the search folder (TEST A) via the 4 digit number, matches it with the corresponding folder in the destination folder (TEST B), creates a new folder called “COPY TEST” in the matched folder in TEST B, and copies the TEST A folder – along with any enclosed files – into this new folder called “COPY TEST”. As an example;
TEST A (FOLDER TO BE SEARCHED) TEST B (FOLDERS FOR INFO TO BE COPIED INTO)
E.g - C:\TEST A\1000 - Folder123 E.g - C:\TEST B\1000
"1000 - Folder123" "1000"
"1001 - Folder446" "1001"
"1002 - Folder789" "1002"
"1003 - Folder332" "1003"
Once the script had been successfully run, the updated TEST B folder would now look something like this:
"C:\TEST B\1000\COPY TEST\1000 - Folder123"
It would also be good if there was something in place to make sure no files were overwritten and that additional copies be made instead.
I hope my explanation is clear enough, although if anyone needs any further clarification I'll do my best to provide this.
Thank you all in advance for your help in this matter.
Regards,
Tom
WinRM Remote Powershell session (wsmprovhost.exe) not exiting after calling Remove-PSSession on Server 2008 R2
The company I work for has a powershell based deployment process for deploying a web application to many internal web and database servers. We use remote powershell sessions and winrm to run an installation script on the target computer after deploying a zip file, and while this works beautifully on most servers, we have one problem child.
The part that has me very confused is why this same script runs fine on 4 other servers but not this one. I'm not sure what the OS version is on the others where it is working, but I can find out if that is relevant.
We are opening a new session, running an installation script, and afterwards are following it with a call to Remove-PSSession -Session $remoteSession, but wsmprovhost.exe never terminates. It will stay running for days until we reboot the server or restart the WinRM service. After we hit our five concurrent session limit, any attempts to open a new session as the domain account we use to run all this, we get an error saying we've hit our limit for open sessions.
I've done some searching and have found many suggestions, which have all turned out to be dead ends. These two posts are similar to my issue, but in the end didn't yield any fixes:
- http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/e17f3665-4d0b-445b-9ce6-f42013ceaffd
- http://social.technet.microsoft.com/Forums/en-US/winserverpowershell/thread/99ea167d-fde3-4ccb-b1ed-0a425980cd62
Version Info for the target box:
PS C:\Windows\system32> $PSVersionTable Name Value ---- ----- CLRVersion 2.0.50727.5466 BuildVersion 6.1.7601.17514 PSVersion 2.0 WSManStackVersion 2.0 PSCompatibleVersions {1.0, 2.0} SerializationVersion 1.1.0.1 PSRemotingProtocolVersion 2.1
Version Info for the box that is initiating the connection:
Name Value ---- ----- CLRVersion 2.0.50727.4234 BuildVersion 6.0.6002.18111 PSVersion 2.0 WSManStackVersion 2.0 PSCompatibleVersions {1.0, 2.0} SerializationVersion 1.1.0.1 PSRemotingProtocolVersion 2.1
Some other tid-bits about our environment:
- This is an internal QA server that we use to test our software.
- The deployment is initiated via a powershell script, which is run as a domain account. Both boxes are on the same domain. There is a windows service (Cruise Control) running on the source box as a domain account, and it spawns powershell.exe with appropriate parameters to start the process.
- The source server that initiates the deployment is server 2008 and the box we are deploying to is 2008 R2
- When we hit our concurrent session limit, I went to the target server and enumerated open shells, and this is what it told me:
PS C:\Windows\system32> Get-WSManInstance -ConnectionURI 'http://localhost:5985/wsman' -ResourceURI shell -Enumerate rsp : http://schemas.microsoft.com/wbem/wsman/1/windows/shell lang : en-US ShellId : FB73A939-3CB6-415C-AB55-2F7B2B72E6BC ResourceUri : http://schemas.microsoft.com/powershell/Microsoft.PowerShell Owner : MYDOMAIN\CruiseControl ClientIP : 10.68.82.225 IdleTimeOut : PT180.000S InputStreams : stdin pr OutputStreams : stdout ShellRunTime : P4DT12H37M58S ShellInactivity : P4DT12H23M19S MemoryUsed : 60MB ChildProcesses : 0 rsp : http://schemas.microsoft.com/wbem/wsman/1/windows/shell lang : en-US ShellId : ECD72634-20F0-49BC-8075-59D306F696BE ResourceUri : http://schemas.microsoft.com/powershell/Microsoft.PowerShell Owner : MYDOMAIN\CruiseControl ClientIP : 10.68.82.225 IdleTimeOut : PT180.000S InputStreams : stdin pr OutputStreams : stdout ShellRunTime : P4DT12H7M55S ShellInactivity : P4DT11H53M17S MemoryUsed : 61MB ChildProcesses : 0 rsp : http://schemas.microsoft.com/wbem/wsman/1/windows/shell lang : en-US ShellId : CF934340-34AF-48E1-ACCE-3CBE7DF1DFC4 ResourceUri : http://schemas.microsoft.com/powershell/Microsoft.PowerShell Owner : MYDOMAIN\CruiseControl ClientIP : 10.68.82.225 IdleTimeOut : PT180.000S InputStreams : stdin pr OutputStreams : stdout ShellRunTime : P4DT11H52M53S ShellInactivity : P4DT11H38M16S MemoryUsed : 59MB ChildProcesses : 0 rsp : http://schemas.microsoft.com/wbem/wsman/1/windows/shell lang : en-US ShellId : C8A1C9E4-3818-490E-B1FF-E2D4C7B8716C ResourceUri : http://schemas.microsoft.com/powershell/Microsoft.PowerShell Owner : MYDOMAIN\CruiseControl ClientIP : 10.68.82.225 IdleTimeOut : PT180.000S InputStreams : stdin pr OutputStreams : stdout ShellRunTime : P4DT11H37M52S ShellInactivity : P4DT11H23M12S MemoryUsed : 61MB ChildProcesses : 0 rsp : http://schemas.microsoft.com/wbem/wsman/1/windows/shell lang : en-US ShellId : A1420013-FF1F-4C68-A198-A2C0C7448B0C ResourceUri : http://schemas.microsoft.com/powershell/Microsoft.PowerShell Owner : MYDOMAIN\CruiseControl ClientIP : 10.68.82.225 IdleTimeOut : PT180.000S InputStreams : stdin pr OutputStreams : stdout ShellRunTime : P4DT12H22M57S ShellInactivity : P4DT12H8M21S MemoryUsed : 61MB ChildProcesses : 0
This the part of the script that is supposed to open and close connections. This executes with $ErrorActionPreference = 'Stop'.
C:\Windows\system32\net.exe use /delete /y $Config.Deployment.ShareToDeployTo C:\Windows\system32\net.exe use $Config.Deployment.ShareToDeployTo $Config.Deployment.RemoteUserPassword "/USER:$($Config.Deployment.RemoteUserName)" if (Test-Path $destinationZipPathAsShare) { Remove-Item -Force $destinationZipPathAsShare } if (Test-Path $destinationUnzipDirAsShare) { Remove-Item -Recurse -Force $destinationUnzipDirAsShare } Copy-Item -Path $DeploymentZipFile -Destination $destinationZipPathAsShare if ($Config.Deployment.RemoteUserName) { $password = ConvertTo-SecureString -AsPlainText $Config.Deployment.RemoteUserPassword -Force $credential = New-Object System.Management.Automation.PSCredential -ArgumentList $Config.Deployment.RemoteUserName,$password $remoteSession = New-PSSession $Config.Deployment.ComputerToDeployTo -Credential $credential -UseSSL } else { $remoteSession = New-PSSession $Config.Deployment.ComputerToDeployTo } try { Invoke-Command ` -Session $remoteSession ` -ScriptBlock { param ($exe,$out) & $exe $('-o'+$out) } ` -ArgumentList @($destinationZipPathAsLocal,$destinationUnzipDirAsLocal) Remove-Item -Force $destinationZipPathAsShare Copy-Item -Path $Config.BranchSed -Destination $destinationBranchSedAsShare Copy-Item -Path $Config.Deployment.ClientLogo -Destination $destinationClientLogoAsShare Copy-Item -Path $Config.Deployment.ReportsLogo -Destination $destinationReportsLogoAsShare $installScriptArgs = New-Object "System.Collections.Generic.List[string]" $installScriptArgs.Add($destinationInstallScriptAsLocal) $installScriptArgs.Add($Config.EnvironmentName) $installScriptArgs.Add($Config.Deployment.DeploymentDirAsLocal) $installScriptArgs.Add($Config.Deployment.WebsitesDirAsLocal) $installScriptArgs.Add($Config.Deployment.ComputerToDeployPortalTo) $installScriptArgs.Add($Config.Deployment.LMSContentDirectory) $installScriptArgs.Add($destinationBranchSedAsLocal) $installScriptArgs.Add($destinationClientLogoAsLocal) $installScriptArgs.Add($destinationReportsLogoAsLocal) Invoke-Command ` -Session $remoteSession ` -ScriptBlock { param ($script,$a1,$a2,$a3,$a4,$a5,$a6,$a7,$a8) . $script -SiteName "$a1" -DeploymentsFolder "$a2" -WebsitesFolder "$a3" -PortalVpcPath "$a4" -LMSContentPath "$a5" -BranchSed "$a6" -ClientLogo "$a7" -ReportsLogo "$a8" } ` -ArgumentList $installScriptArgs } finally { Remove-PSSession -Session $remoteSession }
The first Invoke-Command call here is self extracting archive created with 7-Zip. The second is a call to our installation script.
Sorry for the penultimate post, and thanks in advance for any advice/help. You guys rock!
nick
Create proxy email address and set it as the primary email (bulk) - Office 365 - Powershell
(1) i would like to basically create a proxy email address for every user by taking their existing email and simply changing the domain. so for example, bob@whatever.com would have proxy bob@whatever2.com
(2) i would then like a separate step to basically change the primary email. so bob@whatever2.com becomes the primary.
i need to do this in powershell because there are a ton of users.
i found this for (1):
$users = Get-Mailbox foreach ($a in $users) {$a.emailaddresses.Add("smtp:$($a.alias)@<new domain name>")} $users | %{Set-Mailbox $_.Identity -EmailAddresses $_.EmailAddresses}
but it seemed a bit dated and i was unsure.
*edit* ok that worked great actually, so how do i change the primary email address now?
How to export user membeship and Attribute values to CSV
Hi
I have these simple script to pull the attribute values:
import-module ActiveDirectory Get-ADUser -filter {objectclass -eq "user"} -Properties extensionattribute5| select name, extensionattribute1 | Export-Csv Attributes_Result.csv
I need to add the user membership to these report on another column.
How can I do this?
Maelito
Maelito
Excluding from Convert to Html
Good afternoon, I am using a powershell script to run a query on sql and grab the results and then save them to html. The problem I am running into is that in addition to the fields I need it's adding hidden fields such as - RowError, RowState, Table, ItemArray, HasErrors. I want to only ConvertTo-HTML the two fields I need. If I run the powershell with write host before its converted to html I get all the proper data but when it runs through the convert to html the hidden fields show up. I just want to remove them but have yet to figure out how. Code block below to give you a example.
##setup data source $dataSource = "localhost" ##SQL instance name $database = "DBAMonitoring" ##Database name $sqlCommand = "exec usp_MyReport" ##The T-SQL command to execute $TableHeader = "My SQL Report" ##The title of the HTML page $OutputFile = "C:\MyReport.htm" ##The file location ##set HTML formatting $a = @"<style> BODY{background-color:white;} TABLE{border-width: 1px; border-style: solid; border-color: black; border-collapse: collapse; } TH{border-width: 1px; padding: 0px; border-style: solid; border-color: black; background-color:#C0C0C0 } TD{border-width: 1px; padding: 0px; border-style: solid; border-color: black; background-color:white }</style>"@ $body = @"<p style="font-size:25px;family:calibri;color:#ff9100"> $TableHeader</p>"@ ##Create a string variable with all our connection details $connectionDetails = "Provider=sqloledb; " +"Data Source=$dataSource; " +"Initial Catalog=$database; " +"Integrated Security=SSPI;" ##Connect to the data source using the connection details and T-SQL command we provided above, and open the connection $connection = New-Object System.Data.OleDb.OleDbConnection $connectionDetails $command = New-Object System.Data.OleDb.OleDbCommand $sqlCommand,$connection $connection.Open() ##Get the results of our command into a DataSet object, and close the connection $dataAdapter = New-Object System.Data.OleDb.OleDbDataAdapter $command $dataSet = New-Object System.Data.DataSet $dataAdapter.Fill($dataSet) $connection.Close() ##Return all of the rows and pipe it into the ConvertTo-HTML cmdlet, and then pipe that into our output file $dataSet.Tables | Select-Object -Expand Rows | ConvertTo-HTML -head $a –body $body | Out-File $OutputFile
I need to know if the Remote Desktop Connection is a active (determine Console / RDP session)
I thought that it is easy to find out in PowerShell if I am currently locally connected to the desktop (console) or trough Remote Desktop Connection. But it is not easy. I cannot find this information in WMI and also I cannot find some easy solution on the internet so I am asking here ;-). Please san somebody help me?
At this moment I found only two possibilities but they are not good.
First possibility is use Qwinsta. The problem is that Qwinsta is available only on the server operating systems.
Second possibility is use Terminal Services Module - http://psterminalservices.codeplex.com/.
Please is there easier solution? I just want to know if the session where the PowerShell script is running is RDP or Console. Thank you.
Connecting to remote powershell using C# development
Hi guys,
I'm trying to use C# to connect to a powershell on a remote server,
here is the code:
string liveIDConnectionUri = "https://vm-milad/powershell";string schemaUri = "http://schemas.microsoft.com/powershell/Microsoft.Exchange"; SecureString SecPass = new SecureString();string password = "Qwert..";foreach (char c in password) { SecPass.AppendChar(c); } PSCredential ali = new PSCredential("mcmilad\administrator", SecPass);//WSManConnectionInfo connectionInfo = new WSManConnectionInfo(); WSManConnectionInfo connectionInfo = new WSManConnectionInfo(new Uri(liveIDConnectionUri),schemaUri,ali); connectionInfo.SkipCNCheck = true; connectionInfo.SkipRevocationCheck = true; connectionInfo.SkipCACheck = true; connectionInfo.AuthenticationMechanism = AuthenticationMechanism.Basic; using (RunspacePool runspace = RunspaceFactory.CreateRunspacePool(1, 2, connectionInfo)) { runspace.Open(); }
and here is the WinRM setting on the remote server:
Allow unencrypted traffic : true
Basic authentication : true
By the way, I have already ran winrm /quickconfig and I have configured listeners for winrm as well.
but it ends un with "Access denied" error, any ideas?
Include 'extra' properties in output
Hi,
I'm looking to get a list of log on as service accounts on remote computers. I can output the service names and accounts but is there any way to output the server name etc ($SQLInstance.SQLInst and $SQLInstance.SQLNamed in the code below) so I can differentiate between them?
Here is my work in progress:
Thanks.# Import list of Servers
$SIList=IMPORT-CSV 'C:\PSH Scripts\SQL Related\SQL_Instances.csv' # Step through Each Item in the List foreach ($SQLInstance in $SIList) { write-host $SQLInstance.SQLInst $SQLInstance.SQLNamed # Get Service Acounts Info $report += Get-WMIObject Win32_Service -ComputerName $SQLInstance.SQLInst | Where-Object{$_.name -like '*SQL*'} | Sort-Object -Property StartName | select Name, StartName } $report | convertto-html | out-file 'C:\PSH Scripts\SQL Related\SQL_Instances.html'
How to delete an element from XML embedded in WMI
I have an xml embedded in WMI that contains the following.
<?xml version="1.0" encoding="utf-16"?><UpdateXML xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" Name="SMS_SoftwareUpdate" LocaleId="1033"><UpdateXMLDescriptionItems><UpdateXMLDescriptionItem PropertyName="ArticleID" UIPropertyName=""><MatchRules><string>KB123456</string><string>KB121337</string><string>KB121338</string><string>KB121339</string><string>KB121334</string><string>KB121331</string><string>KB121330</string><string>KB1213333</string><string>KB12133799</string><string>KB121337</string></MatchRules></UpdateXMLDescriptionItem><UpdateXMLDescriptionItem PropertyName="UpdateLocales" UIPropertyName=""><MatchRules><string>'Locale:9'</string></MatchRules></UpdateXMLDescriptionItem><UpdateXMLDescriptionItem PropertyName="_Product" UIPropertyName=""><MatchRules><string>'Product:b86cf33d-92ac-43d2-886b-be8a12f81ee1'</string><string>'Product:83aed513-c42d-4f94-b4dc-f2670973902d'</string><string>'Product:00b2d754-4512-4278-b50b-d073efb27f37'</string><string>'Product:c755e211-dc2b-45a7-be72-0bdc9015a63b'</string></MatchRules></UpdateXMLDescriptionItem><UpdateXMLDescriptionItem PropertyName="IsSuperseded" UIPropertyName=""><MatchRules><string>false</string></MatchRules></UpdateXMLDescriptionItem><UpdateXMLDescriptionItem PropertyName="_UpdateClassification" UIPropertyName=""><MatchRules><string>'UpdateClassification:0fa1201d-4330-4fa8-8ae9-b877473b6441'</string></MatchRules></UpdateXMLDescriptionItem><UpdateXMLDescriptionItem PropertyName="_Company" UIPropertyName=""><MatchRules><string>'Company:56309036-4c77-4dd9-951a-99ee9c246a94'</string></MatchRules></UpdateXMLDescriptionItem></UpdateXMLDescriptionItems></UpdateXML>
I have a text file that contains a list of KB numbers that I want to delete from the above XML
Text File contains;
KB13579
KB121334
KB121331
How can I delete the <string> elements from the above XML that match the KB numbers in the text file
I 'm using the below but it is not working giving this error at the bold section of the code.
The error is:
Cannot convert argument "0", with value: "KB13579", for "RemoveChild" to type "System.Xml.XmlNode": "Cannot convert
the "KB13579" value of type "System.String" to type "System.Xml.XmlNode"."
At C:\temp\pstest3.ps1:32 char:29
+ ($xml.SelectSingleNode("/UpdateXML/UpdateXMLDescript ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [], MethodException
+ FullyQualifiedErrorId : MethodArgumentConversionInvalidCastArgument
POWERSHELL CODE BELOW:
Import-Module "E:\SMS\AdminConsole\bin\ConfigurationManager.psd1" $SiteCode = "CAS" #"KB121337" $ADRTarget = "TESTADR" write-output $ADRTarget $IncludeKBs = (Get-Content C:\temp\KBArticle.txt) $adrs = Get-CMSoftwareUpdateAutoDeploymentRule foreach ($adr in $adrs) {if ($adr.name -eq $ADRTarget) {$xml = New-Object XML $xml.LoadXml($adr.UpdateRuleXML) $ADRkbs = $xml.selectnodes("/UpdateXML/UpdateXMLDescriptionItems/UpdateXMLDescriptionItem[@PropertyName='ArticleID']") foreach ($UpdateXMLDescriptionItemNode in $ADRKBs) {$stringNodeList = $UpdateXMLDescriptionItemNode.selectNodes("MatchRules/string")} #Delete KB's in KBlist from ADR so we start fresh Write-Output "We will now test if we have existing KB's in ADR and delete if found" foreach ($includekb in $includekbs) {Write-Output "Now we are going to delete this Kb: " $IncludeKB foreach ($stringNode in $stringNodeList) {If ($stringnode.get_innerXml() -eq $IncludeKB) {Write-Output "Found the KB will now delete: " $stringnode.get_innerXml() $xmlinput = $xml.CreateElement("string") $xmlinput.InnerText = $IncludeKB ($xml.SelectSingleNode("/UpdateXML/UpdateXMLDescriptionItems/UpdateXMLDescriptionItem[@PropertyName='ArticleID']")).RemoveChild($xmlinput) | Out-Null } } }
Listing all the patches/updates installed in Windows machine
Hi All
I want a script to list all the patches/updates installed in my PC. I tried the below script but it does not give me complete list of patches [SQL, Visual Studio, some Office patches are not listed]
$updateSearcher = new-object -com "Microsoft.Update.Searcher"
$totalupdates = $updateSearcher.GetTotalHistoryCount()
$patchList=$updateSearcher.QueryHistory(1,$totalupdates)
Please let me know if there is any way to achieve this.
Regards Ram
Get-GPOReport Remote PowerShell Session
Hello,
I have a custom PowerShell configuration (PSSessionConfiguration w/ Startup Script) to allow some folks the ability to run a subset of cmdlets from a remote session. This has been working great and I wanted to extend the functionality to incorporate the Get-GPOReport cmdlet. So as I have in the past, I added this cmdlet to my $allowedCmdlets array in the startup script for this session configuration. When I enter a remote session under this configuration and execute the cmdlet with the -ReportType parameter as "Xml" (Get-GPOReport -ReportType Xml) I get the following error:
Operation is not valid due to the current state of the object.
+ CategoryInfo :
+ FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.GroupPolicy.Commands.GetGpoReportCommand
I can run the same cmdlet with the -ReportType parameter as "Html" (Get-GPOReport -ReportType Html) and it works like a champ. I have a feeling the start up script for the session configuration is limiting too much and preventing the XML output from the Get-GPOReport cmdlet to be displayed. Not sure though.
Can anyone help me work through this, please?
PSSessionConfiguration Startup Script:
##--LOAD SESSION MODULES--## Import-Module ActiveDirectory Import-Module GroupPolicy ##--RESTRICT ACCESS TO ALL CMDLETS, VARIABLES, APPS FIRST--## Foreach ($command in Get-Command) {$command.Visibility = "private"} Foreach ($variable in Get-Variable) {$variable.Visibility = "private"} $ExecutionContext.SessionState.Applications.Clear() $ExecutionContext.SessionState.Scripts.Clear() $ExecutionContext.SessionState.LanguageMode = "NoLanguage" $InitialSessionState = [Management.Automation.Runspaces.InitialSessionState]::CreateRestricted("RemoteServer") Foreach ($proxy in ($InitialSessionState.Commands | Where {$_.Visibility -eq "Public"})) { $cmdlet = Get-Command -CommandType cmdlet -ErrorAction SilentlyContinue $proxy.Name If ($cmdlet) { $alias = Set-Alias "$($proxy.Name)" "$($cmdlet.ModuleName)\$($cmdlet.Name)" -PassThru $alias.Visibility = "Private" } Set-Item "function:global:$($proxy.Name)" $proxy.Definition } ##--GRANT ACCESS TO SPECIFIC CMDLETS--## $allowedCmdlets = @("Get-ADUser", "Get-ADGroup", "Get-ADGroupMember", "Get-GPO", "Get-GPOReport") Get-Command | Where-Object {$allowedCmdlets -contains $_.Name} | ForEach-Object {$_.Visibility = "Public"}
get-website : Could not load file or assembly error
I have several web servers where I use Powershell to perform inventory tasks.
Recently, two of my servers started giving me this error when they try to execute get-website in a Powershell script that is run as a scheduled task:
get-website : Could not load file or assembly'Microsoft.PowerShell.Commands.Utility' or one of its dependencies. The system
cannot find the file specified.
At E:\scripts\DetailedInv.ps1:61 char:21
+ ForEach($website in get-website){
+ ~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (:) [Get-Website], FileNotFoundExc
eption
+ FullyQualifiedErrorId : System.IO.FileNotFoundException,Microsoft.IIs.Po
werShell.Provider.GetWebsiteCommand
These are windows 2008 R2 X64 servers that are fully patched.
The strange thing is, I use this same script on all my web servers, but these two generate this error. If I open the script in the Powershell ISE and execute it on the problem server, the script runs successfully, but if I right click on the script and choose "Run with PowerShell" the above error appears and no information in generated.
Any idea what could be causing this?
Delete 2nd level and above (3rd,4th,etc) subfolders and files with exclusion based on older than
Hello everyone !
I have the following folder structure:
-Projects -->(root folder)
-Project1 (2nd level subfolder)
-Project2 (2nd level subfolder)
-Project3 (2nd level subfolder)
-Project4 (2nd level subfolder)
- etc` ..
Goals:
1) I'd like to keep ALL 1st level folders (project1,2,3,4.....etc) no matter what.
2) Delete only the contents of the project folders (files+subfolders in all depths) ONLY if the content is older than 14 days, in no situation should the 1st level folders be deleted, just their contents based on older than 14 days.
3) The ability to exclude certain 2nd level subfolder projects/3rd level subfolders paths inside projects.
I am using a test folder to run the tests:
- C:\Drivers\Win (as root folder)
- AUDIO (2nd level subfolder)
- DISPLAY6 (2nd level subfolder)
- INTELINF (2nd level subfolder)
- MONITOR (2nd level subfolder)
trying to run the following code:
cls $ErrorActionPreference = 'Stop' $root = 'C:\Drivers\win' $ExcludePaths = '\AUDIO', '\INTELINF\infinst_autol' $date = (Get-Date).AddDays(-14) get-childitem $root | where { $_.PsIsContainer } | get-childitem -recurse | % { $found = $false foreach ($path in $ExcludePaths) {if ($found = $found -or ($_.FullName -like "$root$path\*")) {break}} if (!$found) {$_} } | where { $_.LastWriteTime -lt $date } | Remove-Item -Recurse -WhatIf
results in 2 issues:
1. $ExcludePaths only excludes the 1st mentioned exclusion and ignores the 2nd (from the example above -\AUDIO gets excluded, \INTELINF or \INTELINF\infinst_autol does not get excluded and being deleted.
2. $ExcludePaths is unable to exclude 3rd level subfolders such as: \AUDIO\Folder , only manages to exclude the 2nd level subfolder \AUDIO .
Any chance you can help out by fixing/rewriting the script ??
Thanks in advance :-)
I want filter Get-ADComputer -Properties PasswordLastSet by date.
I have a functional script that grabs the Get-ADComputer -Properties PasswordLastSet and displays the computer name and date. What I want is to filter out systems by the date, so I only see systems 30 days older than the date run. Here is what I have that works:
$computers = get-content C:\Scripts\computerlist.txt
ForEach ($comp in $computers)
{
Get-ADComputer $comp -Properties PasswordLastSet | Select-Object Name,PasswordLastSet | Export-CSV C:\Scripts\PasswordLastSet.csv -append -force -NoTypeInformation
}
How do I filter based on the results (date) of PasswordLastSet?
Please mark my post as helpful or the answer or better yet.... both! :) Thanks!
WMIC Powershell Call TriggerSchedule Error
Setting AD user paths
I am using server 2008R2 with the active directory module. I want to call the new-aduser cmdlet to add a user to a domain controller called "Network Users". I am currently writing the following:
new-aduser -name "John" -path"dc=Network Users,dc=dingis,dc=local"
The domain is dingis.local
I get no error, my prompt just turns into this: >>
It looks like powershell is waiting for more arguments but I have no idea what else it wants. Thank you in advance.
NOTE. If I type:
new-aduser -name "John"
A new user is successfully created in the "Users" domain controller
Issue with foreach and Get-ADUser -Filter
I think I'm having an issue with variable type handling. Can someone explain why the first block of code works, but the 2nd doesn't?
$studentsList = ipCSV C:\studentsSummer.csv foreach ($student in $studentsList) { $emailAddress = $null $emailAddress = $student.emailacct $tmpStudent = $null $tmpStudent = Get-ADUser -Filter {mail -eq $emailAddress} Add-ADGroupMember $student.crn -Members $tmpStudent }
$studentsList = ipCSV C:\studentsSummer.csv foreach ($student in $studentsList) { $tmpStudent = $null $tmpStudent = Get-ADUser -Filter {mail -eq $student.emailacct} Add-ADGroupMember $student.crn -Members $tmpStudent }
Assume the CSV is like:
EMAILACCT,CRN,COURSE Kimberly.Anne@fake.biz,CRN2,5 Jim.Abele@fake.biz,CRN1,5 Paul.Atterman@fake.biz,CRN1
I've tried several varatoins with single and double quotes as well as ([string]$student.emailacct) but i can't seem to crack this one today.
EDIT:
oops, the error would have been helpful:
Get-ADUser : Property: 'emailacct' not found in object of type: 'System.Management.Automation.PSCustomObject'. At line:3 char:29+ $tmpStudent = Get-ADUser <<<< -Filter {mail -eq $student.emailacct}+ CategoryInfo : InvalidArgument: (:) [Get-ADUser], ArgumentException+ FullyQualifiedErrorId : Property: 'emailacct' not found in object of type: 'System.Management.Automation.PSCusto mObject'.,Microsoft.ActiveDirectory.Management.Commands.GetADUser Add-ADGroupMember : Cannot validate argument on parameter 'Members'. The argument is null or empty. Supply an argument that is not null or empty and then try the command again. At line:4 char:44 + Add-ADGroupMember $student.crn -Members <<<< $tmpStudent+ CategoryInfo : InvalidData: (:) [Add-ADGroupMember], ParameterBindingValidationException+ FullyQualifiedErrorId : ParameterArgumentValidationError,Microsoft.ActiveDirectory.Management.Commands.AddADGrou pMember
Mike Crowley | MVP
My Blog --
Planet Technologies
Trouble installing SMTP on Server 2012 Standard Core
I asked this on the windows 2012 forum, where I was advised to ask this on this form.
I have a Server core instance I am administrating via PowerShell remoting. It has IIS and Sql 2008R2 functioning correctly and I want to add SMTP. I've verified its running 2012 standard edition:
PS C:\Users\JDearing\Documents> CimInstance Win32_OperatingSystem|select caption caption ------- Microsoft Windows Server 2012 Standard
I try to install SMTP with the following command:
Add-WindowsFeature SMTP-Server,RSAT-SMTP -source:wim:d:\sources\install.wim:1 -Debug -Verbose
It fails with:
Add-WindowsFeature : The request to add or remove features on the specified server failed. Installation of one or more roles, role services, or features failed. The source files could not be downloaded. Use the "source" option to specify the location of the files that are required to restore the feature. For more information on specifying a source location, see http://go.microsoft.com/fwlink/?LinkId=243077. Error: 0x800f0906+ CategoryInfo : InvalidOperation: (@{Vhd=; Credent...Name=localhost}:PSObject) [Install-WindowsFeature], Exception+ FullyQualifiedErrorId : DISMAPI_Error__Cbs_Download_Failure,Microsoft.Windows.ServerManager.Commands.AddWindowsFeatureCommand DEBUG: Call to GetAlterationRequestState provider method failed with error(s): The request to add or remove features on the specified server failed. Installation of one or more roles, role services, or features failed. The source files could not be downloaded. Use the "source" option to specify the location of the files that are required to restore the feature. For more information on specifying a source location, see http://go.microsoft.com/fwlink/?LinkId=243077. Error: 0x800f0906
The ISO is mounted to the D: drive and the image for 2012 standard server cor is indeed 1:
PS C:\Users\JDearing\Documents> Get-windowsimage –imagepath d:\sources\install.wim Index : 1 Name : Windows Server 2012 SERVERSTANDARDCORE Description : Windows Server 2012 SERVERSTANDARDCORE Size : 7,178,226,690 bytes Index : 2 Name : Windows Server 2012 SERVERSTANDARD Description : Windows Server 2012 SERVERSTANDARD Size : 11,999,889,351 bytes Index : 3 Name : Windows Server 2012 SERVERDATACENTERCORE Description : Windows Server 2012 SERVERDATACENTERCORE Size : 7,172,264,095 bytes Index : 4 Name : Windows Server 2012 SERVERDATACENTER Description : Windows Server 2012 SERVERDATACENTER Size : 11,995,265,169 bytesWhat am I doing wrong?
Enumerate named parameters
Hi All,
I want to write a small function, which will be put in a module, that needs to be called by all scripts to track when which script has run, version,by who and a link to the transcript file.
Now I want to add listing all values for the named parameters when the script is called. My initial idea was, I pass $args, loop thru all parameters and done..
But what I found out is that as soon as I put a param definition (ex. param($url,$site) ) in a script the $args collection remains empty.
Basically the question is, is it possible and how can you loop thru all named parameters in a script without knowing the names?
rgds,
Bart