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

How to script move computer to different ou after getting lastlogondate

$
0
0
Get-ADComputer -Filter * -Properties LastLogonDate -SearchBase "Domain" |
    Where { $_.LastLogonDate -lt (Get-Date).AddMonths(-3) } | Set-ADComputer -Enabled $false

Can someone help finish this off for me? This goes ahead and finds computers that haven't logged in 3 months and disables it. Now I need the script to move those computers to a different OU. Thanks!

Error Catching.

$
0
0

I'm trying to pull in the local security policy on my servers and I'm running my script against all my servers.  For the most part all is fine but on some servers I get the following error message.  Can someone tell me what it means and is possible how to fix it?  All my information still pulls in so if I could just silentlycontinue on this error it would be great

New-Object : Exception calling ".ctor" with "1" argument(s): "Value was invalid.
Parameter name: sddlForm"
At C:\myscript.ps1:784 char:15
+                 $sid = new-object System.Security.Principal.SecurityIdentifier($str)
+                        ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [New-Object], MethodInvocationException
    + FullyQualifiedErrorId : ConstructorInvokedThrowException,Microsoft.PowerShell.Commands.NewObjectCommand


SMaximus7

Windows PowerShell Web Access - Custom Microsoft.Powershell_Profile.ps1 for All Users

$
0
0

Hi Everyone,

I'm looking for a bit of guidance on implementing a custom Powershell profile for all users of the system using the Add-PswaAuthorization cmdlet. More, I'm really looking for how/where to drop the custom profile that you set using the -ConfigurationName parameter.

I've tried using the full path and filename, which doesn't work (using this command: Add-PswaAuthorizationRule -UserGroupName 'DOMAIN\Administrative_Sec_Gr' -ComputerName * -ConfigurationName C:\Windows\System32\WindowsPowerShell\v1.0\Microsoft.Power­Shell_profile.ps1). I'd like to avoid creating a blanket profile for the entire system as I would like to customize experience using auth rules paired with customized profiles (limiting cmdlet access, directory access, computer access, etc).

Can someone point me in the right direction please? Most of the documentation I've found examines the issue on a per user basis with very little guidance on how to handle a group situation.

Thanks!

Mike


Michael Kaminski

Powershell Script to find text string and paste text below

$
0
0

I have a text file for our website that is edited everyday and would like to script the daily changes.  The script would need to find a particular line based on match, add a blank then paste a new line with a calculated date.  This is what I have so far:

$Text = get-content C:\temp\cvcal.inc
$NewText = @()
foreach ($Line in $Text) {
if ($Line -eq "<p>listed by Judge...<br><br>") {
$Line = $Line.Replace("<p>listed by Judge...<br><br>", "<p>listed by Judge...<br><br>`r`n")
$NewText += $Line
$NewText += '<a href="/courtscheduling/cvcal/cvjud20150128.pdf">01/28/2015</a><br>'
}
else {
$NewText += $Line
}
}
$NewText | Set-Content C:\temp\cvcal.inc


It will find the text (<p>listed by Judge...<br><br>) and replace it with the same text with the added carriage return and new line.  The new text (<a href="/courtscheduling/cvcal/cvjud20150128.pdf">01/28/2015</a><br>) is added and a blank line is below it, which I do not want. This is the results:

<p>listed by Judge...<br><br>

<a href="/courtscheduling/cvcal/cvjud20150128.pdf">01/28/2015</a><br>

<a href="/courtscheduling/cvcal/cvjud20150127.pdf">01/27/2015</a><br>

My dilemma is to get rid of the second blank line and be able to use a date variable to replace the dates in the replacement text (20150128 & 01/28/2015). The dates are calculated as 2 weeks from tomorrow.

Thanks for any help

Jerry

Running PowerShell Studio psf file

$
0
0

Hi,

I am using Sapien PowerShell Studio and created  a form (psf). Is it possible running a native psf on computers without PowerShell Studio or do I need convert it to ps1?

Thanks,

How to set up a virtual machine MAC address Powershell, specify the MAC address range?

$
0
0

HI,Expert:

    How toset up a virtualmachineMACaddressPowershell,specify theMACaddress range

Thanks in advance!

How to Virtual VHDX file Implants the IP address?

