Quantcast
Channel: The Official Scripting Guys Forum! forum
Viewing all 15028 articles
Browse latest View live

Enabling Windows ICS from PowerShell

$
0
0

I am trying to use Windows ICS to share the computer's internet connection with a separate adapter in PowerShell. This is what I have so far:

# Register the HNetCfg library (once)
regsvr32 hnetcfg.dll

$MainAdapter = Get-NetAdapter | Where-Object {$_.MediaConnectionState -eq 'Connected' -and $_.PhysicalMediaType -ne 'Unspecified'} | Sort-Object LinkSpeed -Descending

function EnableICS([string]$ID)
{
    # Create a NetSharingManager object
    $m = New-Object -ComObject HNetCfg.HNetShare

    # List connections
    $m.EnumEveryConnection |% { $m.NetConnectionProps.Invoke($_).Guid }

    # Find connection
    $c = $m.EnumEveryConnection |? { $m.NetConnectionProps.Invoke($_).Guid -eq $ID }

    # Get sharing configuration
    $config = $m.INetSharingConfigurationForINetConnection.Invoke($c)

    # See if sharing is enabled
    Write-Output $config.SharingEnabled

    # See the role of connection in sharing
    # 0 - public, 1 - private
    # Only meaningful if SharingEnabled is True
    Write-Output $config.SharingType

    # Enable sharing (0 - public, 1 - private)
    $config.EnableSharing(0)

    # Disable sharing
    #$config.DisableSharing()
}

EnableICS($MainAdapter.InterfaceGuid)

It works, but only on systems with two network adapters. ICS needs an adapter as an input, and another as an output.  In the ICS GUI, when there are more than two adapters, it asks for a "Home network connection" that it uses as the output. But when I run this code, it doesn't specify the other adapter, so it doesn't do anything. How can I specify that other adapter in my script?


Wasabi Fan


Passing Windows credentials with xDatabase

$
0
0

The example scripts to deploy dacpac/bacpac are using credentials that need to have SQL authentication enabled on the server. I verified with SQL authentication and am able to deploy the dacpac to my target server.

How can I run the scripts to use network credentials/SSPI?

Best regards

Kishore


Kishore

Scheduled Batch doesnt rename, manual batch renames perfect

$
0
0

I have a batch program that looks at a directory and renames ever file. When I run the batch program manually it renames without issues. When I schedule the batch program, it does not rename.

Here is the code.

