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

SetAuditRuleProtection($False, $True) and Set-ACL

$
0
0

$acl = Get-ACL ...

#do some stuff to the DACL

#mark SACL to inherit audit

$acl.SetAuditRuleProtection($False, $True)

While this sequence of events will not break SACL inheritance, it will not restore SACL inheritance as expected, either. Is this a bug? I see this behavior on local and UNC paths.


creat custom table

$
0
0

Hi, Thanks for you help My best regards Arnold



How to show Win32_classes properties

$
0
0

Hello

When I do this in PowerShell:

Get-WmiObject Win32_TCPIPPrinterPort

or even: Get-WmiObject Win32_TCPIPPrinterPort | Format-List *

it doesn't show anything. But if I put Get-WmiObject with another Win32 Class e.g. Win32_printer it shows some properties.

Why is that?

Thanks

Powershell foreach -parallel WMI query operation did not complete within the allotted timeout of 00:00:30

$
0
0

Hello!

I'm running the following script in PS 3.0:

Workflow Test-My-WF {  
  $servers=Get-Content -Path "ser.txt"
  foreach -parallel ($server in $servers) {
    $proci = (Get-WmiObject win32_Processor -ComputerName $server | select name)
    if($proci)
        {
        $proci
        }
       }
}
Test-My-WF

I get some results but I endupt with the following error after 30sec.

The operation did not complete within the allotted timeout of 00:00:30. The time allotted to this operation may have been a portion of a
longer timeout.
At Test-My-WF:8 char:8
+
    + CategoryInfo          : InvalidResult: (:) [], TimeoutException
    + FullyQualifiedErrorId : JobStateFailed

Is it possible to change the timeout ? (running the same workflow against anothet WMI class for example W32_Process runs faster and I do not experience the same problem).

Many thanks in advance for your answers!


email trouble