$
0
0

Hi Expert,

WeAutomatically creates multiple virtual machine has been configured, but we don't  how to VHDX files Implants IP addresses through Powershell

Thanks in advance!

Importing several CSV files into Excel

$
0
0

Hello Everyone,

I managed to piece together this code which runs several powershell scripts that each output a CSV for every day of the week.

Next, I located a function that takes a CSV file as input and exports that as a worksheet in an Excel document.

My problem is, the last column in the Excel file should be the first column and I just cannot spot why this behavior is occuring.

#First phase, output CSV files used later in the script.
Monday.ps1
Tuesday.ps1
Wednesday.ps1
Thursday.ps1
Friday.ps1
Saturday.ps1
Sunday.ps1
#Now the function to export the CSV from Phase 1 into an Excel Spreadsheet.
function Export-Excel {
[cmdletBinding()]
Param([Parameter(ValueFromPipeline=$true)][string]$junk)

	begin{
		$header=$null
		$row=1
	}
	process{
		if(!$header){
			$i=0
			$header=$_ | Get-Member -MemberType NoteProperty | select name
			$header | %{$Global:ws.cells.item(1,++$i)=$_.Name}
		}
		$i=0++$row
		foreach($field in $header){
			$Global:ws.cells.item($row,++$i)=$($_."$($field.Name)")
		}
	}
}

$xl=New-Object -ComObject Excel.Application
$wb=$xl.WorkBooks.add(1)
$Global:ws=$wb.WorkSheets.item(1)

$Global:ws.Name='Sunday'
import-csv 'C:\Sunday.csv' | Export-Excel
$Global:ws=$wb.WorkSheets.Add()
$Global:ws.Name='Saturday'
import-csv 'C:\Saturday.csv' | Export-Excel
$Global:ws=$wb.WorkSheets.Add()
$Global:ws.Name='Friday'
import-csv 'C:\Friday.csv' | Export-Excel
$Global:ws=$wb.WorkSheets.Add()
$Global:ws.Name='Thursday'
import-csv 'C:\Thursday.csv' | Export-Excel
$Global:ws=$wb.WorkSheets.Add()
$Global:ws.Name='Wednesday'
import-csv 'C:\Wednesday.csv' | Export-Excel
$Global:ws=$wb.WorkSheets.Add()
$Global:ws.Name='Tuesday'
import-csv 'C:\Tuesday.csv' | Export-Excel
$Global:ws=$wb.WorkSheets.Add()
$Global:ws.Name='Monday'
import-csv 'C:\Monday.csv' | Export-Excel
$xl.Visible=$true


Deploy.ps1 cannot be loaded because the execution of scripts is disabled on this system

$
0
0

Hi all,

I want to execute a simple script but after execution I receive an error message as displayed in the title.

Tried to resolve this through Powershell (64 bit) Set-ExecutionPolicy Unrestricted and by Get-ExecutionPolicy i can see that it is indeed set to Unrestricted.

Despite all efforts, i still receive the same error message.

who can help!?

Thanks in advance

Maarten

Putting the Parent OU Name into the User Department field, within AD

$
0
0

I have been asked to go through and clean up the AD for the company which is a mess, a part of the clean-up is to populate the department field with the user's parent OU name

OU = IT

    User = Chris

              Department = IT

I have created a PowerShell script that will do most of my clean-up for me, but I am having issues with the department, cos as I understand it the parent OU contactor is not really a contractor.

There is the basic layout of my code so far

 #$ous = Get-ADUser -Filter * -SearchBase "OU=xxx,DC=xxxx,DC,=xxx"

foreach($ou in $ous)

{

 $ou.Title = "Student"

    $ou.Title = "Student"

    $ou.streetAddress = "Prince Philip Barracks"

#    $ou.postOfficeBox = "PO Box 12345"

    $ou.l = "Bordon"

    $ou.st = "Hampshire"

    $ou.postalCode = "GU35 0JE"

    $ou.co = "United Kingdom"

 Set-ADUser -Instance $ou

 }

Want I would like to do is something like

$ou.department = ************ but I am not sure on how to go about this, I have found and read about some code

Example

