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

Powershell DSC - Laptops running on battery

$
0
0

Hi,

Wonder if anyone has come across this situation or might have any ideas on how to help,

We have sets of laptops in trolleys and a set of laptops which are used on-site and off-site all with the same configuration running Windows 7 x64, Group Policy would not always apply offsite so we decided to use Powershell DSC as a replacement mechanism for maintaining registry / policy settings and protecting from configuration driftWindows Management Framework 4.0 has already been installed on the devices.

Unfortunately, it seems the scheduled tasks created by Powershell DSC have the condition set on them for "Start the task only if the computer is on AC power", the trolley laptops are never powered up when connected the mains, they are powered up, used on battery then powered down and returned to the trolley to charge, so the DSC configuration never runs!

As a hacky fix, I've exported the Powershell DSC tasks as XML, changed the settings and used schtasks.exe to delete the task and import a new one based on the XML.  If we reconfigured Powershell DSC the tasks are automatically recreated by the set-dsclocalconfigurationmanaager command and once again won't start.

Does anyone know if there is a way to configure Powershell DSC to create these tasks without the AC power requirement flag set?

Thanks,

Chris.




powershell for adding default printer

$
0
0

We currently use an exe that looks through a text file, finds the name of the printer the user is on and then adds the default printer from that list as the default printer. This exe is called from the logon script.  This exe is starting to have problems so we are trying to find a way to replace this.

Line from logon script

@start /w %logonserver%\netlogon\defprinter\defprinter %COMPUTERNAME%

Example of the list:

Comp1,\\Printserver\Pqueue1
Comp2,\\Printserver\pqueue2
Comp3,\\Printserver\pqueue3
Comp4,\\Printserver\pqueue1
Comp5,\\Printserver\pqueue2

The creator of said exe is long gone from the organization so we're not sure of what the exe contains.   Is there a way for a powershell script to take the computer name the logon script is running from, search the list and then apply the shared queue name as the default printer?

Powershell script to get firewall status on all computers on the domain

$
0
0

Trying to create a script that will get the status of the firewall's on all computers in the domain. I have a decent start but the formatting looks like crap and I am sure there is a better way to do this. Any help would be appreciated.

$strFilter = "computer"

$objDomain = New-Object System.DirectoryServices.DirectoryEntry

$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.SearchScope = "Subtree"
$objSearcher.PageSize = 1000

$objSearcher.Filter = "(objectCategory=$strFilter)"

$colResults = $objSearcher.FindAll()

foreach ($i in $colResults)
    {
        $objComputer = $i.GetDirectoryEntry()
		$objComputer.Name
        netsh -r $objComputer.Name advfirewall show allprofiles state | Export-Csv -append -Path C:\Firewall.csv
    }
My export is not working as expected - it is just giving me gibberish numbers

pssession in Scheduled task

$
0
0
I have written powershell script which contains new-pssession and import-pssession cmdlets. Everything works fine from Console session. But same script does not work when it is configured on Scheduled task. Is there any way to get to work?

Powershell: win32_offlinefilescache - Pin and Synchronise Folders to Local Offline Files Cache (CSC)

$
0
0

Hi all,

I'm in the proces of writing a script which pins folders into the offline files cache (CSC) on Windows 7 x64 machines. It takes an array of strings (the paths to sync), pins them to the cache and then once everything's pinned it performs a full synchronisation of the CSC on the local box.

Only it doesn't.

I've scoured the MSDN libraries on "Win32_OfflineFiles*" and everything looks correct, when the script runs it returns a value of 0 (success), the output to the console shows that the pin command is running succesfully on the folder path.  When you look at Sync Center on the local machine the paths specified in the script aren't pinned anywhere and no synchronisation of the cache has taken place.

If anyone's got any clues or can offer any help I'd be much obliged, this is driving me nuts now!

Ok, the code (I'll just include the two functions that aren't working rather than everything):