$
0
0
have tried to answer many ads on crasigslist & ebay. when replying by email msn says email sent. also sometimes says problem sending email from my address. have never gotten reply from any ad- 25-30 times tried. need hel[p in solving email tbl.

set-alias

$
0
0

Hello,

What is wrong with the following code:

Set-alias gs set-executionpolicy restricted

I want to set this line in my $profile but the line isnt working. I got the same problem when I want to use "cd" instead of set-executionpolicy, for example:

set-alias gs cd C:\myscripts 

But neither of them work. Can someone tell me what i'm doing wrong or tell me a other way of doing it if it is not possible doing it with set-alias.

Thanks!

Connect to Hotmail using Powershell

$
0
0

Folks,

I have been trying to connect to Hotmail through Powershell. Can you offer any advice on how to accomplish that

Thanks

Similar to connecting to remote computer using WSManagement, how to do it through powershell terminal?

$
0
0

I have the following code to connect to the remote powershell and execute script on remote machine :

WSManConnectionInfo connectionInfo =newWSManConnectionInfo(false,"MachineName",5985,"/wsman", shellUri, credential); using (Runspace runspace =RunspaceFactory.CreateRunspace(connectionInfo)){ runspace.Open(); using (PowerShell powershell =PowerShell.Create()){ powershell.Runspace= runspace;String file =@"C:\scripts\createUser.ps1"; powershell.Commands.AddScript(System.IO.File.ReadAllText(file));Collection<PSObject> results = powershell.Invoke();}}

How to execute the script in same way from powershell command prompt?




Azure AD Managment

$
0
0

Hi,

 I recently ran into the situation where we wanted to create multiple Azure AD's from a particular subscription. However, I quickly discovered there are no management options from within powershell. There was explanation given to me that basically revolved around the concept that the Azure Portal does not have any "resource" knowledge of AD's.

It seems strange that I cannot create new AD's from powershell yet from the Portal I can simply add a new one. Can anyone help me understand this a bit better?

Bypassing Execution Policy for a specific host

$
0
0

Is is possible to have the execution policy set to remotesigned but have specific hosts set to bypass? I am administering an SCCM 2012 environment and I want to be able to run Powershell to check for the existence of packages or applications but it keeps erroring out that the script is not signed. I tried adding the server to wsman:\localhost\client\truestedhosts but that did not seem to work either. Is this possible?

Thanks!

Tony

Restart IIS remotely

$
0
0

Hi,

I want to restart IIS service on a remote machine. What's the Powershell command for this, where I will be able to mention the remote server name, username, password?

AD Module for Windows PowerShell - Insufficient Access Rights to perform the operation

$
0
0
I have a recently upgraded domain that's now running all 2008R2 DCs.  The domain functional level is 2008R2 and the forest functional level is 2003.  I've also created a brand new lab domain with virtual machines and experienced the exact same problem.  When I logon to a DC and open the AD module for Windows Powershell I can run AD related commands like get-adcomputer, get-aduser, etc.  When I try to run any command that modifies attributes though I get an error (listed below).  I'm a member of the domain admins, enterprise admins, schema admins, etc.  The only way I can get it to work is to explicitly add myself to the ACL of an object.  That doesn't make any sense though because by virtue of being a domain admin I should have full control of the object anyway.  In fact if I check effective permissions it even shows me that I do have full control.  Considering I'm experiencing this exact same issue is two totally different 2008R2 domains I can't believe no one else is.  Any ideas?


Set-ADComputer: Insufficient access rights to perform the operation at line:1 char:15
+ Set-ADComputer <<<<  testPC -Description Test3
+ CategoryInfo          : NotSpecified: (testPC:ADComputer) [Set-ADComputer], ADException
+ FullyQualifiedErrorId : Insufficient access rights to perform the operation,Microsoft.ActiveDirectory.Management.Commands.SetADComputer

How do I search a spreadsheet for a list of URL's | then search those URL's for keywords | save the output? (Oh yeah..., and schedule it)

$
0
0

Fist, I should mention I am not a programmer but am eagerly learning powershell!

I am looking for an automated solution to accomplish what I am currently doing manually.  I need a script that would combine the following:

  1. Reach out to a list of websites (probably a loop of some sort since the list will come out of a spreadsheet which could contain 1 or 100 different sites)
  2. Search each page for a specific word or words (not contained in the spreadsheet though that may make it more scalable)
  3. Save the URL of the site(s) that contained the keywords to one text file (versus the multiple .html files I am creating today)
  4. Have the output contain which words it found on which site.
  5. If not overly complicated, I would like to schedule this to recur once a week.

A working script would be ideal, but even the resources that show me how to incorporate each element would suffice.

I have had success pulling down the full content of the listed pages and saving them to a directory, which requires manual intervention.

So far this works, but it's not scalable:
     Set-ExecutionPolicy RemoteSigned
     $web = New-Object Net.WebClient
     $web.DownloadString("http://sosomesite/54321.com") | Out-File "C:\savestuffhere\54321.html"
     $web.DownloadString("http://sosomesite/54321.com") | Out-File "C:\savestuffhere\65432.html"
     Get-ChildItem -Path "C:\savestuffhere\" -Include *.html -Recurse | Select-String -Pattern "Keyword 1"

In otherwords, I have to manually replace the "http://sosomesite/54321.com" and "C:\savestuffhere\54321.html" when the URL changes to .\65432.com and the output name to match.  That works fine when it's a couple sites, but again, is not scalable.  

Then, to see if any of the saved file's contain the keyword(s), I have to search the directory for the keyword which I am using:
Get-ChildItem -Path "C:\savestuffhere\54321.html" -Include *.html -Recurse | Select-String -Pattern "Keyword 1"

Wmi class Win32_printer not found in root/cimv2

$
0
0

Hello all,

I'm trying to use powershell to remove a local IP printer.  I tried with this.  The command ran successfully but did not remove my printer.

remove-wmiobject -computername localhost -class Win32_printer | where { $_.portname -eq '192.168.4.54' -and $_.local -eq 'TRUE'}

NOW, I can't even run get-wmiobject -class Win32_printer as it says it does not exist in the root/cimv2 namespace.  I tried using get-ciminstance instead of get-wmiobject and got this.

The WS-Management service cannot process the request. The class Win32_printer does not exist in the root/cimv2 namespace.

I did a get-wmiobject -list and outputed that to a txt file and reviewed it.  I have no Win32_printer class!

How do I get it back??


I understand what I did wrong.  I removed the whole class Win32_printer.  then piped that to my filter.  I wanted to get-wmiobject than pipe that to my filter then remove.  Remove should have been last.  But I still no longer have the class!

Adding Global Groups to Domain Local through script.

$
0
0

Hi, I have a script from creating Local Domain groups from Global Security groups, now I want to expand that script so it automatically adds that Global group to Domain Local group.

Here is the script that I have and that works for creating Domain Local groups:

$groups = Get-ADGroup `
    -Filter 'GroupScope -eq "Global" -and GroupCategory -eq "Security"' `
    -Properties Description,DisplayName,ManagedBy
ForEach ($group in $groups) {
    
    $params = @{
        Path = $group.DistinguishedName -replace '^cn=.+?(?<!\\),'
        Name = "DL_FGL_$($group.Name)"
        SamAccountName = "DL_$($group.SamAccountName)"
        Description = "$($group.Description)"
        DisplayName = "$($group.DisplayName)"
        ManagedBy = $group.ManagedBy
        GroupCategory = "Security"
        GroupScope = "DomainLocal"
    }
    Try {
        Get-ADGroup -Identity "DL_$($group.SamAccountName)" | Out-Null
    }
    Catch {
        New-ADGroup @params
    }
}


Remove-ADGroupMember where member is in parent domain and group is in child domain

$
0
0

I have a parent domain (sandbox.local) and a child domain (child.sandbox.local) and want the capability to add and remove sandbox\User to a (domain local) group in the child domain. 

I can add the user to the group:

$GroupDN = (Get-ADGroup $groupsam -server "child.sandbox.local").DistinguishedName
$UserDN = (Get-ADUser $sam -server "sandbox.local").DistinguishedName
Add-ADGroupMember -Identity GroupDN -Members UserDN

Problem: when I use any of the commands listed below, I get an object not found or referral was returned from the server error.

Remove-ADGroupMember -Identity GroupDN -Members UserDN -server "sandbox.local"
Remove-ADGroupMember -Identity GroupDN -Members UserDN -server "child.sandbox.local"

Remove-ADPrincipalGroupMembership -Identity $UserDN -MemberOf $GroupDN -Server "sandbox.local"
Remove-ADPrincipalGroupMembership -Identity $UserDN -MemberOf $GroupDN -Server "child.sandbox.local"

Suggestions?

Paul

<Specific error codes.>



Remove-ADGroupMember -Identity $GroupDN -Members $UserDN -Confirm:$false -Server "sandbox.local"

Remove-ADGroupMember : A referral was returned from the server
At C:\Users\user\AppData\Local\Temp\4e5f275f-5786-4a0d-990e-50312cef9d70.ps1:10 char:21
+ Remove-ADGroupMember <<<<  -Identity $GroupDN -Members $UserDN -Confirm:$false -Server "sandbox.local"
    + CategoryInfo          : ResourceUnavailable: (CN=TestGroup,OU...,DC=local:ADGroup) [Remove-ADGroupMember], ADReferralException
    + FullyQualifiedErrorId : A referral was returned from the server,Microsoft.ActiveDirectory.Management.Commands.RemoveADGroupMember



Remove-ADGroupMember -Identity $GroupDN -Members $UserDN -Confirm:$false -Server "child.sandbox.local"

Remove-ADGroupMember : Cannot find an object with identity: 'CN=user,OU=pacific,OU=KrbUsers,DC=ad,DC=spawar,DC=local' under: 'DC=pac,DC=
ad,DC=spawar,DC=local'.
At C:\Users\user\AppData\Local\Temp\4e5f275f-5786-4a0d-990e-50312cef9d70.ps1:10 char:21
+ Remove-ADGroupMember <<<<  -Identity $GroupDN -Members $UserDN -Confirm:$false -Server "child.sandbox.local"
    + CategoryInfo          : ObjectNotFound: (CN=user,OU=...,DC=local:ADPrincipal) [Remove-ADGroupMember], ADIdentityNotFoundException
    + FullyQualifiedErrorId : SetADGroupMember.ValidateMembersParameter,Microsoft.ActiveDirectory.Management.Commands.RemoveADGroupMember
 


Remove-ADPrincipalGroupMembership -Identity $UserDN -MemberOf $GroupDN -Server "sandbox.local"

Remove-ADPrincipalGroupMembership : A referral was returned from the server
At C:\Users\user\AppData\Local\Temp\4e5f275f-5786-4a0d-990e-50312cef9d70.ps1:11 char:34
+ Remove-ADPrincipalGroupMembership <<<<  -Identity $UserDN -MemberOf $GroupDN -Server "sandbox.local"
    + CategoryInfo          : ResourceUnavailable: (CN=user,OU=...,DC=local:ADPrincipal) [Remove-ADPrincipalGroupMembership], ADReferra
   lException
    + FullyQualifiedErrorId : A referral was returned from the server,Microsoft.ActiveDirectory.Management.Commands.RemoveADPrincipalGroupMembers
   hip



Remove-ADPrincipalGroupMembership -Identity $UserDN -MemberOf $GroupDN -Server "child.sandbox.local"

Remove-ADPrincipalGroupMembership : Cannot find an object with identity: 'CN=user,OU=pacific,OU=KrbUsers,DC=ad,DC=spawar,DC=local' under
: 'DC=pac,DC=ad,DC=spawar,DC=local'.
At C:\Users\user\AppData\Local\Temp\4e5f275f-5786-4a0d-990e-50312cef9d70.ps1:11 char:34
+ Remove-ADPrincipalGroupMembership <<<<  -Identity $UserDN -MemberOf $GroupDN -Server "child.sandbox.local"
    + CategoryInfo          : ObjectNotFound: (CN=user,OU=...,DC=local:ADPrincipal) [Remove-ADPrincipalGroupMembership], ADIdentityNotF
   oundException
    + FullyQualifiedErrorId : SetADPrincipalGroupMembership:ProcessRecordOverride,Microsoft.ActiveDirectory.Management.Commands.RemoveADPrincipal
   GroupMembership
 
 

The term 'new-object' is not recognized as the name of a cmdlet, function, script file, or operable program.

$
0
0

I have a script that runs well the vast majority of the time.  On occasion I get an exception.  I would appreciate any insight as to why it fails on occasion.  I can't understand why the new-object cmdlet wouldn't be recognized:

Message: The term 'new-object' 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.

Source: System.Management.Automation

StackTrace:    at System.Management.Automation.CommandDiscovery.LookupCommandInfo(String commandName, CommandTypes commandTypes, SearchResolutionOptions searchResolutionOptions, CommandOrigin commandOrigin, ExecutionContext context)
   at System.Management.Automation.CommandDiscovery.LookupCommandProcessor(String commandName, CommandOrigin commandOrigin, Nullable`1 useLocalScope)
   at System.Management.Automation.ExecutionContext.CreateCommand(String command, Boolean dotSource)
   at System.Management.Automation.PipelineOps.AddCommand(PipelineProcessor pipe, CommandParameterInternal[] commandElements, CommandBaseAst commandBaseAst, CommandRedirection[] redirections, ExecutionContext context)
   at System.Management.Automation.PipelineOps.InvokePipeline(Object input, Boolean ignoreInput, CommandParameterInternal[][] pipeElements, CommandBaseAst[] pipeElementAsts, CommandRedirection[][] commandRedirections, FunctionContext funcContext)
   at System.Management.Automation.Interpreter.ActionCallInstruction`6.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)
   at System.Management.Automation.Interpreter.EnterTryCatchFinallyInstruction.Run(InterpretedFrame frame)

Here is the script I am running:

param([string]$endpoint)
$ErrorActionPreference = "Stop";
try
{
 [System.Reflection.Assembly]::LoadFile("D:\dotNET_Apps\dotNETCOExBatch\DotNETCOExBatch\bin\DotNETCOExBatch.dll")
 $schedule = new-object DotNETCOExBatch.CallService
 $reply = $schedule.CallWebService($endpoint)
 if ($reply)
 {
  $host.setshouldexit(0)
 }
 else
 {
  $host.setshouldexit(8)
 }
}
Catch
{
 $nl = [Environment]::NewLine
 $evt=new-object System.Diagnostics.EventLog("Application")
 $evt.Source="BatchPowerShell"
 $infoevent=[System.Diagnostics.EventLogEntryType]::Error
 $batchException = $_.Exception
 $logMessage = " "  
 while ($batchException)
 {
  $exMessage = $batchException.Message
  $exStackTrace = $batchException.StackTrace
  $exSource = $batchException.Source
  $logMessage += "$nl $nl Message: $exMessage $nl $nl Source: $exSource $nl $nl StackTrace: $exStackTrace" 
  $batchException = $batchException.InnerException 
 }
 $evt.WriteEntry(" Error starting or process cancellation of $endpoint $logMessage",$infoevent)
 $host.setshouldexit(15)
}

PowerShell Script Running Through Scheduler

$
0
0

Hi Folks,

I am running below script to copy a file from one server to another server. This script uses it's own authentication.

Issue is my security policy doesn't allow me to store password on task scheduler. So I implemented the script to use its own authentication. But this script doesn't work when you run through task scheduler. Any hints ?

$user="dummyuser"
$File="H:\fc\pu.txt"
$password = Get-Content $File | ConvertTo-SecureString
$cred=New-Object System.Management.Automation.PsCredential -ArgumentList ($user,$password)
$list=@("webdev")
$source = "D:\fcopy\PerconaToolkit.pdf"

foreach ($server in ($list))
     {
            if (test-connection $server -quiet)
                {
                    New-PSDrive -name $server -PsProvider FileSystem -root "\\$server\e$\fcopy" -Credential $cred
                    Copy-Item $source -Destination "$($server):"
                    Remove-PSDrive -Name $server
                }                    
                else
                      {
                    Exit
                     }
    }



Use Same Excel Object in Start-Job as Main PS1

$
0
0

I have hundreds of Excel files and one main file that has links to each of these files, but in order for the data to be pulled into the main excel file I need to have every file opened within the same Excel instance and then work through each one. If Microsoft let me open more than 15 files at a time this would be as easy as it was back in the day to open them all at once, but I understand why this isn't allowed anymore... So I created a script to open all of the files with:


$xl = New-Object -comobject Excel.Application
foreach($file in $files){
$wb = $xl.Workbooks.open($filename)
}
$xl.visible = $true

I am also going to be processing hundreds of rows per file. I don't care about the order the files are opened in necessarily. So I have narrowed in on usingStart-Job like so because of the unordered opening and the overhead of starting the Start-Job is better than the forking process I have tried the following:

Start-Job -ScriptBlock {Param( $filename); Write-Host $filename "*" $input "*"; $input.Workbooks.open($filename) } -inputobject $xl -ArgumentList @($filename)

~my_path_and_filename~ * System.Management.Automation.Runspaces.PipelineReader`1+<GetReadEnumerator>d__0[System.Object] *
You cannot call a method on a null-valued expression.+ CategoryInfo          : InvalidOperation: (open:String) [], RuntimeException+ FullyQualifiedErrorId : InvokeMethodOnNull

Start-Job -ScriptBlock {Param( $filename); Write-Host $filename "*" $args[0] "*"; $filename.Workbooks.open($args[0]) } -ArgumentList @($xl, $filename)

Microsoft.Office.Interop.Excel.ApplicationClass * ~my_path_and_filename~ *
Method invocation failed because [Deserialized.System.__ComObject#{000208db-0000-0000-c000-000000000046}] doesn't contain a method named 'open'.+ CategoryInfo          : InvalidOperation: (open:String) [], RuntimeException+ FullyQualifiedErrorId : MethodNotFound

Start-Job -ScriptBlock {Param($xl, $filename); Write-Host $filename "*" $xl "*"; $xl.Workbooks.open($filename) } -ArgumentList @($xl, $filename)

~my_path_and_filename~ * Microsoft.Office.Interop.Excel.ApplicationClass *
Method invocation failed because [Deserialized.System.__ComObject#{000208db-0000-0000-c000-000000000046}] doesn't contain a method named 'open'.
    + CategoryInfo          : InvalidOperation: (open:String) [], RuntimeException+ FullyQualifiedErrorId : MethodNotFound

So, is there a way to pass an Excel Object to the Start-Job cmdlet? Or is there a way to pass an Excel object out of the Start-Job so the main Object can take it over? And lastly, when receiving a job, does one get access to the actual objects inside of the job?

Server2012: Set-ClusterScheduledTask + "Run with highest Priviledges" - ???

$
0
0

Hey there,

I'm trying to fix a script we have to trim VSS copies on our Fileserver which is a Serve 2012 Failover Cluster. 

This has worked in the past, however I think it got messed up when I changed the schedule from a Win8.1 workstation. Anyway, I've lost the "Run with highest priviledges" flag on the task and I can't quite seem to find a way to set it back. Judging by the documentation, if I were able to set a scheduled task principal I could use the -RunLevel switch, but apparently that's not supported with the ClusteredScheduledTasks. Also, it appears that if the settings of the task are set to volatile=true, that enables highest privs, but I can't find a way to do that via the Powershell cmdlets. 

Anyone have any ideas? 

Viewing all 21975 articles
Browse latest View live


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