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

-match a system.date with a string

$
0
0

Hi,

I've got a system.date file variable that I comes back as an object and I want to match it to a variable in date format that is a string.  Is this possible?

Here is my code:

$dtime = [datetime]::parseExact($USDate, "dd/MM/yyyy",$null)
$USDate = $dtime | get-date -format dd/MM/yyyy

If I write-host on $USDate it comes back as follows (as a string)

30/09/2018

The system.date object looks like this and is a true system date:

LastModified:   30/09/2018 02:26:24

When I try and match the 2 it never finds it  I've tried -like and -match which technically should work.

Here is my where clause:

$count = get-s3object -bucketname $bucketname | where {$_.key -like 'ierter/*' -and $_.StorageClass -like 'Standard' -and $_.lastmodified -like $USDate}


Clone Windows 10

$
0
0
Does Powershell have ability to CLONE current Windows 10 disk to an external USB disk as a backup? Thanks

Get-WMIObject - ForEach - Offline Files Trouble

$
0
0

Trying to write a quick PS command to see which computers in an AD OU have Offline Files turned on. Here's what I've used so far:

get-adcomputer -filter * -searchbase "ou=computers, ou=it, ou=staff, dc=domain, dc=domain, dc=com" |foreach {get-wmiobject Win32_OfflineFilesCache} | select-object pscomputername,active

Much of this code works, but put all together I am having trouble pulling the list and which ones are active/inactive for Offline Files. What the code does is return a full count of the machines in an OU, but for each <g class="gr_ gr_479 gr-alert gr_gramm gr_inline_cards gr_run_anim Punctuation only-ins replaceWithoutSep" data-gr-id="479" id="479">entry</g> it's just my own computer name and status. Like this:

PSComputerName active
-------------- ------
LT-IT-CH         True
LT-IT-CH         True
LT-IT-CH         True
LT-IT-CH         True
LT-IT-CH         True

It seems to be just using my local machine and status and not properly pulling.. probably something simple I'm forgetting, and I know <g class="gr_ gr_757 gr-alert gr_spell gr_inline_cards gr_run_anim ContextualSpelling ins-del multiReplace" data-gr-id="757" id="757">WMIObjects</g> can get funky. Any ideas?

Add user to Remote Admin group on multiple hosts

$
0
0

I am using the following code to add a single user to the Admin group on multiple hosts.

param(
        [string] $Domain,
        [string] $UserName
    )

$ComputerListFile = "D:\Scripts\AddWindowsUser\ComputerList.txt"
$ComputerList = Get-Content $ComputerListFile -ErrorAction SilentlyContinue

foreach( $Computer in $ComputerList) {
    $Group = [ADSI]"WinNT://$Computer/Administrators,group"
    $User = [ADSI]"WinNT://$Domain/$UserName,user"
    $Group.Add($User.Path)
}

When I try to execute using the following command,

.\AddWindowsUser.ps1 -Domain "AD" -User "356989"

I get the following error,

distinguishedName : 
Path              : WinNT://computername.domain.global/Administrators,group

The following exception occurred while retrieving member "distinguishedName": "The network 
path was not found."+ CategoryInfo          : NotSpecified: (:) [format-default], ExtendedTypeSystemException+ FullyQualifiedErrorId : CatchFromBaseGetMember,Microsoft.PowerShell.Commands.FormatDefaultCommand

What is the error here? 

How do you what unit of measure a property is when it returns a result

$
0
0

How do I know what units of measure a property of an object returns.  If it is a measure of memory, is it in KB, MB, GB or if it is a measure of time is it in seconds, minutes, days.

For example, when I run... 

get-Process | Get-Member

...I don't see an unit of measure associated with the properties.

There is probably an easy answer to this but it is escaping me right now.



Get-PSRepository WARNING: Unable to find module repositories. Unable to install SQL module, no repositories.

$
0
0

Hello, guys,

Im unable to find repositories. What could be wrong? 

PS C:\> Get-PSRepository
WARNING: Unable to find module repositories.

PS C:\> Register-PSRepository -Default -Verbose

VERBOSE: Performing the operation "Register Module Repository." on target "Module Repository 'PSGallery' () in provider 'PowerShellGet'.".

PS C:\> Get-PSRepository

WARNING: Unable to find module repositories.

Powershell - Unable to install PackageProvider

$
0
0

Hello, 

Why i am unable to install package provider via powershell? 

