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

How to get parent container path of the AD user object?

$
0
0

Hi All,

I would like to export all users parent ou -- can someone help me on this.

I tried with below ps command but got full dn.

get-aduser -filter *| select samaccountname, distinguishedname

is there something like parentcontainer??

 

Thanks for the help


Thanks, Sunil Gupta Sunilgupta@sunilgupta.com


How to get currently-selected cell values in excel with PowerShell

$
0
0

It's easy to open up a given excel spreadsheet:

$xl = New-Object -ComObject "Excel.Application"
$wb = $xl.Workbooks.open("C:\Users\xxxxxxx\Desktop\excel.xlsx")

Make the spreadsheet visible to the user:

$xl.visible = $true

And even select the current sheet they are currently looking at:

$ws = $wb.ActiveSheet

But is it possible to get the cells that the user has currently selected, in that sheet?

$cells = $ws.BlackBoxFunction.GetCells.Please?

or

$cells = $ws.ActiveCells


Because I'm not seeing a way to do so. Even after exploring the $ws and $wb objects with the Get-Member dealio. Any ideas?


Powershell command to show IIS Application Pool?

$
0
0

Hello Community

    Using Powershell 2.0 you can use Get-SPServiceApplicationPool to display
the SharePoint Service Application Pools.

    Is there a PowerShell command to show IIS Application Pools?

    Thank you
    Shabeaut

how to use powershell to search the whole forest for active computers

$
0
0

currently i have a command to find computers account for the domain

current query only retrieve records from the same domain

how can i expand it to the whole forest as it contains multiple domain?

below is the powershell script use

$d = [DateTime]::Today.AddDays(-30); Get-ADComputer -Filter 'PasswordLastSet -ge $d' -Properties PasswordLastSet,operatingsystem,CanonicalName | select Name,PasswordLastSet,operatingsystem,CanonicalName | export-csv c:\computerrecords.csv

This might work, but please let me know what would be the real way to do this?

$
0
0
# For any given "Morning Action Time" this script might test whether the current time is
# within a set number of minutes--$MinutesTimeInterval--before or after the current time
# Use: in a larger script that is fired by Task Scheduler at 10 minute intervals all day
# Once per morning, at a set "Morning Action Time", the script can fire other actions, 
# e.g., send an email or something
$Now=Get-Date
[INT]$MinutesTimeInterval= 5
$MorningActionTime='14:50'
$CurrentDiff = New-TimeSpan $Now $MorningActionTime
[INT]$AbsCurrentDiff = $CurrentDiff.TotalMinutes
#Write-Host 'Time of Day is ' $Now.TimeOfDay
#Write-Host 'Difference-in Minutes-between Now and MorningSendTime is: ' $AbsCurrentDiff
IF ($AbsCurrentDiff -lt 0) {$AbsCurrentDiff *=-1 } # Is there an easier way to return Absolute Value?
IF ($AbsCurrentDiff -le $MinutesTimeInterval)
  {Write-Host Within 5 minutes, either way, of Morning Send Time so...Do some stuff}
ELSE #IF (-not($AbsCurrentDiff -le $MinutesTimeInterval))
  {Write-Host Farther than 5 minutes away, either way, from Morning Send Time so... Do nothing}
Just began fooling with PowerShell last week and, as I am probably demonstating here, I don't know the language very well yet.  Would someone be kind enought to shread this up as needed and let me know how to make it a little cleaner/prettier?

HomeCookN

Enable Audit for C:\Windows

$
0
0

Please let me know how to enable Auditing for C:\Windows via Powershell or thru GPO? Running Windows 2008 SP2 32 bit.

Here's the Code I have compiled but errors out for Windows folder only (Below script is run as Domain Admin):

$Folders = "C:\Windows", "C:\Temp" , "C:\Another"

Foreach ($Folder in $Folders) {

Write-Host "" # Empty line
Write-Host "Applying Auditing for folder", $Folder
Write-Host "" # Empty line

$ACL = Get-ACL $Folder

# Set Auditing for Success event for above Folders for EVeryone group
$PermAudited = "Delete, DeleteSubdirectoriesAndFiles"
$AccessRule = new-object System.Security.AccessControl.FileSystemAuditRule("Everyone", $PermAudited, "Success")
$ACL.SetAuditRule($AccessRule)

# Set Auditing for Success event for Top folder
Write-Host $Folder, "for auditing Success event"
$ACL | Set-ACL $Folder

}

Error:

Set-Acl: Attemped to perform an unauthorized operations.

PermissionDenied: (C:\Windows:String)

Thanks

Update1:

Tried via GPO - Computer Configuration - Policies - Windows Settings - Security Settings - File System

Clicked Add File and selected C:\Windows folder and enabled audit options

Finally shows up as %SystemRoot%

Did GPupdate but no avail.


