I am trying to import a datetime from PowerShell into a SQL Table. It's the only thing stored in that table.
When I run this code: (The value stored in the variable is: 11/19/2020 09:51:40.3244656)
$location = 'path'
Set-Location $location
$c = Get-ChildItem 'path' | Sort { $_.LastWriteTime } | select -last 1 | foreach { $a = $_; $b = Get-Acl $_.FullName; Add-Member -InputObject $b -Name "LastWriteTime" -MemberType NoteProperty -Value $a.LastWriteTime; $b }
$c.LastWriteTime
$date = $c.LastWriteTime
Function Get-Datetime([datetime]$Date = $date ) {
$DT = Get-Date -Date $Date
[string]$DateTime2 = $DT.Month.ToString() + '/'
[string]$DateTime2 += $DT.Day.ToString() + '/'
[string]$DateTime2 += $DT.Year.ToString() + ' '
[string]$DateTime2 += $DT.TimeOfDay.ToString()
return $DateTime2
}
$finaldate = Get-Datetime
#$dateFormatted = $date -format
Invoke-Sqlcmd -ServerInstance "Server" -Database "db" -query "Update [server].[schema].[table] Set [columnName] = '$finaldate'"
I get this error:
Powershell Invoke-Sqlcmd : Conversion failed when converting date and/or time from character string.
How can I get the Powershell command to update the table?
Thank you for your help.
#NekoMusume helped me get to the answer to this specific question. After adding this line, (modified from #NekoMusume's comment): Thanks #NekoMusume! (If you want to answer, I'll mark it for you.)
$finaldate = Get-Date $finaldate -Format "yyyy/MM/dd HH:mm"
The code worked. Final Working code
$location = 'path'
Set-Location $location
$c = Get-ChildItem 'path' | Sort { $_.LastWriteTime } | select -last 1 | foreach { $a = $_; $b = Get-Acl $_.FullName; Add-Member -InputObject $b -Name "LastWriteTime" -MemberType NoteProperty -Value $a.LastWriteTime; $b }
$c.LastWriteTime
$date = $c.LastWriteTime
Function Get-Datetime([datetime]$Date = $date ) {
$DT = Get-Date -Date $Date
[string]$DateTime2 = $DT.Month.ToString() + '/'
[string]$DateTime2 += $DT.Day.ToString() + '/'
[string]$DateTime2 += $DT.Year.ToString() + ' '
[string]$DateTime2 += $DT.TimeOfDay.ToString()
return $DateTime2
}
$finaldate = Get-Datetime
$finaldate = Get-Date $finaldate -Format "yyyy/MM/dd HH:mm"
#$dateFormatted = $date -format
Invoke-Sqlcmd -ServerInstance "Server" -Database "db" -query "Update [server].[schema].[table] Set [columnName] = '$finaldate'"
Ok so I have my first ever powershell script and it works exactly how I want it to. The output was just to a txt file and it was bland.
Totally reworked it to give all results into a single array.
mind you there maybe a better way to do this or I may have put too much code so suggestions welcomed....
my end goal is a html with just 2 rows.... Item and Result
this is ran on a machine that will get registry settings, services startup types and local acct status.
I just cant figure out how to do a table and cycle through the arrays.
thanks for your help as it is greatly apprecaited!!!!
# Static array of registry keys
$RegKeys = #("DisableNotificationCenter","AutoConfiURL","HibernateEnabled","HideSCAHealth","NoDriveTypeAutoRun","TurnOffSidebar","EnableBaloonTips","UseDomainNameDevolution","DomainNameDevolutionlevel","*.one.ads","*","SearchOrderConfig","NoAutoRebootWithLoggedOnUsers","DisabledComponents","fAllowToGetHelp","fDenyTSConnections","EnableLUA","dontdisplaylastusername")
#Static array of service names
$Services = #("LanmanServer","MPSSVC","WinDefend","WSCSVC","TRKWKS","NAPAGENT","WUAUSERV")
#Static array of users
$Users = #("Admin","Guest")
#Registry Keys
$dnc = 'HKCU:\Software\Policies\Microsoft\Windows\Explorer'
if (Test-Path $dnc) {$dnc = (Get-ItemProperty -Path "HKCU:\Software\Policies\Microsoft\Windows\Explorer").DisableNotificationCenter}
else {$dnc = "Key not Found"}
$acu = 'HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings'
if (Test-Path $acu) {$acu = (Get-ItemProperty -Path "HKCU:\Software\Microsoft\Windows\CurrentVersion\Internet Settings").AutoConfigURL}
else {$acu = "Key not Found"}
$he = 'HKLM:\SYSTEM\CurrentControlSet\Control\Power'
if (Test-Path $he) {$he = (Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Power").HibernateEnabled}
else {$he = "Key not Found"}
$hscah = 'HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\Explorer'
if (Test-Path $hscah) {$hscah = (Get-ItemProperty -Path "HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\Explorer").HideSCAHealth}
else {$hscah = "Key not Found"}
$ndtar = 'HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\Explorer'
if (Test-Path $ndtar) {$ndtar = (Get-ItemProperty -Path "HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\Explorer").NoDriveTypeAutoRun}
else {$ndtar = "Key not Found"}
$tos = 'HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\Windows\Sidebar'
if (Test-Path $tos) {$tos = (Get-ItemProperty -Path "HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\Windows\Sidebar").TurnOffSidebar}
else {$tos = "Key not Found"}
$ebt = 'HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\Explorer\Advanced'
if (Test-Path $ebt) {$ebt = (Get-ItemProperty -Path "HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\Explorer\Advanced").EnableBaloonTips}
else {$ebt = "Key not Found"}
$udnd = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\DNSClient'
if (Test-Path $udnd) {$udnd = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\DNSClient").UseDomainNameDevolution}
else {$udnd = "Key not Found"}
$dndl = 'HKLM:\SYSTEM\CURRENTCONTROLSET\SERVICES\Dnscache\Parameters'
if (Test-Path $dndl) {$dndl = (Get-ItemProperty -Path "HKLM:\SYSTEM\CURRENTCONTROLSET\SERVICES\Dnscache\Parameters").DomainNameDevolutionlevel}
else {$dndl = "Key not Found"}
$oads = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains\bms.com\*.one.ads'
if (Test-Path $oads) {$oads = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains\bms.com\*.one.ads")."*"}
else {$oads = "Key not Found"}
$ads = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains\bms.com\*.one.ads'
if (Test-Path $ads) {$ads = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\Internet Settings\ZoneMap\Domains\bms.com\")."*"}
else {$ads = "Key not Found"}
$soc = 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\DriverSearching'
if (Test-Path $soc) {$soc = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\DriverSearching").SearchOrderConfig}
else {$soc = "Key not Found"}
$narwlou = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU'
if (Test-Path $narwlou) {$narwlou = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows\WindowsUpdate\AU").NoAutoRebootWithLoggedOnUsers}
else {$narwlou = "Key not Found"}
$dc = 'HKLM:\SYSTEM\CurrentControlSet\services\TCPIP6\Parameters'
if (Test-Path $dc) {$dc = (Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\services\TCPIP6\Parameters").DisabledComponents}
else {$dc = "Key not Found"}
$atgh = 'HKLM:\SYSTEM\CurrentControlSet\Control\Remote Assistance'
if (Test-Path $atgh) {$atgh = (Get-ItemProperty -Path "HKLM:\SYSTEM\CurrentControlSet\Control\Remote Assistance").fAllowToGetHelp}
else {$atgh = "Key not Found"}
$dtsc = 'HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services'
if (Test-Path $dtsc) {$dtsc = (Get-ItemProperty -Path "HKLM:\SOFTWARE\Policies\Microsoft\Windows NT\Terminal Services").fDenyTSConnections}
else {$dtsc = "Key not Found"}
$elua = 'HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\System'
if (Test-Path $elua) {$elua = (Get-ItemProperty -Path "HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\System").EnableLUA}
else {$elua = "Key not Found"}
$ddlun = 'HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\System'
if (Test-Path $ddlun) {$ddlun = (Get-ItemProperty -Path "HKLM:\SOFTWARE\MICROSOFT\WINDOWS\CurrentVersion\Policies\System").dontdisplaylastusername}
else {$ddlun = "Key not Found"}
#Services
$ls = (Get-WmiObject Win32_Service -filter "Name='LanmanServer'").StartMode
$mpssvc = (Get-WmiObject Win32_Service -filter "Name='MPSSVC'").StartMode
$wd = (Get-WmiObject Win32_Service -filter "Name='WinDefend'").StartMode
$wscsvc = (Get-WmiObject Win32_Service -filter "Name='WSCSVC'").StartMode
$trkwks = (Get-WmiObject Win32_Service -filter "Name='TRKWKS'").StartMode
$napagent = (Get-WmiObject Win32_Service -filter "Name='NAPAGENT'").StartMode
$wuauserv = (Get-WmiObject Win32_Service -filter "Name='WUAUSERV'").StartMode
#Local Accounts
$Adm = Get-WmiObject -Class Win32_UserAccount -Filter "LocalAccount='True' AND Name='Administrator'"
$Admin = $Adm.Disabled
$Gu = Get-WmiObject -Class Win32_UserAccount -Filter "LocalAccount='True' AND Name='Guest'"
$Guest = $Gu.Disabled
#Make individual arrays from each queried information
$RegValues = #($dnc,$acu,$he,$hscah,$ndtar,$tos,$ebt,$udnd,$dndl,$oads,$ads,$soc,$narwlou,$dc,$atgh,$dtsc,$elua,$ddlun)
$ServiceValues = #($ls,$mpssvc,$wd,$wscsvc,$trkwks,$napagent,$wuauserv)
$UsersValues = #($Admin,$Guest)
#Make array of all keys
$RegAll = #($RegKeys[0], $RegValues[0],$RegKeys[1], $RegValues[1],$RegKeys[2], $RegValues[2],$RegKeys[3], $RegValues[3], $RegKeys[4], $RegValues[4], $RegKeys[5], $RegValues[5]
$RegKeys[6], $RegValues[6], $RegKeys[7], $RegValues[7], $RegKeys[8], $RegValues[8], $RegKeys[9], $RegValues[9], $RegKeys[10], $RegValues[10]
$RegKeys[11], $RegValues[11], $RegKeys[12], $RegValues[12], $RegKeys[13], $RegValues[13], $RegKeys[14], $RegValues[14], $RegKeys[15], $RegValues[15]
$RegKeys[16], $RegValues[16], $RegKeys[17], $RegValues[17], $RegKeys[18], $RegValues[18], $Services[0], $ServiceValues[0], $Services[1], $ServiceValues[1]
, $Services[2], $ServiceValues[2], $Services[3], $ServiceValues[3], $Services[4], $ServiceValues[4], $Services[5], $ServiceValues[5], $Services[6], $ServiceValues[6],
$Users[0], $UsersValues[0], $Users[1], $UsersValues[1])
#output to html
$RegAll # | Select #{label='Item';expression={$_}} | ConvertTo-HTML -Fragment -Property 'Item' |Out-File c:\Scripts.html
This is an example which I have used in a script. You can adpt it on your script. Ask when you need help.
$YourArray = #()
#Object one for the array
$test1 = New-Object –TypeName PSObject
$test1 | Add-Member –MemberType NoteProperty –Name Propert_1 –Value "Example1"
$test1 | Add-Member –MemberType NoteProperty –Name Propert_2 –Value "Example2"
$test1 | Add-Member -MemberType NoteProperty -Name Propert_3 -Value "Example3"
#Object two for the array
$test2 = New-Object –TypeName PSObject
$test2 | Add-Member –MemberType NoteProperty –Name Propert_1 –Value "Example_2_1"
$test2 | Add-Member –MemberType NoteProperty –Name Propert_2 –Value "Example_2_2"
$test2 | Add-Member -MemberType NoteProperty -Name Propert_3 -Value "Example_2_3"
$YourArray = $test1,$test2
$beginning = {
#html code the format of the table
#'
<html>
<head>
<title>Report</title>
<STYLE type="text/css">
BODY{background-color:#b0c4de;}
TABLE{border-width: 1px;border-style: solid;border-color: black;border-collapse: collapse;}
TH{font-family:SegoeUI, sans-serif; font-size:15; border-width: 1px;padding: 3px;border-style: solid;border-color: black;background-color:#778899}
TD{font-family:Consolas, sans-serif; font-size:12; border-width: 1px;padding: 3px;border-style: solid;border-color: black;}
tr:nth-child(odd) { background-color:#d3d3d3;}
tr:nth-child(even) { background-color:white;}
</STYLE>
</head>
<h1>Stackoverflow example</h1>
<table>
<tr><th>Propert_1</th><th>Propert_2</th><th>Propert_3</th></tr>
'#
}
#Mapping between Property and table
$process = {
$Propert_1 = $_.Propert_1
$Propert_2 = $_.Propert_2
$Propert_3 = $_.Propert_3
'<tr>'
'<td bgcolor="#33CC33">{0}</td>' -f $Propert_1
'<td bgcolor="#FFFFFF">{0}</td>' -f $Propert_2
'<td bgcolor="#FFFFFF">{0}</td>' -f $Propert_3
'</tr>'
}
$end = {
#'
</table>
</html>
</body>
'#
}
#Export the array in a html sheet
$YourArray | ForEach-Object -Begin $beginning -Process $process -End $end | Out-File -FilePath "U:\Export_Report.html" -Encoding utf8
I have made a create function in windows powershell:
function create(){
param(
$searchBase = "OU=Customers,DC=test,DC=nl",
$NewOUs = #(Import-csv -Path $txt_csv.Text -Delimiter ";"),
[switch]$ProtectOU
)
$Protect = $true
If ($ProtectOU){$Protect = $true}
<# ------- CREATE OU ------- #>
foreach ($NewOU in $NewOUs) {
try {
New-ADOrganizationalUnit -Name $NewOU.company -Description $NewOU.description -Path $searchBase -ProtectedFromAccidentalDeletion $Protect
}
catch {
Write-Host "OU already exists"
}
}
$UserList = Import-Csv -Path $txt_csv.Text -Delimiter ";"
<# ------- CREATE USERS ------- #>
foreach ($User in $UserList) {
$OU = $User.path
$UPN = $User.UPN
$Password = $User.password
$Detailedname = $User.firstname + " " + $User.Lastname
$UserFirstname = $User.Firstname
$FirstLetterFirstname = $UserFirstname.substring(0,1)
$SAM = $User.UPN
$Company = $User.company
$Description = $User.description
$AccountExpirationDate = $User.accountexpirationdate
$params = #{ 'Name'=$Detailedname;
'SamAccountName'=$SAM;
'UserPrincipalName'=$UPN+'#test.nl';
'DisplayName'=$Detailedname;
'GivenName'=$UserFirstname;
'Surname'=$User.Lastname;
'AccountPassword'=(ConvertTo-SecureString $Password -AsPlainText -Force);
'Enabled'=$True;
'PasswordNeverExpires'=$True;
'Path'=$OU;
'Company'=$Company;
'Description'=$Description;
'AccountExpirationDate'=$AccountExpirationDate
'HomeDrive' = "H:"
'HomeDirectory' = "\\home\userdata$\$SAM"
'ProfilePath'="\\dc-test\User Profiles$\$SAM"
}
New-ADUser #params
}
I want this create function as a output file for example in a txt.
This is my wpf button object:
$button_add.Add_Click({create})
When I click on the button the output must generated a output file. I already tried a lot of solutions such ass:
Create | out-file but I don't get the information I want:
source: https://msdn.microsoft.com/en-us/powershell/reference/5.1/microsoft.powershell.utility/out-file
Is it possible to do this?
Kind regards
You would want to do the following:
"processing New-ADUser with $params" | Out-File log.txt -Append
try {
New-ADUser #params
"Created $UPN" | Out-File log.txt -Append
}
catch {
$_ | Out-File log.txt -Append
}
or you could just pass the output of New-ADUser to the Out-File:
New-ADUser #params -PassThru | Out-File log.txt -Append
I am trying to find all file extension in a folder and subfolders and generate a list. I found a oneliner but it do not generate the list as i want. i got mutiple of paths so i do this.
$date = get-date -Format d
$File = "C:\NoBackup\FolderPaths.txt"
foreach ($Folder in (Get-Content $File)) {
Get-ChildItem $Share -Recurse -ErrorAction SilentlyContinue | Group-Object extension | Select-Object #{Name="Folder";Expression={$Folder}}, name, #{n='TotalSize';e={$_.group | ForEach-Object -Begin {$size=0} -Process {$size += ([decimal]::round($_.Length / 1MB))} -End {"$size MB"}}} | Sort-Object -Property 'TotalSize' -Descending | Format-Table -AutoSize
}
This will give a new header foreach folder in folderpaths, and i need the result be like this
.ext1 .ext2 .ext3 .ext4
D:\Folder1 5MB 12MB 20MB 8MB
D:\Folder2 10MB 54MB 12MB 3MB
D:\Folder3 2MB 12MB 20MB 100MB
I cant find out to rewrite the code to get what i need. Hope you can help me out with this.
The script works now. I needed to change
foreach($folder in $folders)
To
foreach($folder in (Get-Content $file))
It is not short or sweet, but try this:
function ConvertTo-Units($decimal)
{
$value = [decimal]::Round($decimal/1mb,2)
$units = "MB"
if($value -eq 0)
{
$value = [decimal]::Round($decimal/1kb,2)
$units = "KB"
}
return "{0} {1}" -f $value,$units
}
$File = "C:\NoBackup\FolderPaths.txt"
$fileData = #{}
foreach ($folder in (Get-Content $file))
{
$files = Get-ChildItem $folder -Recurse -ErrorAction SilentlyContinue -File
$fileData[$folder] = $files | Select-Object extension,length | %{$h = #{}} { $h[$_.extension] += $_.length } { $h}
}
$extensions = $fileData.Keys | % { $fileData[$_].Keys } | % tolower | Select-Object -Unique | ? { $_ }
$properties = #(
#{Name="Folder";Expression={$_}}
)
$extensions | % {$properties += #{Name="$_";Expression=[scriptblock]::Create("ConvertTo-Units `$fileData[`$folder][""$_""]")}}
$result = #()
foreach($folder in $folders)
{
$result += $folder | Select-Object $properties
}
$result | ft * -AutoSize -force
function Get-NaLUNbyMap {
<#
.DESCRIPTION
Gets Lun Information for a particular initiatorgroup name & lunid
.EXAMPLE
Get-Inventory -computername server-r2
.EXAMPLE
Import-Module NaLUNbyMap
Get-NaLUNbyMap -igroup "IA" -lunid 1
#>
[CmdletBinding()]
param(
[Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
[string[]]$igroup,
[Parameter(Mandatory=$True,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
[string[]]$lunid
)
Process
{
$info = (Get-NaLun |Select #{Name="LUN";Expression={$_.path}},#{Name="Size";Expression={[math]::Round([decimal]$_.size/1gb,0)}},#{Name="OnlineStatus";Expression={$_.online}},#{Name="Group";Expression={([string]::Join(",",(Get-NaLun $_.path | get-nalunmap | select -ExpandProperty initiatorgroupname)))}},#{Name="LunID";Expression={Get-NaLun $_.path | get-nalunmap | select -ExpandProperty lunid}} | ?{$_.group -eq $igroup -and $_.lunid -eq $lunid})
return $info
}
}
Hi Im unable to return output from this function, can some one please help me out!
That is some ugly code. :(
Here is a cleaned up version. I think I found your problem. Your parameters are arrays, when they should be single values based on how you are using them.
function Get-NaLUNbyMap {
<#
.DESCRIPTION
Gets Lun Information for a particular initiatorgroup name & lunid
.EXAMPLE
Get-Inventory -computername server-r2
.EXAMPLE
Import-Module NaLUNbyMap
Get-NaLUNbyMap -igroup "IA" -lunid 1
#>
[CmdletBinding()]
param(
[Parameter(Mandatory = $True, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)]
[string]$igroup
,
[Parameter(Mandatory = $True, ValueFromPipeline = $True, ValueFromPipelineByPropertyName = $True)]
[string]$lunid
)
process {
$Luns = foreach ($Lun in Get-NaLun) {
$LunMap = Get-NaLunMap $_.Path
New-Object PSObject -Property #{
"LUN"= $_.Path
"Size" = [Math]::Round([Decimal]$_.Size / 1gb, 0)
"OnlineStatus" = $_.Online
"Group" = $LunMap | Select-Object -ExpandProperty InitiatorGroupName
"LunId" = $LunMap | Select-Object -ExpandProperty LunId
}
}
$Luns | Where-Object {$_.Group -eq $igroup -and $_.LunId -eq $lunid}
}
}