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

Copy-Item -Recurse from UNC to local folder does not seem to be working.

$
0
0

I'm trying to copy log files from a number of sources to a local folder, but nothing seems to be happening.

My code:

Param(
	[parameter(Mandatory=$true,ValueFromPipeline=$true)]
	[ValidateScript({Test-Path $_ -PathType 'Leaf'})] 
	[String] 
	$FileOfLogFiles
)

$ListOfLogFiles = Get-Content $FileOfLogFiles
$CurrentPath = Get-Location
$CurrentTime = Get-Date -UFormat "%Y-%m-%d_%H-%M-%S_%Z"
$DestinationPath = "$CurrentPath\$CurrentTime\"
Write-Host ""

ForEach ( $LineOfLogFiles in $ListOfLogFiles )
{
	If ( $LineOfLogFiles.substring(0,1) -eq "#" )
	{
	} Else {
        [string[]]$ElementsOfLineOfLogFiles = $LineOfLogFiles.split(";")
        $Server = $ElementsOfLineOfLogFiles[0]
        $Volume = $ElementsOfLineOfLogFiles[1]
        $LogFolder = $ElementsOfLineOfLogFiles[2]

        $SourcePath = "\\$Server\$Volume`$\$LogFolder\*.log"
        Write-Host "$(Get-Date -Format o) SourcePath      = '$SourcePath'"
        Write-Host "$(Get-Date -Format o) DestinationPath = '$DestinationPath'"

        Get-ChildItem -Path "$SourcePath" -Recurse"Copy-Item -Path `"$SourcePath`" -Destination $DestinationPath -force -recurse -verbose"
         Copy-Item -Path  "$SourcePath"  -Destination $DestinationPath -force -recurse -verbose
	}
	Write-Host ""
}

My data file looks like this:

vcac2web1;e;Program Files (x86)
vcac2web2;e;Program Files (x86)
vcac2mgmt1;e;Program Files (x86)
vcac2mgmt2;e;Program Files (x86)
vcac2demw1;e;Program Files (x86)
vcac2demw2;e;Program Files (x86)
vcac2agnt1;e;Program Files (x86)
vcac2agnt2;e;Program Files (x86)

The script does not generate any errors, but no files are actually copied. The Get-ChildItem does find the log files. I am running this in PowerShell proper, not the IDE. OS = Windows Server 2012 not R2, PS = 3.0

send active directory password rule via an email

$
0
0

Hello

Can anyone help me scripting, we would like to send out an automated email to all mgmt heads about the AD password rules.

Thanks

Naveen Rao

List shared groups between AD users.

$
0
0

Hi,

I am fairly new to PowerShell.  I'm looking for a script that will list the shared groups among AD users.  I would like the script to essentially spit out the groups that five specific users have in common.

Browsing the forum, I have seen several examples of scripts comparing users and outputting the differences, on the flipside of this I would like the output to reflect the similarities (in relation to group membership).

If a similar question has been answered elswehere within the forum, please let me know.  Thanks!

0..7 | ForEach

$
0
0

I have several checkboxes on a form: $Checkbox0, $Checkbox1 .. $Checkbox7

I tried to use 0..7 | ForEach to access them, like $Checkbox$_.Checked, but not working. Is there a way to do it? Thanks.

POWERSHELL ACTIVEDIRECTORY – FIND ALL USERS WHO REPORT TO SPECIFIC MANAGE

$
0
0

I want to display all users who report to a specific manager without using a import cmd. I've had no joy from the script below. Can anyone give me some insight of what I'm doing wrong?

#users name are displayed as " cn=smith\, doe"

$User = read-host -Prompt "Enter DL Manager AD credentials" 

$Ou1= "ou=employees,ou=ohcin,dc=corp,dc=local"

$OuObj = "$user,$ou1"

get-aduser -filter {manager -eq "$OuObj"} |ft name


Aaron Harris ExchangeSharePointGuy

Want a Script to set Computer extensionattribute in Bulk

$
0
0

Want a Script to set Computer extensionattribute in Bulk by giving input from CSV Computer Name and extensionattribute.

Regards,

Kashi


Kashi

Can't run Batch files or Devnev (visual studio) - is not recognized .. command

$
0
0

Getting the famous error :

... is not recognized as an internal or external command`*

When & Where :

not sure about the total range of the problem,
Here I can't run batch files and "devneve.exe"

sample Batch could be :

@echo off    
clr

'clr' is not recognized ...

**Here are the keynotes:**

 1. I run it as an admin (cmd)
 2. The Path variable seems to have anything needed, Powershell's path is also there sys32..v1
 3. I'm going into the current directory of devnev.exe ...
 4. ran also "devnev.exe"
 5. I don't have 2 cmd s in a known folder
 6. the autorun registries for command prompt were deleted
 7. the cmd extensions were disabled and re-enabled
 8. Avast IS 9 is running,
 9. The system seems to be fine
 10. all .Net frameworks are installed
 11. for a test jetAudio or ILDasm could be executed from the cmd

Win 8.1 Pro , CPU i7, VS 2013 upd2


Getting a computer's IP address - am I making this too complicated?

$
0
0

I've been asked to resolve a bunch of machine names to IP addresses, and the person wanting the results doesn't care if the machines are actually available or not. I figured I could try the following methods:

Ping, WMI, parsing AD

so I put together the following script:

function Get-IPAddress{

Param([string]$computername=$env:computername)

[regex]$ip4="\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}"

get-wmiobject win32_networkadapterconfiguration -filter "IPEnabled='True'" -computer $computername | 
 Select DNSHostname,Index,Description,@{Name="IPv4";Expression={ $_.IPAddress -match $ip4}},
 @{Name="IPv6";Expression={ $_.IPAddress -notmatch $ip4}},MACAddress
 }

$_csv         = @()
$_csv_header  = """IP"",""Server"""
$_csv         += $_csv_header

$servers = get-content C:\temp\servers.txt
foreach ($server in $servers){
    If (Test-Connection $server -Count 1 -Quiet -ErrorAction SilentlyContinue ) {
        $ipaddress = get-ipaddress $server
        $ipv4address = $ipaddress.ipv4}
        Else { $ipv4address = 'IP DOES NOT RESOLVE'}
        If ( $ipv4address -eq $null){
            $ipv4address = Get-ADComputer $server -Properties ipv4Address | ft ipv4Address,name}
            If ( $ipv4address -eq $null){
            $testconnection = test-connection $server -count 1
            $ipv4address = $testconnection.IPV4Address.IPAddressToString}
        $_csv += """$ipv4address"",""$server"""
        }

$_csv | Out-File c:\temp\servers.csv -Encoding ASCII

Am I making that too complicated? Is there something I overlooked? Is there a way to take error returns on failed WMI attempts ("get-wmiobject : Access is denied") and put them in my final output? Am I just dumb because someone has already written a better script?

Thank you.


zarberg@gmail.com


I am having a problem importing a csv file into Powershell v3.

$
0
0

I am having a problem importing a csv file into Powershell V3 ISE.  I am getting the following error:

 C:\windows\system32>  Import-Csv C:\Scripts\PowerShell Scripts\newusers.csv

 

 

 

I

Import-Csv : Cannot bind parameter 'Delimiter'. Cannot convert value "Scripts\newusers.csv" to

type "System.Char". Error: "String must be exactly one character long."

At line:1 char:35

+  Import-Csv C:\Scripts\PowerShell Scripts\newusers.csv

+                                   ~~~~~~~~~~~~~~~~~~~~

    + CategoryInfo          : InvalidArgument: (:) [Import-Csv], ParameterBindingException

    + FullyQualifiedErrorId : CannotConvertArgumentNoMessage,Microsoft.PowerShell.Commands.Impor

   tCsvCommand

 

Add a custom email alias to all my mail enabled users

$
0
0

Hey Everyone,

I'm trying to add an email alias to all my mail enabled users using powershell.

 I'm in a dir sync setup can I do something like the below.Of course the smtp:$($a.lname)_$($a.fname@domain.ca isn't working for me. It was posted online as "$a.alias", which isn't what I need. I need to add lname_fname@domain.ca to every mailbox.A crappy voice mail system software that can't alter it's send To address format template is driving this change.  I don't want to use an address policy, due to it changing the default reply in the process.

if someone can help me get this script working that would be fantastic.

$users = Get-Mailuser
foreach ($a in $users) {$a.emailaddresses.Add("smtp:$($a.lname)_$($a.fname@domain.ca")}
$users | %{Set-Mailuser $_.Identity -EmailAddresses $_.EmailAddresses}


Suleman

Use of saved credentials

$
0
0

I know I can Get-Credential and use the object for things like creating a scheduled task, or using Invoke-Command on another machine.

And I know I believe I can save that Credential to file for later use as well.

But, is there any way to run an arbitrary cmdlet using that saved credential? Say a Copy-Item? I have a series of things I want to do in the context of the saved credential, and others that need to happen in the user context, and I would like to have the script running in user context simply wrap a series of commands in that credential. The other approach I am considering is a scheduled task, but that is a bit of a kludge compared to just wrapping what I need in the credential, if that is possible.

Gordon

Running 5 commands using array elements and waiting between?

$
0
0

Hi All,

Trying to learn PS so please be patient with me ;)

System: PSv3 on Win2012 server running WSUS role

I am wanting to execute 5 commands using a 'foreach' loop but wait until one finishes before moving onto the next. Can you please check out what I have and provide some suggestions of improvement? or scrap it completely if it's rubbish :(

Current code:

#### SCRIPT START ####
#Create and define array and elements
$Array1 = @(" -CleanupObsoleteComputers"," -DeclineSupersededUpdates -DeclineExpiredUpdates"," -CleanupObsoleteUpdates"," -CleanupUnneededContentFiles"," -CompressUpdates")
#Run the cleanup command against each element
foreach ($element in $Array1) {
Get-WsusServer | Invoke-WsusServerCleanup $element -Whatif
}
#### SCRIPT END ####

I am assuming that I need to use @ to explicitly define elements since my second element contains two commands with a space between?

The cleanup command doesn't accept '-Wait' so I'm not sure how to implement a pause without just telling it to pause for x time; not really a viable solution for this as the command can sometime take quite a while. They are pretty quick now that I do this all the time but just want it to be future proof and fool proof so it doesn't get timeouts as reported by others.

I have found lots of code on the net for doing this remotely and calling the .NET assemblies which is much more convoluted. I however want to run this on the server directly as a scheduled task and I want each statement to run successively so it doesn't max out CPU and memory, as can be the case when a single string running all of the cleanup options is passed.

Cheers.

invoke with function inside

$
0
0

hi all,

i have a print utility but it can be a little slow when having 5+ servers, so i would like to run it with invoke command and as a job. I have a function addprinter

#add printer function
function addprinter ($printername,$printerport,$server)
{
echo "$(get-date -format 'g') adding prt name: $PrinterName to port: $PrinterPort on $server" >> $log
#try creating port if it doesn't exist
try{
$PortClass.Name = "IP_"+"$PrinterPort" 
$PortClass.Protocol = 1 
$PortClass.HostAddress = "$PrinterPort" 
$PortClass.PortNumber = "9100" 
$PortClass.SNMPEnabled = $False
$PortClass.psbase.put()
}
catch{}
#Set printer settings and add it to the port
try{
$PrinterClass.DriverName = $driverbox.Text #"HP Universal Printing PCL 6 (v5.8.0)"
$PrinterClass.PortName   = "IP_"+"$PrinterPort"
$PrinterClass.DeviceID   = "$PrinterName" 
$PrinterClass.Network = $False
$PrinterClass.Shared = $False
$PrinterClass.Default = $False
$PrinterClass.psbase.put()
cscript c:\windows\system32\printing_admin_scripts\en-us\prncnfg.vbs -s $server -t -p $PrinterName +rawonly -enablebidi
}
catch{}
}

and my invoke command looks like this

Invoke-Command -ComputerName $server -ScriptBlock {$function:addprinter} -asjob -ArgumentList $printername,$printerport,$server

I made some breakpoints and made sure the variables are populated, but not seeing anything on the server that im trying to run this to. And i know my addprinter function works without the invoke it must be how im passing arguments and the function itself?

Any suggestions?

Thanks


can PowerShell allow the key F9 to generate a set of characters anytime it is pressed ?

$
0
0
can a PowerShell scriot be installed that allows the key F9 to generate a set of characters anytime it is pressed ?

Active Directory Powershell add users Manager

$
0
0

I'm trying to update multiple users managers using a csv file. I can get the users logon name using eharris with "

Get-aduser -identity eharris |Set-ADUser -Manager "aharris". However, if I add a foreach loop it fails saying its unable to find the using on the DC. Can you give me any guidance on what I'm missing in my script. 

$list = Import-CSV "C:\1DL\AddManager\test.csv" 

ForEach ($user in $list)

{

$user.name

$SAM = "$user.name" 
$Manager = "aharris"

Get-aduser -identity $sam | |Set-ADUser -Manager "aharris"
}

#




Aaron Harris ExchangeSharePointGuy


Why do I need to press ctrl + c to proceed through application

$
0
0
Note - This question is not about the ruby programming language. 

I am running some ruby tests for my code. I have to execute a ruby command which will 
run a couple of tests on my code and give the results. When I run this command in cmd, 
the tests run on their own and I get the results in console. Nice and easy.

But, when I run the same tests in Powershell, I have to press ctrl+c for every "stage"
of the test. 

c:\> c:\tests\rubyTest.rb
> PressED enter key

Say running your tests...
{ctrl+c}

Prepare the objects and data needed for test...
{ctrl+c}

Running the tests...
{ctrl+c}

Test ends. Time taken and exceptions are reported...
{ctrl+c}

Back to prompt !

Is there any PowerShell Script to Get all Unique Permissions in SharePoint 2010

$
0
0

As the title says.

I want to get all Unique Permissions from SharePoint and if Possible I want to do it via PowerShell.

We don't really need any Groups Permissions, we just need the unique ones.

HRESULT 0x80070001,Register-ClusteredScheduledTask

$
0
0

I'm trying to define a ClusteredScheduleTask on a cluster, running Powershell on the active node.

Code:

$trigger = New-ScheduledTaskTrigger -at 12:00 -Once
$action = New-ScheduledTaskAction -Execute "notepad"
Register-ClusteredScheduledTask -Action $action -TaskName "clusteredtasktest" -Trigger $trigger -TaskType anynode

Error:

Register-ClusteredScheduledTask : Incorrect function.
At C:\Users\nwalters\Documents\TestWebSampleCode2.ps1:3 char:1
+ Register-ClusteredScheduledTask -Action $action -TaskName "clusteredtasktest" -T ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (PS_ClusteredScheduledTask:Root/Microsoft/...edScheduledTask) [Register-Clus
   teredScheduledTask], CimException
    + FullyQualifiedErrorId : HRESULT 0x80070001,Register-ClusteredScheduledTask

Posted here first: http://serverfault.com/questions/623407/powershell-set-clusteredscheduledtask-error-incorrect-function

Still not getting any definitive answer. This is one of the few things remaining before switching our production code to this cluster.

Thanks,
Neal Walters

PS1 command to generate IP Configuration for all Servers

$
0
0
Any PS command which can be used to generate IP Details and hostname(Server IP, Prefered and Alterate DNS IP, Hostname) assigned to servers in a domain. Or generate the same for a list of servers?

Converting Json to CSV

$
0
0

I am using powershell to get some data from a webservice which is returning json.

I wish to write this out to a CSV file, but not sure how to do it.

So far:

$webRequest = [System.Net.WebRequest]::Create( $loc )
				$webRequest.Headers.Add($auth2)
				$return = $webRequest.GetResponse()
#				$usagein = Invoke-WebRequest -Uri $loc -Headers @{"authentication"=$authent} -timeoutsec 6000 | ConvertFrom-Json 
                $stream = $return.getResponseStream()
				$sr = new-object IO.StreamReader($stream)
				$result = $sr.ReadToEnd()
				$return.close()
				$resultjson = $result | ConvertFrom-Json
				$result > ".\output_normal.txt"
				$resultjson > ".\output_json.txt"
				write-host "done for" $beginrange $endrange

I end up with two files, one with the raw output and one with nicly formatted Json. 

How can I write to a CSV file?

Thanks.

Viewing all 21975 articles
Browse latest View live