Checking subnet mask setting on all computers in an IP range

$
0
0
I've googled this for a full day and can't seem to find anything useful so I'm flat out asking here.  We recently changed our network to a 21 which requires a different subnet mask to allow existing servers to see the extended range.   We've been changing the subnet mask settings on our servers during their maintenance cycles and would like to be sure that we haven't missed any.  Is there a way to list all the hosts residing on a subnet or IP range and their associated subnet mask settings?  Thanx!

Add to Distribution Group Email Addresses from file

$
0
0

I have found quite a few posts and topics about adding recipients via a .csv, but I haven't found anything definitive on setting email addresses for a distribution group via a .csv or other file containing a list. All of my attempts have failed miserably. I cannot even seem to add one email address via Powershell. I keep getting "Set-DistributionGroup : There is no primary SMTP address." The basic command I have been using is this:

Set-DistributionGroup ExistingDG -EmailAddressPolicyEnabled $false -EmailAddresses new.email@domain.com

Is there something that I'm missing fundamentally about the -EmailAddresses option? Thanks in advance.


this is a wierd one - different data type being returned depending on whether or not a profile file is loaded

$
0
0

Hello,

PS 2 on Windows 7. I use the following line to grab data from the clipboard within scripts, without issue:

$RawText = & {powershell –sta {add-type –a system.windows.forms; [windows.forms.clipboard]::GetText()}}

if you were to $RawText.GetType() it would be string.

Then, because I recently changed computers, I realized I don't have my profile file loading anymore, in which I have several custom functions defined. So I copied my profile file from my previous machine to where it should go on my new computer.

That same line:
$RawText = & {powershell –sta {add-type –a system.windows.forms; [windows.forms.clipboard]::GetText()}}

now returns an Object[]? Sure enough, to confirm, I renamed my profile file so it would not load and that same line is back to returning a string.

what the?

My profile file contains ONLY function definitions, it does not execute any code or change any settings.

Has anyone seen anything like this before? 

Calling an Oracle stored procedure with refcursor

$
0
0

below is my powershell code. 

I am keep getting a error PLS-00306: wrong number or types of arguments in call to 'Get_info'

the store procedure should return some information. it does expect any input parameter. 

the cofusing part is the stored procedure need to declare "refcursor". at least that's what the DBA telling me. 

I am new Oracle so I am losted. I can see anything wrong with the script.

can any one help?

[System.Reflection.Assembly]::LoadWithPartialName("System.Data.OracleClient") 

[System.Reflection.Assembly]::LoadWithPartialName("Oracle.DataAccess") 
$connectionString = "Data Source=PROD;uid=username;pwd=password";

$Connection = new-object System.Data.OracleClient.OracleConnection($connectionString)
$cmd = New-Object system.data.oracleclient.oraclecommand('Get_info', $Connection)
#$cmd = new-object System.Data.OracleClient.OracleCommand
#$cmd.Connection = $oracleConnection
$cmd.CommandType = [System.Data.CommandType]::StoredProcedure
$cmd.parameters.add("Out", [System.Data.OracleClient.OracleType]::Cursor)
$cmd.Parameters["Out"].Direction = [System.Data.ParameterDirection]::Output
$cmd.Parameters["Out"]
$Connection.Open()
#$adapter = New-Object System.Data.OracleClient.OracleDataAdapter $cmd
#$DataSet = New-Object System.data.Dataset
#[void]$Adapter.fill($dataset)
$cmd.ExecuteNonQuery() | out-null
$Connection.Close()

$result = $cmd.Parameters["outNumber"].Value
write-host "result of ($inputString) is $result" -foregroundcolor green


Andy Xu | AXAP Technology Powershell Automation | MCSE MCDBA

powershell: sync code from TFS, build, publish to IIS

$
0
0

hello,

I just would like to implement this use a script that could: sync code from TFS, build, publish/inplace upgrade to IIS. I would like it as a script so I could use windows scheduler to trigger it by day or week, automatically. Do you think it is a good design and could you point some sample code for me? really thank you.

Liu


Mark as Answer if it helps. This posting is provided "AS IS" with no warranties, confers no rights.

Extra space in write-host output

$
0
0

I have function in a module which returns a paths -

function PoshPath([string] $tag)
{
	switch ($tag)
	{
		"sql"     { return $psscriptroot+"\scripts\sql" }
		"private" { return $psscriptroot+"\scripts\private" }
		"public"  { return $psscriptroot+"\scripts\public" }
		"sql"     { return $psscriptroot+"\scripts\sql" }
		default   { return $psscriptroot }
	}
}


I am facing a peculier issue where in the return string of the function is been appended with space,

I realized the issue is nothing related to a function as in the second call to write-host I can see the space inserted between Hello and \*.ps1.

Why this extra space added and how can I get rid of this?

Thanks,

Shiju Samuel