Get-ADUser -Filter * -Properties distinguishedname,cn |

 select @{n='ParentContainer';e={$_.distinguishedname -replace "CN=$($_.cn),",''

but I am not sure on how to import this into the body of my code.

Any ideas?

Compare CreationTime of Two Files

$
0
0

I'm trying to compare the creation time of two files. I've seen many instances and examples on the internet where the creation time is compared against the current date, but I need check if one file is more than 7 days older than another file and if so move a file.
Here's what I've got:

$file1 = Get-ChildItem $ScriptPath\Archive\Weekly | Sort CreationTime | Select -First 1
$file2 = Get-ChildItem $ScriptPath\Archive\Daily\$backup | Select CreationTime

So $file1 is the most recent file in the specified directory, and $file2 is a the creation time of $backup. I need to see if $file1 is more than 7 days older than $file1. Any ideas?

Thanks in advance
Adam


Check for folders with no music files in

$
0
0

Hi

Relatively new to PS and am trying to find a way to check my Music (iTunes) Library for folders with no music files. I could check for empty folders but there seem to be AlbumArt folders all over the place which will skew the output.

What I currently have is:

Clear-Host
$ThePath = "$Env:USERPROFILE\Music\iTunes\iTunes Media\Music" #Change this
$dirs = Get-ChildItem -Path $ThePath -Recurse -Directory | Sort-Object FullName
$Output = @()

foreach ($dir In $dirs.Fullname) {
    if(-not(Test-Path "$dir/*.m4a")) {
        If(-not(Test-Path "$dir/*.mp3)) {
            $Output += $dir.Replace("$Env:USERPROFILE\Music\iTunes\iTunes Media\Music\", "")
        }
    }
}

$Output | Out-File $env:USERPROFILE\Cloudstation\Scripts-Home\iTunes\NoMusic.txt

As you can see I'm starting to nest IF statements.  Is there an easier way, whereby I could exclude multiple extensions without nesting IF's?

Thanks
Tony

Powershell copy from server to another user task scheduler

$
0
0

Hi!

I've made two powershell scripts to copy files from my main server to my ftp-server, for user downloads.

the first script is like this:

Set-ExecutionPolicy Unrestricted -force
.\ftp2.ps1

#ftp server
$ftp = "ftp://ftp.extend.no/"
$user = "<hidden>"
$pass = "<hidden>"
$from = "D:\FTP\*"  
$to = "\\ftp.extend.no\D$\ftp"

$webclient = New-Object System.Net.WebClient
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)

Copy-Item -path $from -destination $to -force
Copy-Item "D:\EQS_webroot\export\<hidden>\*" "\\ftp.extend.no\D$\ftp\<hidden>\" -force

the second (as you can see, the first script referst to this)

#ftp server
$ftp = "ftp://ftp.extend.no/"
$user = "<hidden>"
$pass = "<hidden>"
$from = "D:\FTP\*"  
$to = "\\ftp.extend.no\D$\ftp"

$webclient = New-Object System.Net.WebClient
 
$webclient.Credentials = New-Object System.Net.NetworkCredential($user,$pass)

Remove-Item $to -recurse
Copy-Item $from $to -force

These two scripts works when i run them from powershell and cmd, but not through task scheduler.

Task scheduler options:

program/script "%windir%\System32\WindowsPowerShell\v1.0\powershell.exe"

add arguments: d:\powershell\ftp\ftp.ps1
Start in: d:\powershell\ftp\

I've tried some arguments like -executionpolicy bypass, -file,  and other.. but nothing works.

Can you help me with this?

Set-AuthenticodeSignature -filePath from Pipeline

$
0
0

Not sure if this is a Set-AuthenticodeSignature problem, or my use of the pipeline. So, I have 

Get-ChildItem "$MLF\Resources\*" -include:*.ps1,*.psm1,*.vbs

returning the correct singable subset of files in a folder. But when I try to pipe the results to Set-AuthenticodeSignature I get errors claiming -filePath is empty. I have tried both $_ and $_.FullPath.

Get-ChildItem "$MLF\Resources\*" -include:*.ps1,*.psm1,*.vbs | Set-AuthenticodeSignature -filePath:$_ -certificate:$Cert[0] -force

Now I can put the Get-ChildItem result in a variable and then foreach the variable. But as usual the pipeline approach seems to mess with my head. I presume I don't need a foreach in the pipeline, because the whole point is the pipeline will send items one at a time, correct? I have found some example code that creates a pipeline enabled function, and it's in the function that Set-AuthenticodeSignature is called. From what I can tell Set-AuthenticodeSignature is pipeline capable, and I expected to have issues with the variable for  -certificate that is reused. So, where am I going wrong? Or am I barking up an empty tree?

Finding a specific file exactly 2 levels deep in 1000's of folders (and deleting it)

$
0
0

Our user home folders, all 6000+ of them, are on a rather large external NAS-type device. Before I got here, some users had taken to saving things right from their PC to their home folder and on occasion that included their desktop.ini file. Unfortunately this can cause problems. I'd like to go through and delete all files named desktop.ini but only in the root of the user directories.

Say the path to my NAS is \\filer and the users folders are all under \\filer\users (E.G. '\\filer\users\jonesm' or '\\filer\users\smithj'). I'd like to first list out and record all the desktop.ini files in every user folder, but only at the root of those user folders. I came up with this:

gci -path \\filer\users\*\* -force -filter "desktop.ini" > c:\temp\desktopiniresults.txt

If I wanted to delete all those files right after, I could do this:

gci -path \\filer\users\*\* -force -filter "desktop.ini" | foreach ($_) {remove-item $_.fullname -force}

Is there any easy way to both record the ones I found and delete them in one command?

Thanks


zarberg@gmail.com


Out-GridView Question

$
0
0
Hello,

I'm wondering if you can control the window size when using Out-GridView? For example:

Get-Service | Out-GridView

When this is run the window is showing more space than what I need; is it possible to have it shrink the window size to fit the results?

CSV Export Formatting

$
0
0

I've been working on a script for the last couple of days to extract Full Access, Send-As, and Send on Behalf of permissions for a specific mailbox.  At first I couldn't wrap my head around how to get Exchange permissions and AD permissions data to extract seamlessly to a CSV with PS.  Luckily I was able to find a similar question on TechNet that all but showed me the way, the only problem is the formatting once the script executes and the data is exported.

For reference, this is that question - https://social.technet.microsoft.com/Forums/sqlserver/en-US/5420d0a2-aded-414c-9ddf-f0e171dcb189/exchange-2010-retrieve-full-mailbox-access-sendas-access-and-send-on-behalf-of-access?forum=winserverpowershell

I added a few tweaks of my own and the output looks great for the most part.  The only problem I'm having is with the Send on Behalf of perms and how that's displayed in the CSV.  I thought of creating a variable to grab those permissions, export them, and then import them into the CSV, but I can't seem to wrap my head around it.  I'm not even sure it's possible when pulling out the GrantOnBehalfOfTo perms.

The script:

Add-PSSnapin Microsoft.Exchange.Management.PowerShell.E2010

$MBName = Read-Host 'Please enter the mailbox alias.  Example: username'
$CSVPath = Read-Host 'Please enter the full path of the folder in which you would like to save the results and name the file.  Example: [C:\Scripts\Output\test.csv]'

$Mailbox = Get-Mailbox $MBName

$FullAccess = $Mailbox | Get-MailboxPermission | Where {$_.user.tostring() -ne "NT AUTHORITY\SELF" -and $_.IsInherited -eq $false} | Select-Object Identity,User,@

{Name='Permissions';Expression={[string]::join(', ', $_.AccessRights)}}

$SendAs = $Mailbox | Get-ADPermission | Where {($_.ExtendedRights -like “*Send-As*”) -and ($_.IsInherited -eq $false) -and -not ($_.User -like “NT AUTHORITY\SELF”)} |

Select-Object Identity,User,@{Name='Permissions';Expression={[string]::join(', ', $_.ExtendedRights)}}

$SendOnBehalf = $Mailbox | Where {$_.GrantSendOnBehalfTo -ne $null} | Select Identity,@{Name='User';Expression={$_.Alias}},@{Name=’Permissions';Expression=

{[string]::join(“|”,($_.GrantSendOnBehalfTo))}}

$All = @()
$FullAccess | %{ $All += $_ }
$SendAs | %{ $All += $_ }
$SendOnBehalf | %{ $All += $_ }
$All | Sort-Object User | Export-Csv -NoTypeInformation $CSVPath

I've attached what the export looks like and how I'm hoping it can be formatted.  Can anyone offer any help?


Get last logon time,computer and username together with Powershell

$
0
0

I have a script which gets the last logon times of each computer in the domain.

My script:

$dcs = Get-ADComputer -Filter { OperatingSystem -NotLike '*Server*' } -Properties OperatingSystem

foreach($dc in $dcs) {
    Get-ADComputer $dc.Name -Properties lastlogontimestamp |
    Select-Object @{n="Computer";e={$_.Name}}, @{Name="Lastlogon"; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp)}}
}

==================================

Result:

Computer Lastlogon -------- --------- DC1 6/06/2013 16:38:24 DC2 6/06/2013 16:30:40

=============================================

I also want to get who/which account made this logon. For example:

Computer Lastlogon User -------- ------------------ ---- DC1 6/06/2013 16:38:24 user2 DC2 6/06/2013 16:30:40 user1



Loop with WMI Query taking too long, need to break out if time exceeds 5 min

$
0
0
I've written a script that will loop through a list of computers and run a WMI query using the Win32_Product class. I am pinging the host first to ensure its online which eliminates wasting time but the issue I'm facing is that some of the machines are online but the WMI Query takes too long and holds up the script. I wanted to add a timeout to the WMI query so if a particular host will not respond to the query or gets stuck the loop will break out an go to the next computer object. I've added my code below:

$Computers = @()
$computers += "BES10-BH"
$computers += "AUTSUP-VSUS"
$computers += "AppClus06-BH"
$computers += "Aut01-BH"
$computers += "AutLH-VSUS"
$computers += "AW-MGMT01-VSUS"
$computers += "BAMBOOAGT-VSUS"

## Loop through all computer objects found in $Computes Array
$JavaInfo = @()
FOREACH($Client in $Computers)
	{

		## Gather WMI installed Software info from each client queried
		Clear-Host
		Write-Host "Querying: $Client" -foregroundcolor "yellow"
		$HostCount++
		$Online = (test-connection -ComputerName ADRAP-VSUS -Count 1 -Quiet)
		IF($Online -eq "True")
			{
				$ColItem = Get-WmiObject -Class Win32_Product -ComputerName $Client -ErrorAction SilentlyContinue | `
				Where {(($_.name -match "Java") -and (!($_.name -match "Auto|Visual")))} | `
				Select-Object Name,Version

				FOREACH($Item in $ColItem)
					{
						## Write Host Name as variable
						$HostNm = ($Client).ToUpper()

						## Query Named Version of Java, if Java is not installed fill variable as "No Java Installed
						$JavaVerName = $Item.name
						IF([string]::IsNullOrEmpty($JavaVerName))
							{$JavaVerName = "No Installed"}

						## Query Version of Java, if Java is not installed fill variable as "No Java Installed
						$JavaVer = $Item.Version
						IF([string]::IsNullOrEmpty($JavaVer))
							{$JavaVer = "Not Installed"}

						## Create new object to organize Host,JavaName & Version
						$JavaProp = New-Object -TypeName PSObject -Property @{"HostName" = $HostNm"JavaVerName" = $JavaVerName"JavaVer" = $JavaVer
						}
						## Add new object data "JavaProp" from loop into array "JavaInfo"
						$JavaInfo += $JavaProp
					}
			}
			Else
			{Write-Host "$Client didn't respond, Skipping..." -foregroundcolor "Red"}

	}	

Get-Process on a remote machine doesn't work but Invoke-Command does

$
0
0

So we use some scripts to check for running processes and I have 1 machine that isn't cooperating.

If I run get-process wuinstall -computername server1 I get an error stating: Couldn't connect to remote machine.

If I run Invoke-Command {get-process wuinstall} -ComputerName server1 I get my results back just fine.

Is there anything that would cause one to work and not the other?  I'm baffled because of 20+ machines we just have 1 that doesn't like it.  I'm logged into my admin box as a Domain Admin account.

Thanks.

Viewing all 21975 articles
Browse latest View live