@ECHO OFF
SETLOCAL ENABLEDELAYEDEXPANSION
CD ../Open_PO
FOR /f "tokens=*" %%a IN ('dir /b "Open Purchase Order-en-us-"*') DO (
SET "oldName=%%a"
SET "newName=!oldName:Open Purchase Order-en-us-=!"
ECHO Renaming !oldName! to !newName!
RENAME "!oldName!" "!newName!"

EXIT

Powershell Workflow. Test-Connect error: Error due to lack of resources

$
0
0

Hi!

I use Test-Connection Cmdlet to ping a lot of PCs with workflow script (throttlelimit 5).

Sometimes I get error message:

Test-Connect error: Error due to lack of resources.

When I use same script without workflow (10 copies of ps1-file) at the same PC, I don't get error message.

Powershell 4.0

Windows 7 SP1 Enterprise, installed all updates.

Intel Pentium Dual CPU E2180 @ 2.00 GHz

Memory - 4 GB

Pagefile is enabled.

find and replace text in a txt file from a lookup csv

$
0
0

Hi

I am a very basic PS user and i think it is great but am struggling with this one.

I have a text file which was generated by Subinacl. I am migrating data to a new domain and the user names and user folders need to be changed.

There are potentially 100s/1000s of users affected.

I need to search the text file and use the csv file with two columns as a lookup

one for the user to find, the other with what needs replacing.

I would like to write the updated text file to a new file to preserve my existing file.

can anyone help me?

All help would be most welcome

Fuzzy logic

How to Search for a Specific file on Remote Computers

$
0
0

This works on my local machine but not when I try to run on remote Machine

$logFile = 'c:\scripts\file\test.log'
##$Filename1 = "$env:LOCALAPPDATA\Temp\filetest.pdf"
##$Filename2 = "$env:LOCALAPPDATA\Temp\filetest.exe"

If (Test-Path $Filename1){
Write-Host "Exist"
}Else{
Write-Host "Does Not Exist"
}
If (Test-Path $Filename2){
Write-Host "Exist"
}Else{
Write-Host "Does Not Exist"
}

The Biggest problem is trying to figure out the path since it is in user profiles??


VBScript GetVirtualSystemThumbnailImage help!

$
0
0

Hey All!

I am writing an HTA application (some of you may have seen some of my other questions), and I am now stuck on the thumbnail image of a VM. I am taking the VBScript example from here:

https://msdn.microsoft.com/en-us/library/cc160707(v=vs.85).aspx

with slight modifications for root\virtualization\v2, but when I run it, all I get is a WScript.Echo "Done" and a log file with "Done" in it. I see two subs in the example to write the image (SaveThumbnailImage and PrintThumbnailImage), but they are never actually called in the script. Any attempts to call those with OutParams.ImageData error with a type mismatch.

Particularly, if you copy and paste the example, the mismatch error is on line 80 with the "stream.WriteText text".

Are the [] brackets shown in the above link required when passing the data to the sub? As in: SaveThumbnailImage(objOutParams.ImageData[])

I have seen the PowerShell examples, and I can get the PowerShell example to work, but being an HTA, I need this to work with VBScript. Has anybody successfully gotten a VBScript to output a thumbnail image? Any tips on getting this to work?

Thank you in advace!

Eric

EDIT: Tried adding the brackets [], but it throws an error "Expected ')'". Doesn't seem to like the brackets.

What exactly is being created with the ADODB.stream? Is that the issue? This one is new to me. I have .NET 3.5 and .NET 4.5 installed.

To Note, I have seen the PowerShell examples, and I am currently using that to get the thumbnails, but calling the PowerShell script with parameters is not working directly from the HTA. I have to call a VBScript with parameters, then the VBScript calls the PowerShell script. Ugly, but that's the only thing I have gotten to work so far. I would much rather just have VBScript entirely within the HTA.


Set-acl giving error!

$
0
0
My goal: copy files and folders and keep the structure from source to destination and after copying set-acl from source to destination. copying works fine but when it comes to set-acl part, it fails.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
$Source = 'C:\utdelat\A\Capsules'$Destination = 'C:\utdelat\c\Capsules'$Files = Copy-Item -Path $Source -Destination $Destination -Recurse -PassThru -ErrorAction stop -Force  -Verbose$SFileFullName = Get-ChildItem -Path $source -Recurse | ForEach-Object {$_.FullName}$ACLS = Get-Acl -Path $SFileFullName$DFileFullName = Get-ChildItem -Path $Destination -Recurse | ForEach-Object {$_.FullName}foreach ($ACLin$ACLS){try{Set-Acl -Path $DFileFullName -AclObject $ACL -Verbose
                        }catch{write-error$_.exception
                            }
                        }
the error message:
1
2
3
4
5
6
Set-Acl: The security identifier is not allowed to be the owner of this object.
At line:9 char:29+                             Set-Acl -Path $DFileFullName -AclObject $ACL -Verbos ...+                             ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : InvalidOperation: (C:\utdelat\c\Ca...ng Pattern.cpsx:String) [Set-Acl], InvalidOperationException+ FullyQualifiedErrorId : System.InvalidOperationException,Microsoft.PowerShell.Commands.SetAclCommand

Script to remove all printers

$
0
0

I'm trying to find a script to remove all current and stale printers on some TS sessions.  I've tried a couple of scripts but they all seem to error one way or another.  Firstly I've tried

strComputer = "."
Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colInstalledPrinters = objWMIService.ExecQuery _
("Select * From Win32_Printer Where Network = True")
For Each objPrinter in colInstalledPrinters
objPrinter.Delete_
Next

But I get an invalid parameters on Line 6 with code 80041008 and source SWbemObjectEx.  I've also tried

'Define Variables and Objects.
Set WshShell = CreateObject("Wscript.Shell")

Const NETWORK = 22

Set objNetwork = CreateObject("WScript.Network")

strComputer = "."

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\cimv2")
Set colPrinters = objWMIService.ExecQuery("Select * From Win32_Printer")

For Each objPrinter in colPrinters
    If objPrinter.Attributes And NETWORK Then
        strPrinter = objPrinter.Name
        objNetwork.RemovePrinterConnection strPrinter
    End If
Next

'Note: Gpupdate command has to be run twice as the ECHO command can't answer more than one question.

'Refresh the USER policies and also answer no to logoff if asked.
Result = WshShell.Run("cmd /c echo n | gpupdate /target:user /force",0,true)

'Refresh the Computer policies and answer no to reboot.
Result = WshShell.Run("cmd /c echo n | gpupdate /target:computer /force",0,true)

'Hand back the errorlevel
Wscript.Quit(Result)

But with this one I get an error on line 16 with 'This network connection does not exist' and code 800708CA and source WSHNetwork.RemoveNetworkDrive.

Only solution at the moment I can think of is to just remove them all from the registry but would rather do it user based via script.

Logon Script with Credential

$
0
0

Hello everybody.

Let me explain my problem. 

I have a Powershell shell Logon Script for a Domain user without privileges that has to:

  • Run IE as Domain user.
  • When user close al IE open windows, Script have to make some process as soon as finish, script run again IE.
  • The user that run the script doesn’t have any kind of access to the any drive and doesn’t have any access to any app or windows config setting, he has only access to IE through Powershell Logon Script, no more.
  • I gave to user privileges as a part of the operating system through GPO.

Well, let me show you the script before continue with the explanation: 

Function fCredenciales([String]$FileTXT, [String]$UserIE)

{

               $UsIE1       = Get-Credential -Credential $UserIE 

              $SecureIE  = $UsIE1.Password

               $BytesIE    = ConvertFrom-SecureString $SecureIE

               $BytesIE   | Out-File $FileTXT

}

 

#------------------------------------------------#

#                     SCRIPT                               #

#------------------------------------------------#

$Folder  = "C:\Cred"

$FileIE   = $Folder + "\IE.txt"

$UsIE     = "Domain\User"

 

If(-Not (Test-Path $Folder))

{

               New-Item $Folder -Type Directory

                fCredenciales $FileIE $UsIE

}

If (-Not (Test-Path $FileIE))

{

               fCredenciales $FileIE $UsIE

}

 

$UsIETxt   = Get-Content $FileIE | ConvertTo-SecureString

If ($UsIETxt -eq $Null)

{

               fCredenciales $FileIE $UsIE

}

#------------------------------------------------#

 

$UsuarioIE      = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList $UsIE, $UsIETxt

$MyNetwork    = Get-WMIObject Win32_NetworkAdapterConfiguration -ComputerName LocalHost | Where-Object { $_.IPAddress -ne $null } # | Select-Object IPAddress

$MyIPAddress = $MyNetwork.IPAddress[0]

$URL                   = "https://www.mywebpage.com/?qwerty="+ $MyIPAddress + " -private"

$IE                       = "C:\Program Files\Internet Explorer\iexplore.exe"

 

#------------------------------------------------#

While ($True)

{

    Start-Process $IE -ArgumentList $URL -ArgumentList $URL  -Credential $UsuarioIE

    $IDProcess = Get-Process -Name iexplore | ?{$_.MainWindowTitle} | %{$_.ID}

    Wait-Process -Id $IDProcess

 

    #------------------------------------------------#

    # Proccess 1                                              #

    #------------------------------------------------#

                                  .

                                 .   

    #-------------------------------------------------------------#

    # Process2                                                                 #

    #-------------------------------------------------------------#

    .

    .

    .

}

I need to execute IE as other user.

As logon user doesn’t have drive access, he cannot read credential.

If logon script wants to ask for credential, credential windows never shown.

I don’t know why, but if the user hasn’t  administratives privilegesStart-Proccess with –Credential doesn´t work, exactly as Wait-Process -Id $IDProcess.

The security department wants:

  • User Without any access (No drives, no menu, no nothing J).
  • Script has to run IE as domain simple user.
  • If script needs administrative privileges to run  Wait-Window the script can be run as administrative user, but not the Start-Process.

 I hope that you can understand me.

 

Thanks in advanced,

Angel Biurrun C.

Powershell Startup Script GPO Not yet been run

$
0
0

Hi Guys and Gals,

I would really appreciate some help on this one, i am learning power shell but actually being able to execute scripts on start up woudl help a lot on this.

We have server 2012 R2 and Windows 8.1 machines SCCM configured pretty well.

We are trying to find a work around for a buggy load of samsung tablets which have a wireless adapter which only seems to work by disabling and enabling. Once you reboot it shows as being active in Deivce Manager but only is able to work (no SSID's appear) once you disable/enable, So i came up with the workaround of a powershell startup script to disable and enable the adapter, this works from the shell in theory if you run it as admin, it basically is this:

disable-netadapter wifi -Confirm:$false

enable-netadapter wifi -Confirm:$false

Works a treat once you have logged in but we need it to run pre-logon otherwise obviously we will have mobile DC Synch issues if we attempt to issue any.

We have copied it to the sysvol folder, checked the Domain Computers security group is added. Moved it to the sys32 folder on the local box to test, still not executing, also added in 'set-execution policy bypass, still nothing on reboot

GPResult /v brings up info that it is there and present in the GPO but says : This script has not yet been run

Any ideas on this? Help, pretty please with sugar on top.

Table of contents with hyperlinks

$
0
0

I have a folder with 20 subfolders and over 400 files; how can I create a table of contents with hyperlinks to the files?  I want the link to display the first line of the word document as the hyperlink text.  This could all be done manually but doing it with a powershell script would really save time as this needs to be done periodically.  Thanks for all your help.

Thanks

Jerry


Jerry Becker

Powershell Get-ADUser returns Computer objects as well ???! How to prevent.

$
0
0

I ran the following script and got a bunch of computer objects in my csv. How to i Prevent this? I already tried using 

Where-Object{$_.type-eq"user"} OR

 -filter{type-eq"user"}

script:

Get-ADUser-Filter*-PropertiessamAccountName,accountExpires,Created,LastLogonTimeStamp,Department,physicalDeliveryOfficeName,employeeID,AccountExpirationDate,Manager|

Where-Object

{$_.accountexpirationdate-lt$timex}|


select

Name,samAccountName,@{Name="Timestamp"; Expression={[DateTime]::FromFileTime($_.lastLogonTimestamp)}},@{n='Date Created';e={$_.created}},Department,@{n='Location';e={$_.physicalDeliveryOfficeName}},employeeID,AccountExpirationDate,@{Label='Manager sAMAccountName';Expression={(Get-ADUser$_.Manager).sAMAccountName}},@{Label='Manager Name';Expression={(Get-ADUser$_.Manager).name}}|


export-csv

-path$mypath-notypeinformation


New Powershell User. Stuck on Get-User. Please Help!

$
0
0

Hi. This is my first post here. I am new to Powershell and am trying to pull a list of users in a specific OU in AD that have not logged in for 1 year. I then need to sort them by a certain set of characters contained within their Display Name. So far, here's the code I have written and it's not working. It's probably a new user mistake, but I have done some searching and tried different things with no luck.

$Properties =
@('samAccountName' ,'EmailAddress' , 'DisplayName' , 'LastLogonDate')

$searchbase = "OU=OUNAME,DC=DC1,DC=DC2,DC=DC3,DC=DC4

$time = (Get-Date).AddYears(-1)

Get-ADUser - Filter * -Properties $Properties -Searchbase $searchbase | Select $Properties | Where {_.LastLogonDate -lt $time} | Export-CSV -Path "C:\Users\NEWPOWERSHELLUSER\Desktop\WHYISNTTHISWORKING.CSV

Powershell update-help issue

$
0
0

Help please! I am going through the powershell jumpstart tutorial and have come to the point where I enter -

update-help

When I press enter I get an error stating that it is not recognised as the name of a cmdlet. Before anyone asks I am definitely running powershell as administrator.

What am I doing wrong?


Jeet S


Create Batch file to delete files and subfolders, but not root folder

$
0
0
Good evening,

Does anyone know an efficient way of deleting files and subfolders in a shared folder, but not deleting the root folder?

my goal is to create a batch file that starts every Friday evening as scheduled task which deletes the contents of a shared folder (files and subfolder) without removing the root directory, the fact of using the command "md" will not return the same access rights.

Thank you in advance for your assistance.

change of samaccountname

$
0
0

I need to change all users logon name in AD to their (first letter of first name.last name)    Server 2008

Query array tables

$
0
0

I have two CSV files and I need to use one column from one csv file as a key into other csv file and get value from another column based on it.

e.g.  CSV 1

name,emp-id,title,manager

john,123,cpa,peter

peter,345,manager,russell

CSV 2

dept,emp-id, manager-id

it,123,345

So what i need is use manager-id from CSV 2 file and use it as a key to look into CSV1 file against emp-id column and then get corresponding name

so from example, use 345 from CSV 2 as key to look up name peter from CSV 1

Set service status into Stop_Pending

$
0
0

Hello All,

I wrote a powershell script to check if service status is in stop pending state or start pending state.

how do i change the service status into Stop_Pending status for a testing purpose? It helps me to check my script is working or not.

Is there any tool to test this like stress test for CPU and memory?

Regards,

Mac

Help with script to automate selections in disk cleanup

$
0
0

Hello All,

      I use a script to run disk cleanup in task manager(cleanmgr.exe /sagerun:n (where "n" is any number - I use 99)). After I drop this in task manager I then have to manually configure the settings in disk cleanup using "cleanmgr.exe /sageset:99". What I am looking for is a way to script the selection of the boxes that you need to check or uncheck during manual configuration of cleanmgr.exe /sageset:n. If I had a script that would do this, I could use group policy to deploy a sript to load all these settings without the manual intervention. Then I would use GPP to set the schedule of when clean manager runs. That is the goal - to automate this so I don't have to manually configure this on almost 200 workstations and laptops. Any help would be greatly appreciated.

Sincerely,

Brian

Viewing all 15028 articles
Browse latest View live


Latest Images

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