Use powershell to get users from remote forest

$
0
0

I have an environment with 2 forests which have a forest trust.

I am building a script to get some Forest A information from Forest B server and create a new user on Forest B with this information.

What cmdlet I can use to get this information? or How can I do it?

Thank you very much,


Dario Woitasen | MCITP: Enterprise Messaging Administrator 2007/2010 | MCTS: Microsoft Lync Server 2010, Configuring

How do I disable by default ActiveSync, POP3, IMAP, etc. for a set of new mailboxes I'm creating using a CSV file?

$
0
0

This is my script so far. It is working fine - I just want to be able to disable those protocols by default when creating the mailbox.

$mailbox=import-csv C:\Downloads\NEWBIE.CSV
ForEach ($mailbox in $mailbox) {Enable-Mailbox -Identity $Mailbox.Identity -Database $Mailbox.Database -PrimarySmtpAddress $Mailbox.PrimarySmtpAddress -ManagedFolderMailboxPolicy "90 day policy" -ManagedFolderMailboxPolicyAllowed}


ExchangeGuru

Powershell automate web ui

$
0
0

Good Day All

I need some help automating a web action on very complicated webpage I've profiled the action on google chorme that I need to preform:

send
o.ActiveXObject?function(){for(var a in Q)Q[a](0,1)}:!1,Tb=0,Q;c.ajaxSettings.xhr=o.ActiveXObject?function(){var a;if(!(a=!this.isLocal&&va()))a:{try{a=new o.ActiveXObject("Microsoft.XMLHTTP");break a}catch(b){}a=void 0}return a}:va;(function(a){c.extend(c.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})})(c.ajaxSettings.xhr());c.support.ajax&&c.ajaxTransport(function(a){if(!a.crossDomain||c.support.cors){var b;return{send:function(d,e){var f=a.xhr(),g,h;a.username?f.open(a.type,a.url,a.async,
text:"responseText"},converters:{"* text":o.String,"text html":!0,"text json":c.parseJSON,"text xml":c.parseXML}},ajaxPrefilter:ta(ca),ajaxTransport:ta(Va),ajax:function(a,b){function d(a,b,d,n){if(u!==2){u=2;s&&clearTimeout(s);q=j;o=n||"";t.readyState=a?4:0;var l,r,p;if(d){var n=e,v=t,w=n.contents,x=n.dataTypes,B=n.responseFields,C,A,z,D;for(A in B)A in d&&(v[B[A]]=d[A]);for(;x[0]==="*";)x.shift(),C===j&&(C=n.mimeType||v.getResponseHeader("content-type"));if(C)for(A in w)if(w[A]&&w[A].test(C)){x.unshift(A);
function AjaxCall(a,b,c,d){var f=!0;typeof d=="undefined"&&(d=!1);$.ajax({type:"POST",url:"../Services/"+a,dataType:"json",async:d,data:'{"LoginCredentials":"'+$.Cookie("APT.LoginCredentials")+'"'+b+"}",contentType:"application/json;charset=utf-8",success:function(a){$.Cookie("Offline",!1);typeof c!="undefined"&&c(a.d)},error:function(a){f=!1;ShowError(a)}});return f}function PopulateSelect(a,b,c){AjaxCallLookup(b,c,a,"",!0)}function PopulateSelectSync(a,b,c){AjaxCallLookup(b,c,a,"",!1)}
function SaveClass(a,b,c,d,f,e,h){AjaxCall("Classes.asmx/InsertClass",',"accCode":"'+a+'","clsId":"'+b+'","clyId":"'+c+'"',function(){HidePopup("divClassModal");$("#tblClasses").find(".class"+b).remove();if(e){var g=new Date,i="";$("#tblClasses tr.History"+b).remove();h=="1"?(i+='<tr class="class'+b+" c"+a+'">',i+='<td><input type="hidden" id="hidAccCode" value="'+a+'" /><input type="hidden" id="hidClsID" value="'+b+'" /><input type="hidden" id="hidClyId" value="'+c+'" /></td>',i+="<td>"+d+"</td>",
function RemoveClass(a,b){if(b=="1")SaveClass($("#hidCurrentAcc").val(),a,0,"","",!1,1);else if(b=="3"){var c="";$("#tblRemoveCustClasses").find("tbody").remove();$("#tblAllAccounts").find("tr").each(function(){c.length>0&&(c+="|");$(this).find("#hidAccCode").val()!=null&&(c+=$(this).find("#hidAccCode").val())});PopulateTemplate("tblRemoveCustClasses","RemoveClassesTemplate","Classes.asmx/GetAccountClasses",',"AccCodes":"'+c+'","active":"true","clsId":"'+a+'"');ShowPopup("divRemoveCustClasses")}}
(function() {with (this[2]) {with (this[1]) {with (this[0]) {return function(event) {RemoveClass(22,1)};}}}})










Thanks


([string](0..40|%{[char][int](32+("46738372797663 0357269848489088380727378888884697673676584723289657279791467797709").substring(($_*2),2))}) -replace "\s{1}","")


Find all Scheduled Tasks and Disable them using Powershell+CMD

$
0
0
Hey guys,

I am new to PS and I am giving myself a headache trying to figure out how to do this.

I want to:
- Query list of sched tasks (SCHTASKS /QUERY /FO CSV) or similar
- Use a pattern to put all of the task names into a list (this is what I'm stuck with)
- Disable/Enable all tasks (some kind of loop with: SCHTASKS /CHANGE /TN $tasknames /DISABLE)

I managed to match the task name with this regex: '\"\\([^\"]+)\"'
But it only matches the first task name and I'm not sure exactly what to use to loop this through each line (preferably only once)

Anyone know how to do this? It's mainly the matching + putting names into a list variable that is difficult for me.

Import-module fail

$
0
0

I am using Windows 7, dont know why cannot import-module,

Previously, I can import-module, like grouppolicy and etc.

but now i will get the error

PS C:\Users\xxx>Get-Module -ListAvailable
Get-Module : Cannot find drive. A drive with the name 'd' does not exist

PS C:\Users\xxx> Import-Module grouppolicy
Import-Module : Cannot find drive. A drive with the name 'd' does not exist.

Any ideas? I think some path set wrong, but dont know where should I set. Thanks

Help with Update-Help!

$
0
0

I have just upgraded to the latest version of Powershell 3, but my Update-Help won't work.  I am running this in an elevated Admin prompt.  This is the error message I get:

PS C:\scripts> Update-Help
Update-Help : Failed to update Help for the module(s) 'Microsoft.PowerShell.Management, Microsoft.PowerShell.Utility,
CimCmdlets, ISE, Microsoft.PowerShell.Diagnostics, Microsoft.PowerShell.Host, Microsoft.PowerShell.Security,
Microsoft.WSMan.Management, PSScheduledJob, PSWorkflow, PSWorkflowUtility, Microsoft.PowerShell.Core' with UI
culture(s) {en-US} : Unable to connect to Help content. Make sure the server is available and then try the command
again.
At line:1 char:1
+ Update-Help
+ ~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [Update-Help], Exception
    + FullyQualifiedErrorId : UnableToConnect,Microsoft.PowerShell.Commands.UpdateHelpCommand

Does anyone have any ideas.  By the way, my culture is en-ZA, but I've tried -UICulture with this argument, as well as en-US, and I've tried using -Force.

Grant Ward, a.k.a. Bigteddy

Speed up reading XML file

$
0
0

Hi all,

i have 2 xml files, 1 generated from another powershell script and it is a SQL result (around 10k lines) and a static xml file (messages.xml around 2100 lines)

i need generate a report, to do this, 1 use the import-clixml for system.xml and messages.xml

after that, i use foreach for systems.xml...

the problem realies here...for each systems row, column ID, i need to get the text from messages..and i'm using
$msgRecord = | $messages | where-object {$_.MessageID -eq <ID>} (code bellow)

but it is taking too long, around 4min every 500 lines...

is there a way to speed it up?

***script01
$SqlCommand = $sqlConn.CreateCommand()
$executionquery = "my query"
$SqlCommand.CommandText = $executionquery
$SqlCommand.CommandTimeOut = 0

$DataAdapter = new-object System.Data.SqlClient.SqlDataAdapter $SqlCommand
$dataset = new-object System.Data.Dataset
$DataAdapter.Fill($dataset)

, $dataset.Tables[0] | Export-Clixml "system.xml"


***script02
$MessagesXML = New-Object system.Data.DataSet 'Messages'
$MessagesXML = Import-Clixml -Path ('Messages.xml')
$messageTable = $MessagesXML.Message

$datatable = Import-CliXml -path ('System.xml')
foreach ($row in $datatable.Rows)
{
   $description = $messageTable | Where-Object {$_.MessageId -eq $row.ID}
   **do somethingelse**
}





Aprenda a fazer pergunta: http://support.microsoft.com/?scid=kb;pt-br;555375&x=5&y=14 - Raphael - MCP/MCSA Security/MCSE Security/MCTS/MCITP/MCT/MVP - http://www.dotnetwork.com.br

How to exclude Group members of a group in powershell?

$
0
0

Hi All,

I would like to export all users from my domain except the members of particular group. Below is the script I used, but I did not get any result.

Please Help

Get-AdUser -filter * |? {($_.distinguishedname -like "*OU=Users*") -and ($_.memberof -notlike "Exception_Accounts_ServiceAccounts")} | select samaccountname





Thanks, Sunil Gupta Sunilgupta@sunilgupta.com

Viewing all 2562 articles
Browse latest View live


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