PS C:\> Install-PackageProvider -Name 'Gistprovider' -Verbose
VERBOSE: Using the provider 'Bootstrap' for searching packages.
VERBOSE: Finding the package 'Bootstrap::FindPackage' 'Gistprovider','','','''.
VERBOSE: Using the provider 'PowerShellGet' for searching packages.
VERBOSE: The -Repository parameter was not specified.  PowerShellGet will use all of the registered repositories.
Install-PackageProvider : No match was found for the specified search criteria for the provider 'Gistprovider'. The package provider requires 'PackageManagement' and 'Provide
r' tags. Please check if the specified package has the tags.
At line:1 char:1+ Install-PackageProvider -Name 'Gistprovider' -Verbose+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~+ CategoryInfo          : InvalidArgument: (Microsoft.Power...PackageProvider:InstallPackageProvider) [Install-PackageProvider], Exception+ FullyQualifiedErrorId : NoMatchFoundForProvider,Microsoft.PowerShell.PackageManagement.Cmdlets.InstallPackageProvider

Move filenames based on pattern

$
0
0

I was trying to build a script to move specific files from one location to another. When I run this script with powershell it also moves files with the wrong pattern. For example below I would like to move specific file name which names start with 40001- or higher and less then 50000-. 

Get-ChildItem $path -file  | Where-Object { $_.Name -gt "40001+-*" -and $_.Name -lt "50000+-*" } | Move-Item -destination $path -whatif

If we have a look to the result, we can see that also filenames which didnt had to be moved like 432412... and 432416... are listed to move while only 40003... twice should had been moved. Can somebody tell me what I'm doing wrong?

Result: 

Mode                LastWriteTime         Length                 Name                                                                                                                      
----                -------------         ------ ----                                                                                                                      
-a----        24-5-2007     10:56         537510               40003-ABS-01022006.pdf                                                                                                    
-a----       28-11-2013     14:11         163500              40003-DRINK-04122013.pdf                                                                                                  
-a----        20-9-2018     14:37          40120                432412-cathver-10092018.pdf                                                                                               
-a----        11-9-2018     08:32         451972               432416-cathver-11092018.pdf  


Get partition style info for multiple computers

$
0
0

Dears,

I`m trying to get partition style info for multiple computers.

I have a list of computers = 1.csv

$comps = import-csv C:\tmp\1.csv
$result = ForEach-Object{  
   gwmi -Computer $comp -query "Select * from Win32_DiskPartition WHERE Index = 0" | 
   Select-Object DiskIndex, @{Name="GPT";Expression={$_.Type.StartsWith("GPT")}}
    }

I got an error: gwmi : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

But when I`m writing computers name insteed $comp , it works.

Could you help me.

Re-writing this bit of code to output host name

$
0
0

Hi All,

I have the code below, it allows me to get IP addresses of host names. The issue I have is that i need the hostname and ip address on thesame line. At the moment, I can only get it on seperate lines. So what I want is

Hostname | IPaddress

So its pipe delimeted.

$a = get-content "C:\temp\list.txt"

foreach ($i in $a )
    {
			[System.Net.Dns]::GetHostAddresses($i)  | select IPAddressToString -ExpandProperty IPAddressToString
$i
			 
}


Help with WPF using Posh Powershell Pro Tools Visual Studio 2017

$
0
0

Hey all

I am semi new to working heavily with PowerShell and am working on building a WPF application using Posh Powershell Pro Tools and VS 2017. I have the GUI built and designed how I want it, I just don't know how to bind the buttons and event handlers properly. Basically, I would like for the first page to have a text box to gather input, and a button to take that input and change the name of a PC.

Here is my XAML code:

<Window

  xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

  xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

  Title="Windows Setup Automation" Height="350" Width="451.471"><Grid><Grid.RowDefinitions><RowDefinition Height="153*"/><RowDefinition Height="166*"/></Grid.RowDefinitions><Grid.ColumnDefinitions><ColumnDefinition Width="268*"/></Grid.ColumnDefinitions><Label Content="Type in value of computer name and click &quot;Set Computer Name&quot;" HorizontalAlignment="Left" Margin="10,57,0,0" VerticalAlignment="Top" Width="348" Height="26"/><Button x:Name="firstNext" Content="Next" HorizontalAlignment="Right" VerticalAlignment="Bottom" Width="66" Margin="0,0,14,10" Height="20" Grid.Row="1" Click="firstNext_Click"/><TextBox x:Name="firstComputerNameInput" HorizontalAlignment="Left" Height="22" Margin="38,90,0,0" TextWrapping="Wrap" Text="Type computer name here" VerticalAlignment="Top" Width="120" TextChanged="TextBox_TextChanged" FontStyle="Italic" FontSize="10"/><Button x:Name="firstbuttonSetComputerName" Content="Set Computer Name" HorizontalAlignment="Left" Margin="163,91,0,0" Width="122" Click="firstbuttonSetComputerName_Click" VerticalAlignment="Top"/><Button x:Name="firstPrevious" Content="Previous" Margin="0,0,85,10" VerticalContentAlignment="Center" Grid.Row="1" VerticalAlignment="Bottom" HorizontalAlignment="Right" Width="75" Click="firstPrevious_Click"/></Grid></Window>

Here is my PowerShell code:

function Add-ControlVariables {
New-Variable -Name 'firstComputerNameInput' -Value $window.FindName('firstComputerNameInput') -Scope 1 -Force	
New-Variable -Name 'firstbuttonSetComputerName' -Value $window.FindName('firstbuttonSetComputerName') -Scope 1 -Force	
New-Variable -Name 'firstPrevious' -Value $window.FindName('firstPrevious') -Scope 1 -Force	
New-Variable -Name 'firstNext' -Value $window.FindName('firstNext') -Scope 1 -Force
}

function Load-Xaml {
	[xml]$xaml = Get-Content -Path $PSScriptRoot\FirstPage.xaml
	$manager = New-Object System.Xml.XmlNamespaceManager -ArgumentList $xaml.NameTable
	$manager.AddNamespace("x", "http://schemas.microsoft.com/winfx/2006/xaml");
	$xaml.SelectNodes("//*[@x:Name='firstComputerNameInput']", $manager)[0].RemoveAttribute('TextChanged')
	$xaml.SelectNodes("//*[@x:Name='firstbuttonSetComputerName']", $manager)[0].RemoveAttribute('Click')
	$xaml.SelectNodes("//*[@x:Name='firstPrevious']", $manager)[0].RemoveAttribute('Click')
	$xaml.SelectNodes("//*[@x:Name='firstNext']", $manager)[0].RemoveAttribute('Click')
	$xamlReader = New-Object System.Xml.XmlNodeReader $xaml
	[Windows.Markup.XamlReader]::Load($xamlReader)
}

function Set-EventHandlers {

	$firstComputerNameInput.add_TextChanged({
		param([System.Object]$sender,[System.Windows.Controls.TextChangedEventArgs]$e)
		TextBox_TextChanged($sender,$e)
	})
	$firstbuttonSetComputerName.add_Click({
		param([System.Object]$sender,[System.Windows.RoutedEventArgs]$e)
		firstbuttonSetComputerName_Click($sender,$e)
	})
	$firstComputerNameInput.add_TextChanged({
		param([System.Object]$sender,[System.Windows.Controls.TextChangedEventArgs]$e)
		TextBox_TextChanged($sender,$e)
	})
	$firstPrevious.add_Click({
		param([System.Object]$sender,[System.Windows.RoutedEventArgs]$e)
		firstPrevious_Click($sender,$e)
	})
	$firstNext.add_Click({
		param([System.Object]$sender,[System.Windows.RoutedEventArgs]$e)
		firstNext_Click($sender,$e)
	})

}

$window = Load-Xaml
Add-ControlVariables
Set-EventHandlers

function TextBox_TextChanged
{
	param($sender, $e)
}


function firstbuttonSetComputerName_Click
{
	param($sender, $e)
}


function firstPrevious_Click
{
	param($sender, $e)
}


function firstNext_Click
{
	param($sender, $e)
}


$window.ShowDialog()

Any help would be greatly appreciated! Please let me know if there is any additional information I can provide.

Change a tag in Web.config

$
0
0

Dear All,

I have a tag in my web.config file like this

<compilation debug="true" targetFramework="4.5">

I want to change the value from true to false. I have started to write the powershell script  but I am stuck

$webConfig = '.\web.config'
[xml]$web =  (Get-Content $webConfig)
//I think the change script should go here. But I don't know what to write
$web.Save($webConfig)

Any help would be greatly appreciated.

I do not understand why this does not work now

$
0
0

${c:\scripts\install.txt} = ${c:\scripts\install.txt} -replace '"'
${c:\scripts\test.txt} = ${c:\scripts\test.txt} -replace '"'
$test = Get-Content "C:\scripts\test.txt"
$install = Get-Content "c:\scripts\install.txt"

Foreach ($test in $test) {

Get-Service remoteregistry -ComputerName $test | start-service
mkdir \\$test\C$\install
#Copy-item "$install" -container -recurse \\$test\c$\windows\temp
Copy-item "$install" -container -recurse \\$test\c$\install
#([WMICLASS]"\\$test\ROOT\CIMV2:Win32_Process").Create(“psexec ")
#c:\scripts\pstools\psexec \\$test c:\windows\temp\package\install.cmd
c:\scripts\pstools\psexec \\$test c:\install\package\install.cmd

The line I underline does not work now. I moved to different machine and I do not know I need to get this line to work. My old machine run Powershell ver 5.1 this works. I do not recall what I installed to get it to work before. It says that the Get-Service does not understand remoteregistry. 

Please help me 

How do you know what unit of measure a property is when it returns a result

$
0
0

How do I know what units of measure a property of an object returns.  If it is a measure of memory, is it in KB, MB, GB or if it is a measure of time is it in seconds, minutes, days.

For example, when I run... 

get-Process | Get-Member

...I don't see an unit of measure associated with the properties.

There is probably an easy answer to this but it is escaping me right now.




install-module command closes powershell window

$
0
0
When I run any install-module -name command such as install-module -name azuread, powershell does nothing for 2 or 3 seconds and then just closes. No error message and nothing is installed. This occurs on a new windows 10 machine, running PS in admin mode. Has anyone else seen this behavior?

How to stop getting prompted to "Confirm"

$
0
0

Hello,

I have some Windows Server 2008 systems that I'm trying to run a powershell script on to delete some temp files, but I keep getting prompted with "Confirm... Y [Yes] [A] Yes to All...... ect"  Is there a way to bypass the Confirm?

Thanks,

Tom


Tom Martin Email: tmartin@caa.com

Question on Get-FileShare Cmdlet

$
0
0

Good afternoon everyone...

Let me start by stating that I am in no way a master of scripting.  I do it only when I have a large project that requires one so please be kind.

My challenge at the moment is that I need to enumerate all shares on a number of machines.  Preferably through an input file and output the results into a file on a local drive named $input.txt / $input being the computer name in this instance.

The problem that I have is that I cannot figure out how to pass the variable $input into the -FriendlyName value.  If I can get that piece figured out, I'm ready to start rolling with the remainder of the script.

By the way - the value works fine when passed as a string rather than a variable but I do need to do this across several hundred PCs.  I have tried with single and double quotes, tried brackets, parenthesis and all that fun stuff...

Any help would be very much appreciated!

SCRIPT IN ITS MOST BASIC FORM

$input= import-csv "c:\temp\scripts\shares\pcs.csv"
ForEach ($name in $input){
echo $input
Get-FileShare (Get-StorageFileServer -FriendlyName $input) >> c:\temp\scripts\shares\$input.txt

}

Find a way to count the # of Encrypted drives

$
0
0

Hi, I need a simple script to count the number of bitlocker encrypted drives. I got into a crappy problem and I can't figure it out. see below:

PS C:\Users\MIKE> manage-bde -status
BitLocker Drive Encryption: Configuration Tool version 6.1.7601
Copyright (C) Microsoft Corporation. All rights reserved.

Disk volumes that can be protected with
BitLocker Drive Encryption:
Volume E: [New Volume]
[Data Volume]

    Size:                 98.23 GB
    BitLocker Version:    None
    Conversion Status:    Fully Decrypted
    Percentage Encrypted: 0%
    Encryption Method:    None
    Protection Status:    Protection Off
    Lock Status:          Unlocked
    Identification Field: None
    Automatic Unlock:     Disabled
    Key Protectors:       None Found

Volume F: []
[Data Volume]

    Size:                 21446.87 GB
    BitLocker Version:    Windows 7
    Conversion Status:    Fully Encrypted
    Percentage Encrypted: 100%
    Encryption Method:    AES 256
    Protection Status:    Protection On
    Lock Status:          Unlocked
    Identification Field: None
    Automatic Unlock:     Disabled
    Key Protectors:
        Password
        Numerical Password

Volume C: []
[OS Volume]

    Size:                 74.90 GB
    BitLocker Version:    None
    Conversion Status:    Fully Decrypted
    Percentage Encrypted: 0%
    Encryption Method:    None
    Protection Status:    Protection Off
    Lock Status:          Unlocked
    Identification Field: None
    Key Protectors:       None Found

PS C:\Users\MIKE> manage-bde -status | Select-String -Pattern "Protection Off"

    Protection Status:    Protection Off
    Protection Status:    Protection Off


PS C:\Users\MIKE> manage-bde -status | Select-String -Pattern "Protection On"

    Protection Status:    Protection On


PS C:\Users\MIKE> $drivesoff=(manage-bde -status | Select-String -Pattern "Protection Off")
PS C:\Users\MIKE> $driveson=(manage-bde -status | Select-String -Pattern "Protection On")
PS C:\Users\MIKE> $drivesoff.count
2
PS C:\Users\MIKE> $driveson.count
PS C:\Users\MIKE>

Look at the last line: $driveson.count gives me nothing. Looks like a nasty bug or did I do something stupid?

Thank you.

Query PC local Admin by win32_groupuser

$
0
0

Recently, I use gwmi win32_groupuser to find local PC adminstrator groups user

But in Network Packet capture, I found out that, it is going to use LDAP query DC, not only our DC, other trust domain also query?

Why???

Poweshell Form not closing

$
0
0

I am trying to create a Powershell form with three buttons.

The $form.Close() isn't working

Snippet of the code:

[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Drawing") 
[void] [System.Reflection.Assembly]::LoadWithPartialName("System.Windows.Forms")
[void] [System.Windows.Forms.Application]::EnableVisualStyles() 

$path = "C:\form\Output\text.xml"
$file_n = "test3"

#create form to confirm over-write
$Over_form = New-Object system.Windows.Forms.Form 
$Over_form.Text = 'Confirm'
$Over_form.Size = New-Object System.Drawing.Size(350,200)
$Over_form.StartPosition = 'CenterScreen'


$Over_lbl = New-Object system.Windows.Forms.Label
$Over_lbl.Size = New-Object System.Drawing.Size(349,100)
$Over_lbl.Font = New-Object System.Drawing.Font("Times New Roman",18,[System.Drawing.FontStyle]::Bold)
$Over_lbl.Text = 'NOTE:  Data exists for this system
Overwrite, Re-Open, or Cancel?'

$Over_form.Controls.Add($Over_lbl)

$Ovr_Btn_Over = New-Object System.Windows.Forms.Button
$Ovr_Btn_Over.Text = 'Overwrite'
$Ovr_Btn_Over.Location = New-Object System.Drawing.Point(10,102)
$Ovr_Btn_Over.Add_click({

	#double-check deletion
	$a = new-object -comobject wscript.shell 
		$intAnswer = $a.popup("Confirm Deletion", ` 
		0,"Delete Files",4) 
		If ($intAnswer -eq 6) { #confirmed
		    #delete entry in XML
			[xml]$xml_delete = Get-Content $path
			$xpath = "Answers/system[@name = '$file_n']"
			$delete_this = $xml_delete.SelectSingleNode($xpath)
			while ($delete_this -ne $null) {
				$delete_this.ParentNode.RemoveChild($delete_this)
				$delete_this = $xml_delete.SelectSingleNode($xpath)
			}
			$xml_delete.Save($path)
			[System.Windows.Forms.Application]::DoEvents()
			$Over_form.Close()
		} else { 
			[System.Windows.Forms.Application]::DoEvents()
		    $Over_form.Close() #This works
		} 
})
$Over_form.Controls.Add($Ovr_Btn_Over)

$Ovr_Btn_Re = New-Object System.Windows.Forms.Button
$Ovr_Btn_Re.Text = 'Re-Open'
$Ovr_Btn_Re.Location = New-Object System.Drawing.Point(90,102) 
$Ovr_Btn_Re.Add_click({#Use existing data in HTML form
	$xpath = "Answers/system[@name = '$file_n']"

	[xml]$qAndA = Get-Content $path

	$this_node = $qAndA.SelectSingleNode($xpath)

	#snip - doing some XML stuff here
	$Over_form.Close() #this does not work
})

$Over_form.Controls.Add($Ovr_Btn_Re)


$Ovr_Btn_Cncl = New-Object System.Windows.Forms.Button
$Ovr_Btn_Cncl.Text = 'Cancel'
$Ovr_Btn_Cncl.Location = New-Object System.Drawing.Point(170,102) 
$Ovr_Btn_Re.Add_click({
	
	$Over_form.Close() #This does not work
})
$Over_form.Controls.Add($Ovr_Btn_Cncl)




$Over_form.ShowDialog()

Why does the $Over_form.Close() not work?

Viewing all 21975 articles
Browse latest View live


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