This function (poorly named I'll admit) performs the pin action on a single path that is passed to it. It is called from a ForEach loop which checks to see that each path exists before calling this function.   I do not want a synchronisation to happen when the folders are pinned, I need to pin the folders first, then synch afterwards.  (Hence the "fill" flag not being specified on the pin command).  For an explanation as to the flags on the pin command see the MSDN article (its clearer than I could explain!): http://msdn.microsoft.com/en-us/library/windows/desktop/bb309186%28v=vs.85%29.aspx

Function EnableCSC ($syncpath) {
    $localCSC = [wmiclass]"Win32_OfflineFilesCache"
    $localCSC.Pin($syncpath[0],0x00010801,$true)
    }

This second function performs a full synchronisation (or should...) of the CSC on the local machine. The $paths variable passed to it contains only paths which both exist and have previously been pinned by the enableCSC function.

Function SynchCSC ($paths) {
    if (! $paths) {
        # No arguments, quit.
        }
    Else {
        $localCSC = [wmiclass]"Win32_OfflineFilesCache"
        $localCSC.Synchronize($paths,0x00000002)
        }
    }

I've tried running these scripts manually in the console and they execute correctly and return 0 (success) without actually doing anything.  Network traffic running through the NIC isn't affected (you'd expect a jump if a synch occurs, especially when my test user has a good few GBs of data to synch up) and nothing changes in Sync Center in Control Panel (you'd expect to see any new pinned folders and the results of the last CSC synchronisation).

If anyone's got any clue as to why these two functions don't work I'd be much obliged!

Many thanks!

Remove AD computer object using powershell from text file

$
0
0

HI,

Is there a Powershell command or series of commands I can use to remove a text based list of computers from AD?  

In other words, I have a text file containing a list of computers that are disabled and I want to remove from AD.  Any idea how I might do this?

Use Powershell to automate PowerPoint document repair message response

$
0
0

Hello, I have a challenging problem.  In general, I have thousands of PowerPoint documents, that I need to open and answer a popup message regarding repairing the file (PowerPoint found a problem with content in XXXXX.   PowerPoint can attempt to repair the presentation).  The specific Office PowerPoint 2016 message is attached below.  I would like to automate this via powershell scripting.

I've tried different methods for opening, sending keys, and closing the PowerPoint - all without success.  Specifically, I've tried the following:

1) Opening the document via Com - failed result as COM can't open it due to this message

2) Opening the document via command-line (eg powerpnt.exe c:\doc.ppt) and then use DLLImport for the user32.dll to grab the window, set it's focus, and then use sendkeys to answer the message box - failed result as when I bring the windows to the foreground and use sendkeys, it's the sendkeys don't go to the window.  In troubleshooting the issues, it looks like it brings the app to the foreground, but the keyboard focus is not on it.  In fact, when I mouse click on it - after the script runs - I see the focus for the keyboard goes to the app.

I'm guessing that I need to grab the window and set it to the foreground, as well as set the keyboard to focus on this window, but that still doesn't work.

I"m looking for help to get the keyboard focus to the window, or another creative way to get this problem solved!  My very simple POC script is below.

thx

Simple script***********************

# Helper functions for building the class
$script:nativeMethods = @();
function Register-NativeMethod([string]$dll, [string]$methodSignature)
{
    $script:nativeMethods += [PSCustomObject]@{ Dll = $dll; Signature = $methodSignature; }
}
function Add-NativeMethods()
{
    $nativeMethodsCode = $script:nativeMethods | % { "
        [DllImport(`"$($_.Dll)`")]
        public static extern $($_.Signature);
    " }

    Add-Type @"
        using System;
        using System.Runtime.InteropServices;
        public static class NativeMethods {
            $nativeMethodsCode
        }
"@
}


# Add methods here
Register-NativeMethod "user32.dll" "bool SetForegroundWindow(IntPtr hWnd)"
Register-NativeMethod "user32.dll" "bool ShowWindowAsync(IntPtr hWnd, int nCmdShow)"
Register-NativeMethod "user32.dll" "bool SetActiveWindow(IntPtr hWnd, int nCmdShow)"
Register-NativeMethod "user32.dll" "bool GetFocus(IntPtr hWnd, int nCmdShow)"


# This builds the class and registers them (you can only do this one-per-session, as the type cannot be unloaded?)
Add-NativeMethods

# (the Out-Null is just to throw away the return value)
# [NativeMethods]::SetForegroundWindow((Get-Process -name notepad).MainWindowHandle) | Out-Null
# [NativeMethods]::ShowWindowAsync((Get-Process -name notepad).MainWindowHandle, 2) | Out-Null
# [NativeMethods]::SetActiveWindow((Get-Process -name notepad).MainWindowHandle, 2) | Out-Null

Need help passing the OU path string variable to the New-ADUser cmdlet

$
0
0

Hello all!

I am trying to write a quick script that will allow my team to quickly create AD User accounts.  Here is my code so far:

*********************************************************************

$SamAccountName =  Read-Host 'Please input DomainID'
$GivenName = Read-Host 'Please input First Name of user'
$SurName = Read-Host 'Please input Last Name of user'
$DisplayName = Read-Host 'Please input the Display Name for the user'
$Description = Read-Host 'Please input a Description for this account'
$AccountPassword = Read-Host 'Please input a Password for this account'
$Manager = Read-Host 'Please input the DomainID of the manager of this account'
$Path = Read-Host 'Please input the OU path for this account'

New-ADUser -SamAccountName $SamAccountName -Name $SamAccountName -givenname $GivenName -surname $SurName -displayname $DisplayName -description "$Description" `
-AccountPassword (ConvertTo-SecureString -AsPlainText "$AccountPassword" -Force) -Enabled $true `
-Manager $Manager -path $Path

**********************************************************************

Everything works fine, up until "-path $Path" in the New-ADUser cmdlet.  No matter what I try (single quotes, double quotes, no quotes), I get a bad syntax error.

But, if I replace the $Path = Read-Host line with $Path = '<ou path>' OR I replace "-path $Path" in the cmdlet with "-path '<ou path>'" then the script works fine.

How do I get this script to accept the $Path string from the Read-Host input?

Thanks in advance.


Rename multiple computers in Active Directory

$
0
0

I have a script to rename computer in Active directory, and I receive the following error:

Computer name e033457-cal-ssg cannot be resolved with the exception: No such host is known

Here is the script:

$a = Import-Csv ComputerNames.csv -Header OldName, NewName
Foreach ( $Computer in $a ) {Rename-Computer -ComputerName $Computer.OldName -NewName $Computer.NewName -Force -Restart}

I am running this from Windows 8.1 machine.  I have a GPO setup with firewall execeptions to allow remote access to domain computers.  Any suggestions would be appreciated.

How to consume output directed to a filepath?

$
0
0

$dpc = '"C:\Program Files (x86)\Intel\CLI\dpccli.exe" -o ' + $outfile ..."

Invoke-Expression "& $dpc"

The dpccli.exe program won't run without an output file path.  But I'd rather not write the output to disk because I need to perform processing before it's intelligible.  I'd just have to read it in again.

Is there some abstraction I can use to trick the program into thinking it's writing to a file and redirect output to a string?

How to remove a type added by Add-Type

$
0
0

Hi all,

I have a simple C# addition that is added to a PS session with "Add-Type -TypeDefinition $CreateArray" where $CreateArray contains the C# source. This works fine so far. The PS1 script creates the variable with the source and executes the Add-Type cmdlet as shown above.

When I change something in the C# source, the source is not compiled and the statement is ended with the message "Add-Type : Cannot add type. The type name 'TypedArray.NewArray' already exists." I expected this.But how can I remove this type definition or replace it with a new one compiled from a changed "inline" source?

Help did not say anything on removing added types. 


Regards Jörg

i want to find windows 8 product key

$
0
0
Hi
i am new to PowerShell and am looking for a script that can be run against a list of windows server 2008 64bit, windows server 2008 R2 64bit

Which firewall port(s) required for using get-adgroupmember -server option

$
0
0
I need to query out DMZ domain from our internal network by using get-adgroupmember, instead build remote PS session (port 5985/5986).  I found that get-adgroupmember could specific -server option, but which port is this option use to make connection through DMZ firewall?  That to say if I issue get-adgroupmember -server "server1.dmz.com:XXXX"?  Thanks a lot.

Passing Array values to listbox

$
0
0

Hi,

 

I'm trying to pass the the following Array values in to a list box using Power shell

$values =@('Test1','Test2','Test3','Test4').

Out put of list box show as 

Test1 Test2 test3 Test4.

I need to get all these items one by one in the list box

Test1

Test2

Test3

Test4.

Please advise.

Thanks

Windows PowerShell

$
0
0

I got "Windows Power Shell has stopped working" pups up twice every time I power on my pc. I ran SFC scan one time already, it does not help. What else I can do? Please help


Copy and paste entire row in Excel

$
0
0

Hey Guys/Gals,

I was wondering if anyone knew how to cut an entire row in excel and paste it in a different row.  Say, cut row 250 and paste it in Row 100.

What I have doesn't quite work.  The Cutting does, but not the pasting.  What I get with the paste is

Method invocation failed because [System.__ComObject] doesn't contain a method named 'paste'.

Here is the code so far:

$xl = New-Object -COM "Excel.Application"
$xl.Visible = $true

$wb = $xl.Workbooks.Open("C:\ReportProject\Test.xlsx")
$ws = $wb.Sheets.Item(13)

$rows = $ws.UsedRange.Rows.Count

[void]$ws.Cells.Item($count,1).EntireRow.insert()
$OldRange = $ws.Cells.Item(250,1).EntireRow
[void]$OldRange.Select()
[void]$OldRange.Cut()
[void]$ws.Cells.Item(100,1).EntireRow.paste()


$wb.Close()
$xl.Quit()
Thanks in advance!! :)

Use a PowerShell script as generic script for failover cluster

$
0
0

Hello,

it is possible to use a VB script as generic script resource in a failover cluster: https://msdn.microsoft.com/en-us/library/aa372846%28v=vs.85%29.aspx

Is it possible to do the same with powershell? And if yes is there a sample somewhere available.

Thanks,

Daniel

how to make a .exe application to run in background

$
0
0

we have developed a executable file(.exe application),i.e running successfully when system boots up. but we want that application to run in background without any command prompt window pop up.

i have tried with some vbs scripts,but its failing to run in background, let me know if any solution available to this problem.

sample vbs script:

Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "C:\Windows\System32\netsh.exe" & Chr(34), 0
Set WshShell = Nothing 

Powershell Script add users problem

$
0
0

I need help with running a script. I am new to powershell. I just installed server 2008 r2. I am studying for the 70-640 test. I created a simple script for adding users from a csv file. It worked flawlessly. I modified the script to add more attributes. Ran the script and got errors. While troubleshooting the errors, I came accross a web site and ran these commands "Get-WindowsFeature RSAT-AD-PowerShell | Add-WindowsFeature" and " Import-Module ActiveDirectory". After that I decided to run the original script which ran flawlessly several times. It will not work without errors. I cant tell you how frustrating this is. I have been searching the web for hours. I need to get past this. Here are the files.

userimport.ps1

$objOU=[ADSI]"LDAP://OU=People,DC=contoso,DC=com"
$dataSource=import-csv "NewUsers.csv"
foreach($dataRecord in $dataSource)
{
    #map variables to data source
    $cn=$dataRecord.cn
    $sAMAccountName=$dataRecord.sAMAccountName
    $givenName=$dataRecord.FirstName
    $sn=$dataRecord.LastName
    $displayName=$sn + ", " + $givenName
    $userPrincipalName=$givenName + "." + $sn + "@contoso.com"

    #create the user object
    $objUser=$objOU.Create("user","CN="+$cn)
    $objUser.Put("sAMAccountName",$sAMAccountName)
    $objUser.Put("userPrincipalName",$userPrincipalName)
    $objUser.Put("displayName",$displayName)
    $objUser.Put("givenName",$givenName)
    $objUser.Put("sn",$sn)
    $objUser.SetInfo()
    $objUser.SetPassword("P@ssword")
    $objUser.psbase.InvokeSet("AccountDisabled",$false)
    $objUser.SetInfo()
    }

NewUsers.csv

cn,sAMAccountName,FirstName,LastName
John Woods,john.woods,Johnathan,Woods
Kim Akers,kim.akers,Kimberly,Akers

Taken right from the book

What the heck happened? Can someone tell me how to reset powershell. I noticed that the version is

Major  Minor  Build  Revision
-----  -----  -----  --------
2      0      -1     -1

I dont know which version is installed with 2008 r2. But i need help.

Get-Winevent unique and sorted - little help needed

$
0
0

Hello,

I am still new to PowerShell and I found interesting problem to solve.

Task is this: I need to export unique Application and System events (Critical,Error and Warning) for last 7 days.

Preferably i need only unique events. However, i can't just select unique events by ID, since that might skip some important ones. For example, if 2 services fail, that will generate 2 events with same ID, but with different ProviderName.

Here is what i got so far:

$SevenDays = (Get-Date).AddDays(-7)

Get-WinEvent -FilterHashTable @{LogName='SYSTEM';StartTime=$SevenDays} -ErrorAction SilentlyContinue |
where {$_.LevelDisplayName -eq "Critical" -or $_.LevelDisplayName -eq "Error" -or $_.LevelDisplayName -eq "Warning"} |
Sort-Object ProviderName |
Format-List TimeCreated,LogName,ProviderName,Id,LevelDisplayName,Message -GroupBy ProviderName

This gives me all events in last 7 days, sorted by ProviderName.

I was able to get unique events (by using: sort-object ID -unique) but i need combination of that and of example above.


What i need is to have unique IDs for each "group" (ProviderName). So same ID can be in multiple groups, but always just one event with same ID in one group.

Or other solution will be to figure out other way how to get all unique events but still get rid of the repeating ones. Selecting unique message or time is not working very well since those are always different.

I would appreciate any suggestions or pointers.

Thanks in advance :)

Viewing all 21975 articles
Browse latest View live


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